tide-commander 1.120.2 → 1.121.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{BossLogsModal-UIw_vZf7.js → BossLogsModal-B2YfEJEZ.js} +1 -1
- package/dist/assets/{BossSpawnModal-CSWW6rRF.js → BossSpawnModal-DM48J6B4.js} +1 -1
- package/dist/assets/{ControlsModal-4Xxc5EDw.js → ControlsModal-DA4RhL4J.js} +1 -1
- package/dist/assets/{DockerLogsModal-E6tUsxQp.js → DockerLogsModal-sBpMzoBW.js} +1 -1
- package/dist/assets/{EmbeddedEditor-BnxOx-pQ.js → EmbeddedEditor-B4DsIOre.js} +1 -1
- package/dist/assets/{GmailOAuthSetup-CCuz_0Jh.js → GmailOAuthSetup-P5i2x2nw.js} +1 -1
- package/dist/assets/{GoogleOAuthSetup-ovraU7is.js → GoogleOAuthSetup-DMT3PAQT.js} +1 -1
- package/dist/assets/{IframeModal-Bl7xQUot.js → IframeModal-De15ZrD-.js} +1 -1
- package/dist/assets/{IntegrationsPanel-B5FLW_4i.js → IntegrationsPanel-DnnqQ9jg.js} +2 -2
- package/dist/assets/{LogViewerModal-27S4rXu5.js → LogViewerModal-CxqxaPTn.js} +1 -1
- package/dist/assets/{MonitoringModal-B2e5qRlI.js → MonitoringModal-Sx_u2A3-.js} +1 -1
- package/dist/assets/{PM2LogsModal-DHOdlVKj.js → PM2LogsModal-BVUiu0y3.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-klOACnuZ.js → RestoreArchivedAreaModal-nhGd5mU0.js} +1 -1
- package/dist/assets/{Scene2DCanvas-DgHW6t8b.js → Scene2DCanvas-H4ZMjV2J.js} +1 -1
- package/dist/assets/{SceneManager-lJ5xvrtG.js → SceneManager-Cxww9Amy.js} +1 -1
- package/dist/assets/{SkillsPanel-4xN9yDmZ.js → SkillsPanel-w_4Yp-3y.js} +1 -1
- package/dist/assets/{SlackMultiInstanceSetup-DetD-qvf.js → SlackMultiInstanceSetup-1AODop87.js} +1 -1
- package/dist/assets/{SpawnModal-C6yizyBZ.js → SpawnModal-ByT366Qe.js} +1 -1
- package/dist/assets/{StatisticsModal-CERiPndF.js → StatisticsModal-C2AtvNBi.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-CqEUJYOu.js → SubordinateAssignmentModal-Djuc1Qzv.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-BNL5A1_2.js → TriggerManagerPanel-CZqweJiZ.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-nooqShgn.js → WorkflowEditorPanel-CdFuJVr6.js} +1 -1
- package/dist/assets/{area-logos-DBPYTfWz.js → area-logos-CAaQMgNQ.js} +1 -1
- package/dist/assets/{index-DR9efKHS.js → index-Bthl5h2s.js} +1 -1
- package/dist/assets/{index-DvNc44bt.js → index-CBHWkTIB.js} +1 -1
- package/dist/assets/{index-mOCIfT5x.js → index-CIZTb6i1.js} +1 -1
- package/dist/assets/{index-DLDNoo2_.js → index-CNtNymjx.js} +2 -2
- package/dist/assets/{index-BeVbMyTE.js → index-D1URvPh1.js} +1 -1
- package/dist/assets/{index-Bcw0MYRz.js → index-D8kPhHUs.js} +1 -1
- package/dist/assets/{index-ycT4NXuE.css → index-DW3TlTFY.css} +1 -1
- package/dist/assets/{index-DIehEg3Z.js → index-Dudpmrz0.js} +1 -1
- package/dist/assets/{index-Ddg5qVmi.js → index-TX8bidMy.js} +3 -3
- package/dist/assets/{index-CZOZp8K8.js → index-tpgIJsjD.js} +1 -1
- package/dist/assets/{main-DdMBRxlZ.js → main-B8YPZvpg.js} +4 -4
- package/dist/assets/main-C7Dsh8es.css +1 -0
- package/dist/assets/{web-CQBWIN_w.js → web-B9FRdWR_.js} +1 -1
- package/dist/assets/{web-7bMYrF50.js → web-BgeuoMBy.js} +1 -1
- package/dist/assets/{web-DwY7udDt.js → web-BlddCYpD.js} +1 -1
- package/dist/index.html +2 -2
- package/dist/src/packages/server/routes/browser.js +74 -26
- package/dist/src/packages/server/services/browser-bridge-service.js +13 -0
- package/dist/src/packages/server/websocket/handler.js +22 -1
- package/package.json +1 -1
- package/dist/assets/main-HobQlAS4.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as l,b1 as Re,b2 as Ye,j as e,I as L,u as Y,b3 as as,ab as ns,f as Ve,s as T,b4 as hs,b5 as ms,aW as gs,b6 as fs,C as he,G as oe,H as Z,h as je,i as ke,m as xs,b7 as bs,b8 as js,b9 as vs,ba as ws,P as Ns,bb as Se,a6 as ys,bc as is,bd as ks,be as Be,bf as Ss,bg as Cs,bh as As,bi as Ts,bj as _s,bk as Is,bl as Es,aQ as Ps,W as Ls,S as ye,bm as $s,bn as Ds,aS as Fs,bo as Ue,X as Ee,a_ as Os,bp as ze,bq as Rs}from"./main-DdMBRxlZ.js";import{g as Us,d as zs,u as Ms}from"./area-logos-DBPYTfWz.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Bs=`https://api.github.com/repos/${Ke}/releases/latest`,Vs=`https://api.github.com/repos/${Ke}/releases?per_page=3`,Ks=3600*1e3,Je="app_update_dismissed_version",Ze="1.120.2";function Hs(){var y,C;const[s,i]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),t=((C=(y=Re)==null?void 0:y.getPlatform)==null?void 0:C.call(y))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),d=(u,p)=>{const g=o(u),v=o(p),j=Math.max(g.length,v.length);for(let m=0;m<j;m++){const k=g[m]||0,$=v[m]||0;if(k>$)return 1;if(k<$)return-1}return 0},r=async u=>{var g,v;if(Re&&Ye&&((v=(g=Re).isNativePlatform)==null?void 0:v.call(g))===!0){const j=await Ye.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:j.data,status:j.status}}else{const j=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return j.ok?{data:await j.json(),status:j.status}:{data:null,status:j.status}}},c=l.useCallback(async(u=!1)=>{i(p=>({...p,isChecking:!0,error:null}));try{const[p,g]=await Promise.all([r(Bs),r(Vs)]);if(p.status!==200)throw new Error(`GitHub API error: ${p.status}`);const v=p.data,j=v.tag_name;let m=[];g.status===200&&g.data&&(m=g.data.map(w=>({version:w.tag_name,name:w.name,publishedAt:w.published_at,releaseUrl:w.html_url})));const k=localStorage.getItem(Je);if(!u&&k===j)return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;if(!(d(j,Ze)>0))return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;const I=v.assets.find(w=>w.name.endsWith(".apk")&&w.content_type==="application/vnd.android.package-archive"),V={version:j,name:v.name,changelog:v.body,releaseUrl:v.html_url,apkUrl:(I==null?void 0:I.browser_download_url)||null,apkSize:(I==null?void 0:I.size)||null,publishedAt:v.published_at};return i(w=>({...w,isChecking:!1,updateAvailable:!0,updateInfo:V,recentReleases:m})),V}catch(p){const g=p instanceof Error?p.message:"Failed to check for updates";return i(v=>({...v,isChecking:!1,error:g})),null}},[]),f=l.useCallback(async()=>{var u,p,g;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(p=s.updateInfo)!=null&&p.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),i(v=>({...v,error:null}))}catch(v){const j=v instanceof Error?v.message:"Failed to open download";i(m=>({...m,error:j}))}},[s.updateInfo,t]),a=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),i(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),x=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),p=setInterval(()=>{c()},Ks);return()=>{clearTimeout(u),clearInterval(p)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:f,dismissUpdate:a,openReleasePage:x}}const os="tide-toolbox-collapse";function Ws(s,i){try{const t=localStorage.getItem(`${os}-${s}`);if(t!==null)return t==="true"}catch{}return i}function qs(s,i){try{localStorage.setItem(`${os}-${s}`,String(i))}catch{}}function K({title:s,storageKey:i,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,f]=l.useState(()=>i?Ws(i,t):t),a=()=>{const y=!c;f(y),i&&qs(i,y)},x=o||c;return e.jsxs("div",{className:`collapsible-section ${x?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:a,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(L,{name:x?"caret-down":"caret-right",size:10})})]})]}),x&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Gs({area:s,isSelected:i,onClick:t,onDelete:o}){const{t:d}=Y(["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 ${i?"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 Ys({building:s,isSelected:i,onClick:t,onEdit:o}){var f;const{t:d}=Y(["config"]),r=((f=s.pm2Status)==null?void 0:f.ports)||[],c=(a,x)=>{a.stopPropagation(),window.open(`http://${window.location.hostname}:${x}`,"_blank")};return e.jsxs("div",{className:`building-item ${i?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:as[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(L,{name:ns(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(a=>e.jsxs("a",{href:`http://${window.location.hostname}:${a}`,className:"building-port-link",onClick:x=>c(x,a),title:`Open :${a}`,children:[":",a]},a))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:a=>{a.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx(L,{name:"gear",size:14})})]})}function Js({building:s,onClose:i,onOpenModal:t}){var x,y,C,u,p,g,v,j;const{t:o}=Y(["config","common"]),{buildingLogs:d}=Ve(),r=T.getBuildingLogs(s.id),c=hs[s.style||"server-rack"],f=m=>{T.sendBuildingCommand(s.id,m)},a=m=>{window.open(m,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx(L,{name:ns(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:as[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:i,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:()=>f("start"),disabled:!((x=s.commands)!=null&&x.start)||s.status==="running",title:((y=s.commands)==null?void 0:y.start)||o("config:buildings.noStartCommand"),children:[e.jsx(L,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>f("stop"),disabled:!((C=s.commands)!=null&&C.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx(L,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>f("restart"),disabled:!((p=s.commands)!=null&&p.restart),title:((g=s.commands)==null?void 0:g.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx(L,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>f("healthCheck"),disabled:!((v=s.commands)!=null&&v.healthCheck),title:((j=s.commands)==null?void 0:j.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx(L,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((m,k)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>a(m.url),title:m.url,children:[e.jsx(L,{name:"link",size:12})," ",m.label||m.url]},k))})]}),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:()=>T.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((m,k)=>e.jsx("div",{className:"building-editor-log-entry",children:m},k))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(L,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Zs=[{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 Xs({area:s,onClose:i,onOpenFolder:t}){var Q;const{t:o}=Y(["config","common"]),[d,r]=l.useState(s.name),[c,f]=l.useState(s.prompt||""),[a,x]=l.useState(!1),[y,C]=l.useState(""),[u,p]=l.useState(!1),g=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{f(s.prompt||"")},[s.id,s.prompt]);const v=N=>{const D=N.target.value;r(D),T.updateArea(s.id,{name:D})},j=N=>{T.updateArea(s.id,{color:N})},m=N=>{const D=N.target.value;f(D),T.updateArea(s.id,{prompt:D})},k=()=>{y.trim()&&(T.addDirectoryToArea(s.id,y.trim()),C(""),x(!1))},$=(N,D)=>{D.stopPropagation(),T.removeDirectoryFromArea(s.id,N)},I=()=>{T.bringAreaToFront(s.id)},V=()=>{T.sendAreaToBack(s.id)},w=l.useCallback(()=>{let N=2,D=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,D=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,D=s.radius*1.414);const B=Math.min(N,D)*.4;return{width:Math.round(B*10)/10,height:Math.round(B*10)/10}},[s.type,s.width,s.height,s.radius]),O=async N=>{var B;const D=(B=N.target.files)==null?void 0:B[0];if(D){p(!0);try{const h=await Ms(s.id,D),E=w();T.updateArea(s.id,{logo:{filename:h.filename,position:"center",width:E.width,height:E.height,keepAspectRatio:!0,opacity:.8}})}catch(h){console.error("Failed to upload logo:",h)}finally{p(!1),g.current&&(g.current.value="")}}},z=async()=>{try{await zs(s.id),T.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},H=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,position:N}})},S=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const B=s.logo.height/s.logo.width;T.updateArea(s.id,{logo:{...s.logo,width:D,height:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,width:D}})},R=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const B=s.logo.width/s.logo.height;T.updateArea(s.id,{logo:{...s.logo,height:D,width:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,height:D}})},W=()=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},J=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(N.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:i,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:v,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:ms.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>j(N),"aria-label":`Set area color ${N}`,"aria-pressed":s.color===N,title:N},N))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:I,title:o("config:areas.bringToFront"),children:[e.jsx(L,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:V,title:o("config:areas.sendToBack"),children:[e.jsx(L,{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:[(Q=s.logo)!=null&&Q.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:Us(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:z,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":e.jsx(L,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Zs.map(({key:N,labelKey:D})=>{var B;return e.jsx("button",{className:`area-logo-pos-btn ${((B=s.logo)==null?void 0:B.position)===N?"active":""}`,onClick:()=>H(N),children:o(`config:areas.${D}`)},N)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:S,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:W}),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:J,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:g,type:"file",accept:"image/*",style:{display:"none"},onChange:O})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(N=>e.jsxs("div",{className:"area-folder-item",title:N,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx(L,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:D=>$(N,D),title:o("config:areas.removeFolder"),children:"×"})]},N)),a?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(gs,{value:y,onChange:C,onSubmit:k,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:k,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>x(!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:m,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 Qs(){const{t:s}=Y(["config","common"]),i=fs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,f]=l.useState({name:"",key:"",value:"",description:""}),[a,x]=l.useState(null),y=()=>{o(!0),r(null),f({name:"",key:"",value:"",description:""})},C=m=>{r(m.id),o(!1),f({name:m.name,key:m.key,value:m.value,description:m.description||""})},u=()=>{o(!1),r(null),f({name:"",key:"",value:"",description:""})},p=()=>{!c.name.trim()||!c.key.trim()||(d?T.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}):T.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())},g=m=>{x(m)},v=()=>{a&&(T.deleteSecret(a),d===a&&u())},j=m=>{navigator.clipboard.writeText(`{{${m}}}`)};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:i.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):i.map(m=>e.jsxs("div",{className:`secret-item ${d===m.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:m.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>j(m.key),title:s("config:secrets.copyPlaceholder"),children:`{{${m.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>C(m),title:s("common:buttons.edit"),children:e.jsx(L,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>g(m.id),title:s("common:buttons.delete"),children:"×"})]})]}),m.description&&e.jsx("div",{className:"secret-item-description",children:m.description})]},m.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:m=>f({...c,name:m.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:m=>f({...c,key:m.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:m=>f({...c,value:m.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:m=>f({...c,description:m.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:y,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:a!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:v,onClose:()=>x(null)})]})}async function et(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch echo prompt setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function st(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function tt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch codex binary path: ${i.statusText}`);return(await i.json()).path||""}async function at(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function nt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch tmux mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function it(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function ot(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch interactive mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function lt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function ct(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch backup status: ${i.statusText}`);return i.json()}async function rt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},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 dt({checked:s,onChange:i,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=>i(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ut(){const{t:s}=Y(["config","common"]),[i,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[f,a]=l.useState(!1),[x,y]=l.useState(!1),[C,u]=l.useState(null),[p,g]=l.useState(null),[v,j]=l.useState(null),[m,k]=l.useState(null),[$,I]=l.useState(!1),[V,w]=l.useState(null);l.useEffect(()=>{je(ke("/api/config/categories")).then(h=>h.json()).then(h=>{const E=Array.isArray(h)?h:[];t(E),d(new Set(E.map(F=>F.id)))}).catch(h=>console.error("Failed to fetch config categories:",h))},[]),l.useEffect(()=>{ct().then(k).catch(h=>{console.error("Failed to fetch backup status:",h),w(h.message||"Failed to fetch backup status")})},[]);const O=async h=>{if(!$){I(!0),w(null);try{const E=await rt(h);k(E)}catch(E){w(E.message||"Failed to update backup setting")}finally{I(!1)}}},z=h=>{d(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},H=h=>{c(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},S=()=>d(new Set(i.map(h=>h.id))),R=()=>d(new Set),W=()=>{p&&c(new Set(p.categories.map(h=>h.id)))},J=()=>c(new Set),Q=async()=>{var h;if(o.size!==0){a(!0),j(null);try{const E=Array.from(o).join(","),F=await je(ke(`/api/config/export?categories=${E}`));if(!F.ok)throw new Error("Export failed");const ee=await F.blob(),se=window.URL.createObjectURL(ee),X=document.createElement("a");X.href=se;const A=F.headers.get("Content-Disposition"),q=((h=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:h[1])||"tide-commander-config.zip";X.download=q,document.body.appendChild(X),X.click(),document.body.removeChild(X),window.URL.revokeObjectURL(se),j({type:"success",text:s("config:data.exportSuccess")})}catch(E){j({type:"error",text:E.message||"Export failed"})}finally{a(!1)}}},N=async h=>{var F;const E=(F=h.target.files)==null?void 0:F[0];if(E){u(E),j(null),g(null),c(new Set);try{const ee=await je(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await E.arrayBuffer()});if(!ee.ok){const A=await ee.json();throw new Error(A.error||"Failed to preview config file")}const se=await ee.json(),X=Array.isArray(se.categories)?se.categories:[];g({...se,categories:X}),c(new Set(X.map(A=>A.id)))}catch(ee){j({type:"error",text:ee.message||"Failed to read config file"}),u(null)}}},D=async()=>{if(!(!C||r.size===0)){y(!0),j(null);try{const h=Array.from(r).join(","),E=await je(ke(`/api/config/import?categories=${h}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await C.arrayBuffer()}),F=await E.json();if(!E.ok)throw new Error(F.error||"Import failed");j({type:"success",text:F.message||s("config:data.importSuccess")}),u(null),g(null),c(new Set)}catch(h){j({type:"error",text:h.message||"Import failed"})}finally{y(!1)}}},B=()=>{u(null),g(null),c(new Set),j(null)};return e.jsxs("div",{className:"data-section",children:[v&&e.jsx("div",{className:`data-message data-message-${v.type}`,children:v.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(dt,{checked:!!(m!=null&&m.enabled),disabled:$||!m,onChange:O})]}),e.jsxs("div",{className:"data-backup-info",children:[m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:m.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!m.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:m.scriptPath})]}),m.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(m.lastRunAt).toLocaleString(),m.lastRunOk===!0&&" — ok",m.lastRunOk===!1&&m.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",m.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),V&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:V})]})]}),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:S,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:i.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(h.id),onChange:()=>z(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name})]},h.id))}),e.jsx("button",{className:"data-action-btn export",onClick:Q,disabled:f||o.size===0,children:f?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")})}),C?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:C.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:W,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:J,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:p.categories.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(h.id),onChange:()=>H(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name}),h.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",h.fileCount," ",s("config:data.files"),")"]})]},h.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:B,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:D,disabled:x||r.size===0,children:x?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:N,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function pt(){const s=await je(`${Z()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function ht(s,i){const t=new AbortController;return(async()=>{try{const o=await fetch(xs(`${Z()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const f=await o.text().catch(()=>"");let a=null;try{a=JSON.parse(f)}catch{}const x=a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"?a.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:x}),i(new Error(x));return}const d=o.body.getReader(),r=new TextDecoder("utf-8");let c="";for(;;){const{value:f,done:a}=await d.read();if(a)break;c+=r.decode(f,{stream:!0});let x=c.indexOf(`
|
|
1
|
+
import{r as l,b1 as Re,b2 as Ye,j as e,I as L,u as Y,b3 as as,ab as ns,f as Ve,s as T,b4 as hs,b5 as ms,aW as gs,b6 as fs,C as he,G as oe,H as Z,h as je,i as ke,m as xs,b7 as bs,b8 as js,b9 as vs,ba as ws,P as Ns,bb as Se,a6 as ys,bc as is,bd as ks,be as Be,bf as Ss,bg as Cs,bh as As,bi as Ts,bj as _s,bk as Is,bl as Es,aQ as Ps,W as Ls,S as ye,bm as $s,bn as Ds,aS as Fs,bo as Ue,X as Ee,a_ as Os,bp as ze,bq as Rs}from"./main-B8YPZvpg.js";import{g as Us,d as zs,u as Ms}from"./area-logos-CAaQMgNQ.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Bs=`https://api.github.com/repos/${Ke}/releases/latest`,Vs=`https://api.github.com/repos/${Ke}/releases?per_page=3`,Ks=3600*1e3,Je="app_update_dismissed_version",Ze="1.121.0";function Hs(){var y,C;const[s,i]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),t=((C=(y=Re)==null?void 0:y.getPlatform)==null?void 0:C.call(y))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),d=(u,p)=>{const g=o(u),v=o(p),j=Math.max(g.length,v.length);for(let m=0;m<j;m++){const k=g[m]||0,$=v[m]||0;if(k>$)return 1;if(k<$)return-1}return 0},r=async u=>{var g,v;if(Re&&Ye&&((v=(g=Re).isNativePlatform)==null?void 0:v.call(g))===!0){const j=await Ye.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:j.data,status:j.status}}else{const j=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return j.ok?{data:await j.json(),status:j.status}:{data:null,status:j.status}}},c=l.useCallback(async(u=!1)=>{i(p=>({...p,isChecking:!0,error:null}));try{const[p,g]=await Promise.all([r(Bs),r(Vs)]);if(p.status!==200)throw new Error(`GitHub API error: ${p.status}`);const v=p.data,j=v.tag_name;let m=[];g.status===200&&g.data&&(m=g.data.map(w=>({version:w.tag_name,name:w.name,publishedAt:w.published_at,releaseUrl:w.html_url})));const k=localStorage.getItem(Je);if(!u&&k===j)return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;if(!(d(j,Ze)>0))return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;const I=v.assets.find(w=>w.name.endsWith(".apk")&&w.content_type==="application/vnd.android.package-archive"),V={version:j,name:v.name,changelog:v.body,releaseUrl:v.html_url,apkUrl:(I==null?void 0:I.browser_download_url)||null,apkSize:(I==null?void 0:I.size)||null,publishedAt:v.published_at};return i(w=>({...w,isChecking:!1,updateAvailable:!0,updateInfo:V,recentReleases:m})),V}catch(p){const g=p instanceof Error?p.message:"Failed to check for updates";return i(v=>({...v,isChecking:!1,error:g})),null}},[]),f=l.useCallback(async()=>{var u,p,g;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(p=s.updateInfo)!=null&&p.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),i(v=>({...v,error:null}))}catch(v){const j=v instanceof Error?v.message:"Failed to open download";i(m=>({...m,error:j}))}},[s.updateInfo,t]),a=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),i(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),x=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),p=setInterval(()=>{c()},Ks);return()=>{clearTimeout(u),clearInterval(p)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:f,dismissUpdate:a,openReleasePage:x}}const os="tide-toolbox-collapse";function Ws(s,i){try{const t=localStorage.getItem(`${os}-${s}`);if(t!==null)return t==="true"}catch{}return i}function qs(s,i){try{localStorage.setItem(`${os}-${s}`,String(i))}catch{}}function K({title:s,storageKey:i,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,f]=l.useState(()=>i?Ws(i,t):t),a=()=>{const y=!c;f(y),i&&qs(i,y)},x=o||c;return e.jsxs("div",{className:`collapsible-section ${x?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:a,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(L,{name:x?"caret-down":"caret-right",size:10})})]})]}),x&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Gs({area:s,isSelected:i,onClick:t,onDelete:o}){const{t:d}=Y(["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 ${i?"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 Ys({building:s,isSelected:i,onClick:t,onEdit:o}){var f;const{t:d}=Y(["config"]),r=((f=s.pm2Status)==null?void 0:f.ports)||[],c=(a,x)=>{a.stopPropagation(),window.open(`http://${window.location.hostname}:${x}`,"_blank")};return e.jsxs("div",{className:`building-item ${i?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:as[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(L,{name:ns(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(a=>e.jsxs("a",{href:`http://${window.location.hostname}:${a}`,className:"building-port-link",onClick:x=>c(x,a),title:`Open :${a}`,children:[":",a]},a))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:a=>{a.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx(L,{name:"gear",size:14})})]})}function Js({building:s,onClose:i,onOpenModal:t}){var x,y,C,u,p,g,v,j;const{t:o}=Y(["config","common"]),{buildingLogs:d}=Ve(),r=T.getBuildingLogs(s.id),c=hs[s.style||"server-rack"],f=m=>{T.sendBuildingCommand(s.id,m)},a=m=>{window.open(m,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx(L,{name:ns(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:as[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:i,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:()=>f("start"),disabled:!((x=s.commands)!=null&&x.start)||s.status==="running",title:((y=s.commands)==null?void 0:y.start)||o("config:buildings.noStartCommand"),children:[e.jsx(L,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>f("stop"),disabled:!((C=s.commands)!=null&&C.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx(L,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>f("restart"),disabled:!((p=s.commands)!=null&&p.restart),title:((g=s.commands)==null?void 0:g.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx(L,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>f("healthCheck"),disabled:!((v=s.commands)!=null&&v.healthCheck),title:((j=s.commands)==null?void 0:j.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx(L,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((m,k)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>a(m.url),title:m.url,children:[e.jsx(L,{name:"link",size:12})," ",m.label||m.url]},k))})]}),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:()=>T.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((m,k)=>e.jsx("div",{className:"building-editor-log-entry",children:m},k))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(L,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Zs=[{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 Xs({area:s,onClose:i,onOpenFolder:t}){var Q;const{t:o}=Y(["config","common"]),[d,r]=l.useState(s.name),[c,f]=l.useState(s.prompt||""),[a,x]=l.useState(!1),[y,C]=l.useState(""),[u,p]=l.useState(!1),g=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{f(s.prompt||"")},[s.id,s.prompt]);const v=N=>{const D=N.target.value;r(D),T.updateArea(s.id,{name:D})},j=N=>{T.updateArea(s.id,{color:N})},m=N=>{const D=N.target.value;f(D),T.updateArea(s.id,{prompt:D})},k=()=>{y.trim()&&(T.addDirectoryToArea(s.id,y.trim()),C(""),x(!1))},$=(N,D)=>{D.stopPropagation(),T.removeDirectoryFromArea(s.id,N)},I=()=>{T.bringAreaToFront(s.id)},V=()=>{T.sendAreaToBack(s.id)},w=l.useCallback(()=>{let N=2,D=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,D=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,D=s.radius*1.414);const B=Math.min(N,D)*.4;return{width:Math.round(B*10)/10,height:Math.round(B*10)/10}},[s.type,s.width,s.height,s.radius]),O=async N=>{var B;const D=(B=N.target.files)==null?void 0:B[0];if(D){p(!0);try{const h=await Ms(s.id,D),E=w();T.updateArea(s.id,{logo:{filename:h.filename,position:"center",width:E.width,height:E.height,keepAspectRatio:!0,opacity:.8}})}catch(h){console.error("Failed to upload logo:",h)}finally{p(!1),g.current&&(g.current.value="")}}},z=async()=>{try{await zs(s.id),T.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},H=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,position:N}})},S=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const B=s.logo.height/s.logo.width;T.updateArea(s.id,{logo:{...s.logo,width:D,height:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,width:D}})},R=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const B=s.logo.width/s.logo.height;T.updateArea(s.id,{logo:{...s.logo,height:D,width:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,height:D}})},W=()=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},J=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(N.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:i,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:v,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:ms.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>j(N),"aria-label":`Set area color ${N}`,"aria-pressed":s.color===N,title:N},N))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:I,title:o("config:areas.bringToFront"),children:[e.jsx(L,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:V,title:o("config:areas.sendToBack"),children:[e.jsx(L,{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:[(Q=s.logo)!=null&&Q.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:Us(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:z,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":e.jsx(L,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Zs.map(({key:N,labelKey:D})=>{var B;return e.jsx("button",{className:`area-logo-pos-btn ${((B=s.logo)==null?void 0:B.position)===N?"active":""}`,onClick:()=>H(N),children:o(`config:areas.${D}`)},N)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:S,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:W}),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:J,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:g,type:"file",accept:"image/*",style:{display:"none"},onChange:O})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(N=>e.jsxs("div",{className:"area-folder-item",title:N,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx(L,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:D=>$(N,D),title:o("config:areas.removeFolder"),children:"×"})]},N)),a?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(gs,{value:y,onChange:C,onSubmit:k,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:k,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>x(!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:m,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 Qs(){const{t:s}=Y(["config","common"]),i=fs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,f]=l.useState({name:"",key:"",value:"",description:""}),[a,x]=l.useState(null),y=()=>{o(!0),r(null),f({name:"",key:"",value:"",description:""})},C=m=>{r(m.id),o(!1),f({name:m.name,key:m.key,value:m.value,description:m.description||""})},u=()=>{o(!1),r(null),f({name:"",key:"",value:"",description:""})},p=()=>{!c.name.trim()||!c.key.trim()||(d?T.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}):T.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())},g=m=>{x(m)},v=()=>{a&&(T.deleteSecret(a),d===a&&u())},j=m=>{navigator.clipboard.writeText(`{{${m}}}`)};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:i.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):i.map(m=>e.jsxs("div",{className:`secret-item ${d===m.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:m.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>j(m.key),title:s("config:secrets.copyPlaceholder"),children:`{{${m.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>C(m),title:s("common:buttons.edit"),children:e.jsx(L,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>g(m.id),title:s("common:buttons.delete"),children:"×"})]})]}),m.description&&e.jsx("div",{className:"secret-item-description",children:m.description})]},m.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:m=>f({...c,name:m.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:m=>f({...c,key:m.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:m=>f({...c,value:m.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:m=>f({...c,description:m.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:y,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:a!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:v,onClose:()=>x(null)})]})}async function et(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch echo prompt setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function st(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function tt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch codex binary path: ${i.statusText}`);return(await i.json()).path||""}async function at(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function nt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch tmux mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function it(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function ot(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch interactive mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function lt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function ct(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch backup status: ${i.statusText}`);return i.json()}async function rt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},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 dt({checked:s,onChange:i,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=>i(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ut(){const{t:s}=Y(["config","common"]),[i,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[f,a]=l.useState(!1),[x,y]=l.useState(!1),[C,u]=l.useState(null),[p,g]=l.useState(null),[v,j]=l.useState(null),[m,k]=l.useState(null),[$,I]=l.useState(!1),[V,w]=l.useState(null);l.useEffect(()=>{je(ke("/api/config/categories")).then(h=>h.json()).then(h=>{const E=Array.isArray(h)?h:[];t(E),d(new Set(E.map(F=>F.id)))}).catch(h=>console.error("Failed to fetch config categories:",h))},[]),l.useEffect(()=>{ct().then(k).catch(h=>{console.error("Failed to fetch backup status:",h),w(h.message||"Failed to fetch backup status")})},[]);const O=async h=>{if(!$){I(!0),w(null);try{const E=await rt(h);k(E)}catch(E){w(E.message||"Failed to update backup setting")}finally{I(!1)}}},z=h=>{d(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},H=h=>{c(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},S=()=>d(new Set(i.map(h=>h.id))),R=()=>d(new Set),W=()=>{p&&c(new Set(p.categories.map(h=>h.id)))},J=()=>c(new Set),Q=async()=>{var h;if(o.size!==0){a(!0),j(null);try{const E=Array.from(o).join(","),F=await je(ke(`/api/config/export?categories=${E}`));if(!F.ok)throw new Error("Export failed");const ee=await F.blob(),se=window.URL.createObjectURL(ee),X=document.createElement("a");X.href=se;const A=F.headers.get("Content-Disposition"),q=((h=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:h[1])||"tide-commander-config.zip";X.download=q,document.body.appendChild(X),X.click(),document.body.removeChild(X),window.URL.revokeObjectURL(se),j({type:"success",text:s("config:data.exportSuccess")})}catch(E){j({type:"error",text:E.message||"Export failed"})}finally{a(!1)}}},N=async h=>{var F;const E=(F=h.target.files)==null?void 0:F[0];if(E){u(E),j(null),g(null),c(new Set);try{const ee=await je(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await E.arrayBuffer()});if(!ee.ok){const A=await ee.json();throw new Error(A.error||"Failed to preview config file")}const se=await ee.json(),X=Array.isArray(se.categories)?se.categories:[];g({...se,categories:X}),c(new Set(X.map(A=>A.id)))}catch(ee){j({type:"error",text:ee.message||"Failed to read config file"}),u(null)}}},D=async()=>{if(!(!C||r.size===0)){y(!0),j(null);try{const h=Array.from(r).join(","),E=await je(ke(`/api/config/import?categories=${h}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await C.arrayBuffer()}),F=await E.json();if(!E.ok)throw new Error(F.error||"Import failed");j({type:"success",text:F.message||s("config:data.importSuccess")}),u(null),g(null),c(new Set)}catch(h){j({type:"error",text:h.message||"Import failed"})}finally{y(!1)}}},B=()=>{u(null),g(null),c(new Set),j(null)};return e.jsxs("div",{className:"data-section",children:[v&&e.jsx("div",{className:`data-message data-message-${v.type}`,children:v.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(dt,{checked:!!(m!=null&&m.enabled),disabled:$||!m,onChange:O})]}),e.jsxs("div",{className:"data-backup-info",children:[m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:m.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!m.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:m.scriptPath})]}),m.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(m.lastRunAt).toLocaleString(),m.lastRunOk===!0&&" — ok",m.lastRunOk===!1&&m.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",m.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),V&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:V})]})]}),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:S,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:i.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(h.id),onChange:()=>z(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name})]},h.id))}),e.jsx("button",{className:"data-action-btn export",onClick:Q,disabled:f||o.size===0,children:f?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")})}),C?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:C.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:W,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:J,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:p.categories.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(h.id),onChange:()=>H(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name}),h.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",h.fileCount," ",s("config:data.files"),")"]})]},h.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:B,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:D,disabled:x||r.size===0,children:x?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:N,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function pt(){const s=await je(`${Z()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function ht(s,i){const t=new AbortController;return(async()=>{try{const o=await fetch(xs(`${Z()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const f=await o.text().catch(()=>"");let a=null;try{a=JSON.parse(f)}catch{}const x=a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"?a.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:x}),i(new Error(x));return}const d=o.body.getReader(),r=new TextDecoder("utf-8");let c="";for(;;){const{value:f,done:a}=await d.read();if(a)break;c+=r.decode(f,{stream:!0});let x=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`);for(;x!==-1;){const y=c.slice(0,x);c=c.slice(x+2);const C=y.split(`
|
|
4
4
|
`);let u="message",p="";for(const g of C)g.startsWith(":")||(g.startsWith("event:")?u=g.slice(6).trim():g.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 s,h as Y,i as K,G as Kt,Z as $s,S as Rt,_ as Hs,s as mt,u as le,j as e,I as M,bG as Ft,f as zs,bH as As,bI as Rn,bJ as Os,bK as Gs,bL as Fn,bM as In,bN as Tt,bO as Pn,bP as Ln,bQ as $n,bR as Xt,bS as Hn,bT as Us,bU as Mt,bV as Dt,ak as it,bW as ft,bX as pt,bY as Es,bZ as zn,bb as An,b_ as Jt,b$ as On,c0 as Gn,c1 as Ss,C as Un,o as Bn}from"./main-DdMBRxlZ.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function _n(t){const[n,o]=s.useState(null),[c,r]=s.useState(!1),i=s.useCallback(async()=>{if(t){r(!0);try{const f=await Y(K(`/api/files/git-status?path=${encodeURIComponent(t)}`)),l=await f.json();f.ok?o(l):o({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),o({isGitRepo:!1,files:[]})}finally{r(!1)}}},[t]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Vn(t){try{const n=await Y(K(`/api/files/git-original?path=${encodeURIComponent(t)}`)),o=await n.json();return n.ok&&!o.isNew?{content:o.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Kn=new Set([".txt",".md",".markdown",".json",".yaml",".yml",".xml",".html",".htm",".css",".scss",".sass",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".c",".cpp",".h",".hpp",".cs",".go",".rs",".swift",".kt",".scala",".clj",".ex",".exs",".erl",".hs",".ml",".fs",".sql",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".toml",".ini",".cfg",".conf",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".babelrc",".log",".csv",".tsv",".svg",""]),Wn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Yn=new Set([".pdf"]),qn=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".zip",".tar",".gz",".rar",".7z",".exe",".dmg",".app",".deb",".rpm",".apk",".aab",".ipa",".msi",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".webm",".ttf",".otf",".woff",".woff2",".eot",".sqlite",".db",".so",".dll",".dylib",".a",".o",".obj",".bin",".dat",".iso",".img",".jar",".war",".ear",".class"]);function Jn(t){const n=t.toLowerCase();return Wn.has(n)?"image":Yn.has(n)?"pdf":qn.has(n)?"binary":(Kn.has(n),"text")}function Xn(){const[t,n]=s.useState(null),[o,c]=s.useState(!1),[r,i]=s.useState(null),f=s.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),y=Jn(p),C=u.substring(u.lastIndexOf("/")+1);if(y==="image"){const N=await Y(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!N.ok){const w=await N.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await N.blob(),v=URL.createObjectURL(d);n({path:u,filename:C,extension:p,content:"",size:d.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(y==="pdf"){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load PDF info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"pdf",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&token=${encodeURIComponent(Kt())}`)});return}if(y==="binary"){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load file info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Kt())}`)});return}const R=await Y(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await R.json();if(!R.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(N.ok){n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Kt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const y=p instanceof Error?p.message:"Failed to load file";i(y),n(null)}finally{c(!1)}},[]),l=s.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:t,loading:o,error:r,loadFile:f,clearFile:l,setFile:n}}const Wt="file-explorer-state",Qn=10080*60*1e3;function Zn(t,n){return n?`${Wt}-folder-${n}`:t?`${Wt}-area-${t}`:`${Wt}-default`}async function ea(t){try{const n=await Y(K(`/api/files/exists?path=${encodeURIComponent(t)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ta({areaId:t,folderPath:n,isOpen:o}){const c=Zn(t,n),r=s.useRef(!1);s.useEffect(()=>{r.current=!1},[t,n]);const i=s.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const l=localStorage.getItem(c);if(!l)return null;const u=JSON.parse(l);if(Date.now()-u.timestamp>Qn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async y=>({tab:y,exists:await ea(y.path)})))).filter(({exists:y})=>y).map(({tab:y})=>y);let p=u.activeTabPath;return p&&!j.some(y=>y.path===p)&&(p=j.length>0?j[0].path:null),{tabs:j,activeTabPath:p,viewMode:u.viewMode||"files",selectedFolderIndex:u.selectedFolderIndex||0,expandedPaths:new Set(u.expandedPaths||[])}}catch(l){return console.error("[FileExplorerStorage] Failed to load state:",l),null}},[c]),f=s.useCallback(l=>{if(o)try{const u={tabs:l.tabs,activeTabPath:l.activeTabPath,viewMode:l.viewMode,selectedFolderIndex:l.selectedFolderIndex,expandedPaths:Array.from(l.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,o]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function sa(){const[t,n]=s.useState(()=>{const g=$s(Rt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),o=s.useRef(!1),[c,r]=s.useState(!1),i=s.useRef(0),f=s.useRef(0),l=s.useRef(t);l.current=t;const u=s.useCallback(g=>{g.preventDefault(),o.current=!0,r(!0),i.current=g.clientX,f.current=t,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[t]);return s.useEffect(()=>{const g=p=>{if(!o.current)return;const y=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+y));n(C)},j=()=>{o.current&&(o.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.TREE_PANEL_WIDTH,l.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:t,handleResizeStart:u,isResizing:c}}const na=100,aa=.65,ra=36;function ia(){const[t,n]=s.useState(()=>$s(Rt.MOBILE_TREE_PANEL_HEIGHT,0)),o=s.useRef(t);o.current=t;const c=s.useRef(0),r=s.useRef(0),i=()=>Math.floor((window.innerHeight-ra)*aa),f=p=>Math.min(i(),Math.max(na,p)),l=s.useCallback(p=>{n(p);const y=document.querySelector(".file-explorer-main");y&&y.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=s.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.MOBILE_TREE_PANEL_HEIGHT,o.current),mt.setTerminalResizing(!1)},[]),g=s.useCallback(p=>{p.preventDefault();const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.getBoundingClientRect().height)??240;c.current=p.clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const R=N=>{const d=N.clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",x)},[l,u]),j=s.useCallback(p=>{if(p.touches.length!==1)return;const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.getBoundingClientRect().height)??240;c.current=p.touches[0].clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const R=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[l,u]);return{mobileTreeHeight:t,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(null),[f,l]=s.useState(null),u=s.useCallback(async N=>{c(!0),i(null);try{const d=await Y(K(`/api/files/git-branches?path=${encodeURIComponent(N)}`)),v=await d.json();d.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(d){console.error("[GitBranches] Failed to load branches:",d),i("Failed to load branches"),n([])}finally{c(!1)}},[]),g=s.useCallback(async(N,d)=>{l("checkout"),i(null);try{const v=await Y(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return v.ok||i(w.error||"Checkout failed"),w}catch(v){console.error("[GitBranches] Checkout failed:",v);const w={success:!1,error:"Checkout failed"};return i(w.error),w}finally{l(null)}},[]),j=s.useCallback(async(N,d,v)=>{l("create"),i(null);try{const w=await Y(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),S=await w.json();return w.ok||i(S.error||"Failed to create branch"),S}catch(w){console.error("[GitBranches] Create branch failed:",w);const S={success:!1,error:"Failed to create branch"};return i(S.error),S}finally{l(null)}},[]),p=s.useCallback(async N=>{l("pull"),i(null);try{const d=await Y(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return!d.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(d){console.error("[GitBranches] Pull failed:",d);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{l(null)}},[]),y=s.useCallback(async N=>{l("push"),i(null);try{const d=await Y(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Push failed"),v}catch(d){console.error("[GitBranches] Push failed:",d);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{l(null)}},[]),C=s.useCallback(async(N,d)=>{l("merge"),i(null);try{const v=await Y(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return!v.ok&&!w.conflicts&&i(w.error||"Merge failed"),w}catch(v){console.error("[GitBranches] Merge failed:",v);const w={success:!1,error:"Merge failed"};return i(w.error),w}finally{l(null)}},[]),R=s.useCallback(async N=>{l("merge-abort"),i(null);try{const d=await Y(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge abort failed"),v}catch(d){console.error("[GitBranches] Merge abort failed:",d);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{l(null)}},[]),x=s.useCallback(async N=>{l("merge-continue"),i(null);try{const d=await Y(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge continue failed"),v}catch(d){console.error("[GitBranches] Merge continue failed:",d);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{l(null)}},[]);return{branches:t,loading:o,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:y,mergeBranch:C,mergeAbort:R,mergeContinue:x}}const la=50,oa=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function ca(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(!1),[f,l]=s.useState(null),[u,g]=s.useState(!1),[j,p]=s.useState(0),[y,C]=s.useState({...Rs}),[R,x]=s.useState(null),[N,d]=s.useState([]),[v,w]=s.useState(!1),[S,A]=s.useState([]),[H,G]=s.useState(!1),z=s.useRef(null),ae=s.useRef(""),ee=s.useCallback((O,Z,L)=>{const T=L||y,W=new URLSearchParams;return W.set("path",O),W.set("limit",String(la)),W.set("offset",String(Z)),T.branch&&W.set("branch",T.branch),T.author&&W.set("author",T.author),T.since&&W.set("since",T.since),T.until&&W.set("until",T.until),T.searchPath&&W.set("searchPath",T.searchPath),T.search&&W.set("search",T.search),W.toString()},[y]),D=s.useCallback(async O=>{ae.current=O,c(!0),l(null),x(null),d([]);try{const Z=ee(O,0),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok?(n(T.commits||[]),p(T.total||0),g(T.hasMore||!1)):(l(T.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),l("Failed to load git history"),n([])}finally{c(!1)}},[ee]),F=s.useCallback(async O=>{if(!(r||!u)){i(!0);try{const Z=ee(O,t.length),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok&&(n(W=>[...W,...T.commits||[]]),p(T.total||0),g(T.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,t.length,u,r]),I=s.useCallback(async O=>{if(x(O),!O){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:O.hash}),T=await Y(K(`/api/files/git-commit-files?${L}`)),W=await T.json();T.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=s.useCallback((O,Z)=>{C(L=>({...L,[O]:Z}))},[]),_=s.useCallback(()=>{C({...Rs})},[]);s.useEffect(()=>{const O=ae.current;if(O)return z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{D(O)},oa),()=>{z.current&&clearTimeout(z.current)}},[y]);const ge=s.useCallback(async O=>{G(!0);try{const Z=new URLSearchParams({path:O}),L=await Y(K(`/api/files/git-authors?${Z}`)),T=await L.json();L.ok&&A(T.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:t,loading:o,loadingMore:r,error:f,hasMore:u,total:j,filters:y,setFilter:re,resetFilters:_,selectedCommit:R,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:D,loadMore:F,authors:S,authorsLoading:H,loadAuthors:ge}}function da(t){if(!t.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const o of n){const c=t.current.querySelector(o);if(c&&Fs(c))return c}return Fs(t.current)?t.current:null}function Fs(t){const n=["auto","scroll"].includes(getComputedStyle(t).overflowY),o=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth;return n&&o}function Bs(t){if(!t)return 19.5;const n=parseFloat(getComputedStyle(t).lineHeight);return isNaN(n)?19.5:n}function Yt(t,n=!0){const o=n?t.scrollHeight:0;t.scrollTo({top:o,behavior:"smooth"})}function ua(t){const{scrollTop:n,scrollHeight:o,clientHeight:c}=t;return o<=c?100:Math.round(n/(o-c)*100)}function ha(t,n){const o=Bs(t),c=t.scrollTop,r=Math.floor(c/o)+1,i=n.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-B4DsIOre.js","assets/main-B8YPZvpg.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-C7Dsh8es.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as s,h as Y,i as K,G as Kt,Z as $s,S as Rt,_ as Hs,s as mt,u as le,j as e,I as M,bG as Ft,f as zs,bH as As,bI as Rn,bJ as Os,bK as Gs,bL as Fn,bM as In,bN as Tt,bO as Pn,bP as Ln,bQ as $n,bR as Xt,bS as Hn,bT as Us,bU as Mt,bV as Dt,ak as it,bW as ft,bX as pt,bY as Es,bZ as zn,bb as An,b_ as Jt,b$ as On,c0 as Gn,c1 as Ss,C as Un,o as Bn}from"./main-B8YPZvpg.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function _n(t){const[n,o]=s.useState(null),[c,r]=s.useState(!1),i=s.useCallback(async()=>{if(t){r(!0);try{const f=await Y(K(`/api/files/git-status?path=${encodeURIComponent(t)}`)),l=await f.json();f.ok?o(l):o({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),o({isGitRepo:!1,files:[]})}finally{r(!1)}}},[t]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Vn(t){try{const n=await Y(K(`/api/files/git-original?path=${encodeURIComponent(t)}`)),o=await n.json();return n.ok&&!o.isNew?{content:o.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Kn=new Set([".txt",".md",".markdown",".json",".yaml",".yml",".xml",".html",".htm",".css",".scss",".sass",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".c",".cpp",".h",".hpp",".cs",".go",".rs",".swift",".kt",".scala",".clj",".ex",".exs",".erl",".hs",".ml",".fs",".sql",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".toml",".ini",".cfg",".conf",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".babelrc",".log",".csv",".tsv",".svg",""]),Wn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Yn=new Set([".pdf"]),qn=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".zip",".tar",".gz",".rar",".7z",".exe",".dmg",".app",".deb",".rpm",".apk",".aab",".ipa",".msi",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".webm",".ttf",".otf",".woff",".woff2",".eot",".sqlite",".db",".so",".dll",".dylib",".a",".o",".obj",".bin",".dat",".iso",".img",".jar",".war",".ear",".class"]);function Jn(t){const n=t.toLowerCase();return Wn.has(n)?"image":Yn.has(n)?"pdf":qn.has(n)?"binary":(Kn.has(n),"text")}function Xn(){const[t,n]=s.useState(null),[o,c]=s.useState(!1),[r,i]=s.useState(null),f=s.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),y=Jn(p),C=u.substring(u.lastIndexOf("/")+1);if(y==="image"){const N=await Y(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!N.ok){const w=await N.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await N.blob(),v=URL.createObjectURL(d);n({path:u,filename:C,extension:p,content:"",size:d.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(y==="pdf"){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load PDF info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"pdf",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&token=${encodeURIComponent(Kt())}`)});return}if(y==="binary"){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load file info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Kt())}`)});return}const R=await Y(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await R.json();if(!R.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(N.ok){n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Kt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const y=p instanceof Error?p.message:"Failed to load file";i(y),n(null)}finally{c(!1)}},[]),l=s.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:t,loading:o,error:r,loadFile:f,clearFile:l,setFile:n}}const Wt="file-explorer-state",Qn=10080*60*1e3;function Zn(t,n){return n?`${Wt}-folder-${n}`:t?`${Wt}-area-${t}`:`${Wt}-default`}async function ea(t){try{const n=await Y(K(`/api/files/exists?path=${encodeURIComponent(t)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ta({areaId:t,folderPath:n,isOpen:o}){const c=Zn(t,n),r=s.useRef(!1);s.useEffect(()=>{r.current=!1},[t,n]);const i=s.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const l=localStorage.getItem(c);if(!l)return null;const u=JSON.parse(l);if(Date.now()-u.timestamp>Qn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async y=>({tab:y,exists:await ea(y.path)})))).filter(({exists:y})=>y).map(({tab:y})=>y);let p=u.activeTabPath;return p&&!j.some(y=>y.path===p)&&(p=j.length>0?j[0].path:null),{tabs:j,activeTabPath:p,viewMode:u.viewMode||"files",selectedFolderIndex:u.selectedFolderIndex||0,expandedPaths:new Set(u.expandedPaths||[])}}catch(l){return console.error("[FileExplorerStorage] Failed to load state:",l),null}},[c]),f=s.useCallback(l=>{if(o)try{const u={tabs:l.tabs,activeTabPath:l.activeTabPath,viewMode:l.viewMode,selectedFolderIndex:l.selectedFolderIndex,expandedPaths:Array.from(l.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,o]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function sa(){const[t,n]=s.useState(()=>{const g=$s(Rt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),o=s.useRef(!1),[c,r]=s.useState(!1),i=s.useRef(0),f=s.useRef(0),l=s.useRef(t);l.current=t;const u=s.useCallback(g=>{g.preventDefault(),o.current=!0,r(!0),i.current=g.clientX,f.current=t,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[t]);return s.useEffect(()=>{const g=p=>{if(!o.current)return;const y=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+y));n(C)},j=()=>{o.current&&(o.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.TREE_PANEL_WIDTH,l.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:t,handleResizeStart:u,isResizing:c}}const na=100,aa=.65,ra=36;function ia(){const[t,n]=s.useState(()=>$s(Rt.MOBILE_TREE_PANEL_HEIGHT,0)),o=s.useRef(t);o.current=t;const c=s.useRef(0),r=s.useRef(0),i=()=>Math.floor((window.innerHeight-ra)*aa),f=p=>Math.min(i(),Math.max(na,p)),l=s.useCallback(p=>{n(p);const y=document.querySelector(".file-explorer-main");y&&y.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=s.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.MOBILE_TREE_PANEL_HEIGHT,o.current),mt.setTerminalResizing(!1)},[]),g=s.useCallback(p=>{p.preventDefault();const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.getBoundingClientRect().height)??240;c.current=p.clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const R=N=>{const d=N.clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",x)},[l,u]),j=s.useCallback(p=>{if(p.touches.length!==1)return;const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.getBoundingClientRect().height)??240;c.current=p.touches[0].clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const R=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[l,u]);return{mobileTreeHeight:t,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(null),[f,l]=s.useState(null),u=s.useCallback(async N=>{c(!0),i(null);try{const d=await Y(K(`/api/files/git-branches?path=${encodeURIComponent(N)}`)),v=await d.json();d.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(d){console.error("[GitBranches] Failed to load branches:",d),i("Failed to load branches"),n([])}finally{c(!1)}},[]),g=s.useCallback(async(N,d)=>{l("checkout"),i(null);try{const v=await Y(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return v.ok||i(w.error||"Checkout failed"),w}catch(v){console.error("[GitBranches] Checkout failed:",v);const w={success:!1,error:"Checkout failed"};return i(w.error),w}finally{l(null)}},[]),j=s.useCallback(async(N,d,v)=>{l("create"),i(null);try{const w=await Y(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),S=await w.json();return w.ok||i(S.error||"Failed to create branch"),S}catch(w){console.error("[GitBranches] Create branch failed:",w);const S={success:!1,error:"Failed to create branch"};return i(S.error),S}finally{l(null)}},[]),p=s.useCallback(async N=>{l("pull"),i(null);try{const d=await Y(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return!d.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(d){console.error("[GitBranches] Pull failed:",d);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{l(null)}},[]),y=s.useCallback(async N=>{l("push"),i(null);try{const d=await Y(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Push failed"),v}catch(d){console.error("[GitBranches] Push failed:",d);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{l(null)}},[]),C=s.useCallback(async(N,d)=>{l("merge"),i(null);try{const v=await Y(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return!v.ok&&!w.conflicts&&i(w.error||"Merge failed"),w}catch(v){console.error("[GitBranches] Merge failed:",v);const w={success:!1,error:"Merge failed"};return i(w.error),w}finally{l(null)}},[]),R=s.useCallback(async N=>{l("merge-abort"),i(null);try{const d=await Y(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge abort failed"),v}catch(d){console.error("[GitBranches] Merge abort failed:",d);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{l(null)}},[]),x=s.useCallback(async N=>{l("merge-continue"),i(null);try{const d=await Y(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge continue failed"),v}catch(d){console.error("[GitBranches] Merge continue failed:",d);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{l(null)}},[]);return{branches:t,loading:o,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:y,mergeBranch:C,mergeAbort:R,mergeContinue:x}}const la=50,oa=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function ca(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(!1),[f,l]=s.useState(null),[u,g]=s.useState(!1),[j,p]=s.useState(0),[y,C]=s.useState({...Rs}),[R,x]=s.useState(null),[N,d]=s.useState([]),[v,w]=s.useState(!1),[S,A]=s.useState([]),[H,G]=s.useState(!1),z=s.useRef(null),ae=s.useRef(""),ee=s.useCallback((O,Z,L)=>{const T=L||y,W=new URLSearchParams;return W.set("path",O),W.set("limit",String(la)),W.set("offset",String(Z)),T.branch&&W.set("branch",T.branch),T.author&&W.set("author",T.author),T.since&&W.set("since",T.since),T.until&&W.set("until",T.until),T.searchPath&&W.set("searchPath",T.searchPath),T.search&&W.set("search",T.search),W.toString()},[y]),D=s.useCallback(async O=>{ae.current=O,c(!0),l(null),x(null),d([]);try{const Z=ee(O,0),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok?(n(T.commits||[]),p(T.total||0),g(T.hasMore||!1)):(l(T.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),l("Failed to load git history"),n([])}finally{c(!1)}},[ee]),F=s.useCallback(async O=>{if(!(r||!u)){i(!0);try{const Z=ee(O,t.length),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok&&(n(W=>[...W,...T.commits||[]]),p(T.total||0),g(T.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,t.length,u,r]),I=s.useCallback(async O=>{if(x(O),!O){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:O.hash}),T=await Y(K(`/api/files/git-commit-files?${L}`)),W=await T.json();T.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=s.useCallback((O,Z)=>{C(L=>({...L,[O]:Z}))},[]),_=s.useCallback(()=>{C({...Rs})},[]);s.useEffect(()=>{const O=ae.current;if(O)return z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{D(O)},oa),()=>{z.current&&clearTimeout(z.current)}},[y]);const ge=s.useCallback(async O=>{G(!0);try{const Z=new URLSearchParams({path:O}),L=await Y(K(`/api/files/git-authors?${Z}`)),T=await L.json();L.ok&&A(T.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:t,loading:o,loadingMore:r,error:f,hasMore:u,total:j,filters:y,setFilter:re,resetFilters:_,selectedCommit:R,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:D,loadMore:F,authors:S,authorsLoading:H,loadAuthors:ge}}function da(t){if(!t.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const o of n){const c=t.current.querySelector(o);if(c&&Fs(c))return c}return Fs(t.current)?t.current:null}function Fs(t){const n=["auto","scroll"].includes(getComputedStyle(t).overflowY),o=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth;return n&&o}function Bs(t){if(!t)return 19.5;const n=parseFloat(getComputedStyle(t).lineHeight);return isNaN(n)?19.5:n}function Yt(t,n=!0){const o=n?t.scrollHeight:0;t.scrollTo({top:o,behavior:"smooth"})}function ua(t){const{scrollTop:n,scrollHeight:o,clientHeight:c}=t;return o<=c?100:Math.round(n/(o-c)*100)}function ha(t,n){const o=Bs(t),c=t.scrollTop,r=Math.floor(c/o)+1,i=n.split(`
|
|
3
3
|
`).length;return Math.min(r,i)}function ma(t,n,o=!1){if(!n)return[];o||t.toLowerCase();const c=o?n:n.toLowerCase(),r=[];let i=0;const f=t.split(`
|
|
4
4
|
`);let l=0;for(let u=0;u<f.length;u++){const g=f[u],j=o?g:g.toLowerCase();let p=0,y=j.indexOf(c);for(;y!==-1;){const C=l+y;r.push({index:i++,line:u+1,column:y,length:c.length,charIndex:C}),p=y+c.length,y=j.indexOf(c,p)}l+=g.length+1}return r}function lt(t){return/[\w]/.test(t)}function Ge(t){return/\s/.test(t)}function fa(t,n,o){let c=n-1,r=o;const i=t.length,f=t[c]||"";if(r<f.length){const g=lt(f[r]);if(!Ge(f[r]))for(;r<f.length&&!Ge(f[r])&<(f[r])===g;)r++}for(;c<i;){const g=t[c]||"";for(;r<g.length&&Ge(g[r]);)r++;if(r<g.length)return{line:c+1,col:r};c++,r=0}const l=i,u=Math.max(0,(t[i-1]||"").length-1);return{line:l,col:u}}function pa(t,n,o){let c=n-1,r=o+1;const i=t.length;for(;c<i;){const u=t[c]||"";for(;r<u.length&&Ge(u[r]);)r++;if(r<u.length)break;c++,r=0}if(c>=i)return{line:i,col:Math.max(0,(t[i-1]||"").length-1)};const f=t[c]||"",l=lt(f[r]);for(;r+1<f.length&&!Ge(f[r+1])&<(f[r+1])===l;)r++;return{line:c+1,col:r}}function ga(t,n,o){let c=n-1,r=o-1;for(;c>=0;){const l=t[c]||"";for(;r>=0&&Ge(l[r]);)r--;if(r>=0)break;c--,c>=0&&(r=(t[c]||"").length-1)}if(c<0)return{line:1,col:0};const i=t[c]||"",f=lt(i[r]);for(;r>0&&!Ge(i[r-1])&<(i[r-1])===f;)r--;return{line:c+1,col:r}}function xa(t,n,o,c){if(c==="none")return"";const{anchorLine:r,anchorCol:i,headLine:f,headCol:l}=o;if(c==="line"){const C=Math.min(r,f),R=Math.max(r,f);return n.slice(C-1,R).join(`
|
|
5
5
|
`)}let u,g,j,p;if(r<f||r===f&&i<=l?(u=r,g=i,j=f,p=l):(u=f,g=l,j=r,p=i),u===j)return(n[u-1]||"").substring(g,p+1);const y=[];y.push((n[u-1]||"").substring(g));for(let C=u;C<j-1;C++)y.push(n[C]||"");return y.push((n[j-1]||"").substring(0,p+1)),y.join(`
|
|
6
6
|
`)}function _s(t){const{containerRef:n,isEnabled:o=!0,content:c="",onClose:r,onSearchOpen:i}=t,f=s.useRef({percentage:0,line:1,column:1}),l=s.useRef(null),u=s.useRef(19.5),g=s.useMemo(()=>c.split(`
|
|
7
|
-
`),[c]),j=g.length,[p,y]=s.useState(1),[C,R]=s.useState(0),[x,N]=s.useState(!1),[d,v]=s.useState("none"),[w,S]=s.useState(null),[A,H]=s.useState(!1),[G,z]=s.useState(""),[ae,ee]=s.useState(0),[D,F]=s.useState(!1),I=s.useMemo(()=>ma(c,G,!1),[c,G]),re=s.useCallback(()=>{const m=l.current;if(!m)return;const q=ua(m),ie=ha(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:q,line:ie,column:V}},[c]),_=s.useCallback(()=>{H(!0),z(""),ee(0),i==null||i()},[i]),ge=s.useCallback(()=>{H(!1),z(""),ee(0)},[]),O=s.useCallback(()=>{F(m=>!m)},[]),Z=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.querySelector(".file-viewer-pre"),ue=ie&&parseFloat(getComputedStyle(ie).lineHeight)||u.current,V=ie&&parseFloat(getComputedStyle(ie).paddingTop)||0,Q=(ie?ie.offsetTop:0)+V+(m-1)*ue,te=ue*3;q.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);s.useEffect(()=>{!A||I.length===0||ee(0)},[I,A]),s.useEffect(()=>{if(!A||I.length===0)return;const m=I[ae];m&&(y(m.line),R(m.column),Z(m.line))},[A,I,ae,Z]);const L=s.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),T=s.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.querySelector(".file-viewer-pre");if(!ie)return;const ue=parseFloat(getComputedStyle(ie).lineHeight),V=isNaN(ue)?u.current:ue,E=parseFloat(getComputedStyle(ie).paddingTop)||0,te=ie.offsetTop+E+(m-1)*V,Ne=te+V,xe=q.scrollTop,U=xe+q.clientHeight;te<xe?q.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&q.scrollTo({top:Ne-q.clientHeight,behavior:"auto"})},[]),ne=s.useCallback((m,q)=>{y(m),R(q),W(m),d!=="none"&&S(ie=>ie?{...ie,headLine:m,headCol:q}:null)},[d,W]),be=s.useCallback(()=>{if(d==="none"||!w)return;const m=xa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const q=document.createElement("textarea");q.value=m,q.style.position="fixed",q.style.left="-9999px",document.body.appendChild(q),q.select(),document.execCommand("copy"),document.body.removeChild(q)}),v("none"),S(null)},[d,w,c,g]),de=s.useCallback(m=>{const q=m.target;if((q.tagName==="INPUT"||q.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=l.current;if(!ue)return;let V=!1;const E=u.current,Q=Math.max(1,Math.floor(ue.clientHeight/E)),te=Math.max(1,Math.floor(Q/2)),Ne=(U,se)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(se,Math.max(0,pe))},xe=(U,se)=>{const pe=Ne(U,se);ne(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),S(null)):(v("char"),S({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),S(null)):(v("line"),S({anchorLine:p,anchorCol:0,headLine:p,headCol:0})),V=!0;else if(m.key==="y"&&!m.ctrlKey&&d!=="none")m.preventDefault(),m.stopPropagation(),be(),V=!0;else if(m.key==="j"||m.key==="ArrowDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+1,j);xe(U,C),V=!0}else if(m.key==="k"||m.key==="ArrowUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-1,1);xe(U,C),V=!0}else if(m.key==="d"&&m.ctrlKey||m.key==="d"&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.min(p+te,j);xe(U,C),V=!0}else if(m.key==="u"&&m.ctrlKey||m.key==="u"&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.max(p-te,1);xe(U,C),V=!0}else if((m.ctrlKey||m.metaKey)&&m.key==="f")m.preventDefault(),m.stopPropagation(),_(),V=!0;else if(m.key==="f"&&!m.ctrlKey&&!m.metaKey&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key===" "||m.key==="PageDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key==="b"&&!x&&d==="none"&&!A||m.key==="PageUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-Q,1);xe(U,C),V=!0}else if(m.key==="g"&&!m.shiftKey&&d==="none"&&!A)m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),ne(j,0),Yt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,C-1)),V=!0;else if(m.key==="l"||m.key==="ArrowRight"){m.preventDefault(),m.stopPropagation();const U=(g[p-1]||"").length;ne(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="b"&&!A){m.preventDefault(),m.stopPropagation();const U=ga(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),ne(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const se=(g[p-1]||"").search(/\S/);ne(p,se>=0?se:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!A?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!A?(m.preventDefault(),m.stopPropagation(),T(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),O(),V=!0):m.key==="q"&&d==="none"?(m.preventDefault(),m.stopPropagation(),r==null||r(),V=!0):m.key==="Escape"&&(d!=="none"?(m.preventDefault(),m.stopPropagation(),v("none"),S(null),V=!0):A?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),N(!1),V=!0));V&&(m.key!=="Escape"&&!x&&N(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,A,ge,d,x,ne,be,_,L,T,O]);return s.useEffect(()=>{if(!o)return;const m=da(n);if(l.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const q=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",q,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",q)}},[o,de,re]),{scrollPercentage:f.current.percentage,currentLine:f.current.line,currentColumn:f.current.column,totalLines:j,cursorLine:p,cursorCol:C,cursorModeActive:x,visualMode:d,selection:w,searchActive:A,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:z,nextMatch:L,prevMatch:T,clearSearch:ge,helpActive:D,toggleHelp:O}}const Zt=({query:t,onQueryChange:n,matchCount:o,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:l}=le(["terminal"]),u=s.useRef(null);s.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=s.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=o===0&&t?l("terminal:fileExplorer.noMatches"):o>0?`${c+1}/${o}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:u,type:"text",className:"file-viewer-search-input",placeholder:l("terminal:fileExplorer.searchInFile"),value:t,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:o===0,title:l("terminal:fileExplorer.previousMatch"),"aria-label":l("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:o===0,title:l("terminal:fileExplorer.nextMatch"),"aria-label":l("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:l("terminal:fileExplorer.closeSearch"),"aria-label":l("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ya=[{keys:["j","↓"],description:"Move cursor down one line",category:"Navigation"},{keys:["k","↑"],description:"Move cursor up one line",category:"Navigation"},{keys:["h","←"],description:"Move cursor left",category:"Navigation"},{keys:["l","→"],description:"Move cursor right",category:"Navigation"},{keys:["0"],description:"Jump to start of line",category:"Navigation"},{keys:["$"],description:"Jump to end of line",category:"Navigation"},{keys:["^"],description:"First non-whitespace char",category:"Navigation"},{keys:["d","Ctrl+D"],description:"Half page down",category:"Navigation"},{keys:["u","Ctrl+U"],description:"Half page up",category:"Navigation"},{keys:["f","Space"],description:"Full page down",category:"Navigation"},{keys:["b","Page Up"],description:"Full page up",category:"Navigation"},{keys:["g","Home"],description:"Jump to top of file",category:"Navigation"},{keys:["G","End"],description:"Jump to bottom of file",category:"Navigation"},{keys:["w"],description:"Next word start",category:"Word Motion"},{keys:["e"],description:"Next word end",category:"Word Motion"},{keys:["b"],description:"Previous word start",category:"Word Motion"},{keys:["v"],description:"Character visual mode",category:"Visual Mode"},{keys:["V"],description:"Line visual mode",category:"Visual Mode"},{keys:["y"],description:"Yank (copy) selection",category:"Visual Mode"},{keys:["Escape"],description:"Exit visual mode",category:"Visual Mode"},{keys:["/"],description:"Open search bar",category:"Search"},{keys:["n"],description:"Next match",category:"Search"},{keys:["N"],description:"Previous match",category:"Search"},{keys:["?"],description:"Toggle this help overlay",category:"Help"},{keys:["Escape"],description:"Exit cursor mode (or visual/search)",category:"Help"},{keys:["Alt+E"],description:"Close file viewer",category:"Help"},{keys:["q"],description:"Close file viewer",category:"Help"}],es=({onClose:t})=>{const{t:n}=le(["terminal"]),o=s.useCallback(i=>{i.target===i.currentTarget&&t()},[t]),c=s.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),t())},[t]),r=ya.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:o,onKeyDown:c,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:t,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(M,{name:"close",size:14})}),e.jsx("h2",{className:"keybindings-help-title",children:n("terminal:fileExplorer.keybindingsHelp")}),e.jsx("p",{className:"keybindings-help-subtitle",children:n("terminal:fileExplorer.keybindingsSubtitle")}),e.jsx("div",{className:"keybindings-help-categories",children:Object.entries(r).map(([i,f])=>e.jsxs("div",{className:"keybindings-help-category",children:[e.jsx("h3",{className:"keybindings-help-category-title",children:i}),e.jsx("div",{className:"keybindings-help-list",children:f.map((l,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:l.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:l.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=s.lazy(()=>Rn(()=>import("./EmbeddedEditor-BnxOx-pQ.js"),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.EmbeddedEditor}))),ba=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ja=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",va="https://kroki.io/plantuml/svg";function wa(t){return ba.includes(t.toLowerCase())}function Ca(t){return ja.includes(t.toLowerCase())}function Na(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[t,o]}function ka(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[t,o]}function Ea(t){const n=new TextEncoder().encode(t);let o="";for(const c of n)o+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(o)}`}function Ue({file:t,rightContent:n,onRevealInTree:o,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,l]=s.useState("idle"),[u,g]=s.useState("idle"),[j,p]=s.useState("idle"),y=t.fileType==="text"?Ft(t.extension):t.extension.slice(1).toUpperCase(),C=t.fileType==="text"&&t.content!=null,{settings:R}=zs(),x=async()=>{try{await Tt(t.content),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},N=()=>{const S=new Blob([t.content],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),H=document.createElement("a");H.href=A,H.download=t.filename,document.body.appendChild(H),H.click(),H.remove(),setTimeout(()=>URL.revokeObjectURL(A),1e3)},d=async()=>{l("loading");try{const S=await Y(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!S.ok){const A=await S.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",A),l("error"),setTimeout(()=>l("idle"),2e3);return}l("success"),setTimeout(()=>l("idle"),2e3)}catch(S){console.error("Error opening file in editor:",S),l("error"),setTimeout(()=>l("idle"),2e3)}},v=async()=>{if(t.path)try{await $n(t.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(S){console.error("Error opening file explorer:",S),g("error"),setTimeout(()=>g("idle"),2e3)}},w=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:t.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[As(t.size)," • ",y,t.content&&` • ${t.content.split(`
|
|
7
|
+
`),[c]),j=g.length,[p,y]=s.useState(1),[C,R]=s.useState(0),[x,N]=s.useState(!1),[d,v]=s.useState("none"),[w,S]=s.useState(null),[A,H]=s.useState(!1),[G,z]=s.useState(""),[ae,ee]=s.useState(0),[D,F]=s.useState(!1),I=s.useMemo(()=>ma(c,G,!1),[c,G]),re=s.useCallback(()=>{const m=l.current;if(!m)return;const q=ua(m),ie=ha(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:q,line:ie,column:V}},[c]),_=s.useCallback(()=>{H(!0),z(""),ee(0),i==null||i()},[i]),ge=s.useCallback(()=>{H(!1),z(""),ee(0)},[]),O=s.useCallback(()=>{F(m=>!m)},[]),Z=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.querySelector(".file-viewer-pre"),ue=ie&&parseFloat(getComputedStyle(ie).lineHeight)||u.current,V=ie&&parseFloat(getComputedStyle(ie).paddingTop)||0,Q=(ie?ie.offsetTop:0)+V+(m-1)*ue,te=ue*3;q.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);s.useEffect(()=>{!A||I.length===0||ee(0)},[I,A]),s.useEffect(()=>{if(!A||I.length===0)return;const m=I[ae];m&&(y(m.line),R(m.column),Z(m.line))},[A,I,ae,Z]);const L=s.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),T=s.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.querySelector(".file-viewer-pre");if(!ie)return;const ue=parseFloat(getComputedStyle(ie).lineHeight),V=isNaN(ue)?u.current:ue,E=parseFloat(getComputedStyle(ie).paddingTop)||0,te=ie.offsetTop+E+(m-1)*V,Ne=te+V,xe=q.scrollTop,U=xe+q.clientHeight;te<xe?q.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&q.scrollTo({top:Ne-q.clientHeight,behavior:"auto"})},[]),ne=s.useCallback((m,q)=>{y(m),R(q),W(m),d!=="none"&&S(ie=>ie?{...ie,headLine:m,headCol:q}:null)},[d,W]),be=s.useCallback(()=>{if(d==="none"||!w)return;const m=xa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const q=document.createElement("textarea");q.value=m,q.style.position="fixed",q.style.left="-9999px",document.body.appendChild(q),q.select(),document.execCommand("copy"),document.body.removeChild(q)}),v("none"),S(null)},[d,w,c,g]),de=s.useCallback(m=>{const q=m.target;if((q.tagName==="INPUT"||q.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=l.current;if(!ue)return;let V=!1;const E=u.current,Q=Math.max(1,Math.floor(ue.clientHeight/E)),te=Math.max(1,Math.floor(Q/2)),Ne=(U,se)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(se,Math.max(0,pe))},xe=(U,se)=>{const pe=Ne(U,se);ne(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),S(null)):(v("char"),S({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),S(null)):(v("line"),S({anchorLine:p,anchorCol:0,headLine:p,headCol:0})),V=!0;else if(m.key==="y"&&!m.ctrlKey&&d!=="none")m.preventDefault(),m.stopPropagation(),be(),V=!0;else if(m.key==="j"||m.key==="ArrowDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+1,j);xe(U,C),V=!0}else if(m.key==="k"||m.key==="ArrowUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-1,1);xe(U,C),V=!0}else if(m.key==="d"&&m.ctrlKey||m.key==="d"&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.min(p+te,j);xe(U,C),V=!0}else if(m.key==="u"&&m.ctrlKey||m.key==="u"&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.max(p-te,1);xe(U,C),V=!0}else if((m.ctrlKey||m.metaKey)&&m.key==="f")m.preventDefault(),m.stopPropagation(),_(),V=!0;else if(m.key==="f"&&!m.ctrlKey&&!m.metaKey&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key===" "||m.key==="PageDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key==="b"&&!x&&d==="none"&&!A||m.key==="PageUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-Q,1);xe(U,C),V=!0}else if(m.key==="g"&&!m.shiftKey&&d==="none"&&!A)m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),ne(j,0),Yt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,C-1)),V=!0;else if(m.key==="l"||m.key==="ArrowRight"){m.preventDefault(),m.stopPropagation();const U=(g[p-1]||"").length;ne(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="b"&&!A){m.preventDefault(),m.stopPropagation();const U=ga(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),ne(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const se=(g[p-1]||"").search(/\S/);ne(p,se>=0?se:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!A?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!A?(m.preventDefault(),m.stopPropagation(),T(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),O(),V=!0):m.key==="q"&&d==="none"?(m.preventDefault(),m.stopPropagation(),r==null||r(),V=!0):m.key==="Escape"&&(d!=="none"?(m.preventDefault(),m.stopPropagation(),v("none"),S(null),V=!0):A?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),N(!1),V=!0));V&&(m.key!=="Escape"&&!x&&N(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,A,ge,d,x,ne,be,_,L,T,O]);return s.useEffect(()=>{if(!o)return;const m=da(n);if(l.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const q=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",q,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",q)}},[o,de,re]),{scrollPercentage:f.current.percentage,currentLine:f.current.line,currentColumn:f.current.column,totalLines:j,cursorLine:p,cursorCol:C,cursorModeActive:x,visualMode:d,selection:w,searchActive:A,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:z,nextMatch:L,prevMatch:T,clearSearch:ge,helpActive:D,toggleHelp:O}}const Zt=({query:t,onQueryChange:n,matchCount:o,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:l}=le(["terminal"]),u=s.useRef(null);s.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=s.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=o===0&&t?l("terminal:fileExplorer.noMatches"):o>0?`${c+1}/${o}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:u,type:"text",className:"file-viewer-search-input",placeholder:l("terminal:fileExplorer.searchInFile"),value:t,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:o===0,title:l("terminal:fileExplorer.previousMatch"),"aria-label":l("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:o===0,title:l("terminal:fileExplorer.nextMatch"),"aria-label":l("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:l("terminal:fileExplorer.closeSearch"),"aria-label":l("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ya=[{keys:["j","↓"],description:"Move cursor down one line",category:"Navigation"},{keys:["k","↑"],description:"Move cursor up one line",category:"Navigation"},{keys:["h","←"],description:"Move cursor left",category:"Navigation"},{keys:["l","→"],description:"Move cursor right",category:"Navigation"},{keys:["0"],description:"Jump to start of line",category:"Navigation"},{keys:["$"],description:"Jump to end of line",category:"Navigation"},{keys:["^"],description:"First non-whitespace char",category:"Navigation"},{keys:["d","Ctrl+D"],description:"Half page down",category:"Navigation"},{keys:["u","Ctrl+U"],description:"Half page up",category:"Navigation"},{keys:["f","Space"],description:"Full page down",category:"Navigation"},{keys:["b","Page Up"],description:"Full page up",category:"Navigation"},{keys:["g","Home"],description:"Jump to top of file",category:"Navigation"},{keys:["G","End"],description:"Jump to bottom of file",category:"Navigation"},{keys:["w"],description:"Next word start",category:"Word Motion"},{keys:["e"],description:"Next word end",category:"Word Motion"},{keys:["b"],description:"Previous word start",category:"Word Motion"},{keys:["v"],description:"Character visual mode",category:"Visual Mode"},{keys:["V"],description:"Line visual mode",category:"Visual Mode"},{keys:["y"],description:"Yank (copy) selection",category:"Visual Mode"},{keys:["Escape"],description:"Exit visual mode",category:"Visual Mode"},{keys:["/"],description:"Open search bar",category:"Search"},{keys:["n"],description:"Next match",category:"Search"},{keys:["N"],description:"Previous match",category:"Search"},{keys:["?"],description:"Toggle this help overlay",category:"Help"},{keys:["Escape"],description:"Exit cursor mode (or visual/search)",category:"Help"},{keys:["Alt+E"],description:"Close file viewer",category:"Help"},{keys:["q"],description:"Close file viewer",category:"Help"}],es=({onClose:t})=>{const{t:n}=le(["terminal"]),o=s.useCallback(i=>{i.target===i.currentTarget&&t()},[t]),c=s.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),t())},[t]),r=ya.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:o,onKeyDown:c,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:t,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(M,{name:"close",size:14})}),e.jsx("h2",{className:"keybindings-help-title",children:n("terminal:fileExplorer.keybindingsHelp")}),e.jsx("p",{className:"keybindings-help-subtitle",children:n("terminal:fileExplorer.keybindingsSubtitle")}),e.jsx("div",{className:"keybindings-help-categories",children:Object.entries(r).map(([i,f])=>e.jsxs("div",{className:"keybindings-help-category",children:[e.jsx("h3",{className:"keybindings-help-category-title",children:i}),e.jsx("div",{className:"keybindings-help-list",children:f.map((l,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:l.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:l.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=s.lazy(()=>Rn(()=>import("./EmbeddedEditor-B4DsIOre.js"),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.EmbeddedEditor}))),ba=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ja=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",va="https://kroki.io/plantuml/svg";function wa(t){return ba.includes(t.toLowerCase())}function Ca(t){return ja.includes(t.toLowerCase())}function Na(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[t,o]}function ka(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[t,o]}function Ea(t){const n=new TextEncoder().encode(t);let o="";for(const c of n)o+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(o)}`}function Ue({file:t,rightContent:n,onRevealInTree:o,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,l]=s.useState("idle"),[u,g]=s.useState("idle"),[j,p]=s.useState("idle"),y=t.fileType==="text"?Ft(t.extension):t.extension.slice(1).toUpperCase(),C=t.fileType==="text"&&t.content!=null,{settings:R}=zs(),x=async()=>{try{await Tt(t.content),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},N=()=>{const S=new Blob([t.content],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),H=document.createElement("a");H.href=A,H.download=t.filename,document.body.appendChild(H),H.click(),H.remove(),setTimeout(()=>URL.revokeObjectURL(A),1e3)},d=async()=>{l("loading");try{const S=await Y(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!S.ok){const A=await S.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",A),l("error"),setTimeout(()=>l("idle"),2e3);return}l("success"),setTimeout(()=>l("idle"),2e3)}catch(S){console.error("Error opening file in editor:",S),l("error"),setTimeout(()=>l("idle"),2e3)}},v=async()=>{if(t.path)try{await $n(t.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(S){console.error("Error opening file explorer:",S),g("error"),setTimeout(()=>g("idle"),2e3)}},w=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:t.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[As(t.size)," • ",y,t.content&&` • ${t.content.split(`
|
|
8
8
|
`).length} lines`]})]}),e.jsxs("div",{className:"file-viewer-header-right",children:[r&&t.fileType==="text"&&e.jsx("button",{className:`file-viewer-edit-btn${c?" active":""}`,onClick:r,title:i(c?"terminal:fileExplorer.exitEdit":"terminal:fileExplorer.editFile"),children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 012.474 0l1.086 1.086a1.75 1.75 0 010 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 01-.927-.928l.929-3.25a1.75 1.75 0 01.445-.758l8.61-8.61zm1.414 1.06a.25.25 0 00-.354 0L3.463 11.1a.25.25 0 00-.064.108l-.558 1.953 1.953-.558a.25.25 0 00.108-.064l8.61-8.61a.25.25 0 000-.354l-1.086-1.086z"})})}),C&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:x,title:i("terminal:fileExplorer.copyAllTitle"),children:i(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyAll")}),e.jsx("button",{className:"file-viewer-download-btn",onClick:N,title:i("terminal:fileExplorer.downloadFileTitle"),children:i("common:buttons.download")})]}),e.jsx("button",{className:`file-viewer-reveal-explorer-btn ${u}`,onClick:v,disabled:!t.path,title:w,"aria-label":w,children:u==="success"?e.jsx(M,{name:"check",size:14}):u==="error"?e.jsx(M,{name:"cross",size:14}):e.jsx(M,{name:"folder-open",size:14})}),e.jsx("button",{className:`file-viewer-open-editor-btn ${f}`,onClick:d,disabled:f==="loading",title:i(f==="error"?"terminal:fileExplorer.failedToOpenEditor":f==="success"?"terminal:fileExplorer.openingInEditor":"terminal:fileExplorer.openInEditor"),children:f==="success"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 11-1.06-1.06l7.25-7.25a.75.75 0 011.06 0z"})}):f==="error"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"})}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M1.5 1h6v1.5h-5v11h11v-5H15v6.5H0V1h1.5zm8 0H15v5.5h-1.5V3.56L7.28 9.78l-1.06-1.06L12.44 2.5H9.5V1z"})})}),o&&e.jsx("button",{className:"file-viewer-locate-btn",onClick:()=>o(t.path),title:i("terminal:fileExplorer.locateInTree"),children:e.jsx(M,{name:"target",size:14})}),n]})]})}function Sa({file:t,onRevealInTree:n,renderMarkdown:o,onToggleRender:c,editMode:r,onToggleEdit:i}){const f=s.useRef(null),l=s.useRef(null),u=s.useRef(null),{t:g}=le(["terminal","common"]),[j,p]=s.useState("idle"),[y,C]=s.useState("idle"),[R,x]=s.useState("idle"),[N,d]=s.useState("idle"),v=_s({containerRef:u,isEnabled:!0,content:t.content});s.useEffect(()=>{if(!o&&f.current){const z=Ft(t.extension);Os(z).then(()=>{f.current&&Gs(f.current)})}},[t,o]);const w=s.useCallback(async()=>{if(!l.current){p("error"),setTimeout(()=>p("idle"),2e3);return}try{const z=l.current.innerHTML,ae=Fn(z),ee=l.current.innerText;await In(ae,ee),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},[]),S=s.useCallback(async()=>{if(!l.current){C("error"),setTimeout(()=>C("idle"),2e3);return}try{const z=l.current.innerHTML;await Tt(z),C("copied"),setTimeout(()=>C("idle"),2e3)}catch{C("error"),setTimeout(()=>C("idle"),2e3)}},[]),A=s.useCallback(async()=>{try{await Tt(t.content),x("copied"),setTimeout(()=>x("idle"),2e3)}catch{x("error"),setTimeout(()=>x("idle"),2e3)}},[t.content]),H=s.useCallback(async()=>{try{await Tt(t.content),d("copied"),setTimeout(()=>d("idle"),2e3)}catch{d("error"),setTimeout(()=>d("idle"),2e3)}},[t.content]),G=e.jsxs("div",{className:"file-viewer-header-buttons",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:w,title:g("terminal:fileExplorer.copyRichTextTitle"),children:g(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyRichText")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${y}`,onClick:S,title:g("terminal:fileExplorer.copyHtmlTitle"),children:g(y==="copied"?"terminal:fileExplorer.copied":y==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyHtml")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${R}`,onClick:A,title:g("terminal:fileExplorer.copyMarkdownTitle"),children:g(R==="copied"?"terminal:fileExplorer.copied":R==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyMarkdown")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${N}`,onClick:H,title:g("terminal:fileExplorer.copyOriginalTitle"),children:g(N==="copied"?"terminal:fileExplorer.copied":N==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyOriginal")})]}),e.jsx("button",{className:`file-viewer-render-toggle ${o?"active":""}`,onClick:c,title:g(o?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderMarkdown"),children:o?"</>":"Aa"})]});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:G,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[o?e.jsx("div",{className:"file-viewer-markdown-wrapper",children:e.jsx("div",{className:"markdown-content",ref:l,children:e.jsx(Pn,{remarkPlugins:[Ln],children:t.content})})}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:f,className:"language-markdown",children:t.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${v.currentLine}/${v.totalLines}`,children:v.scrollPercentage===100?"END":v.scrollPercentage===0?"TOP":`${v.scrollPercentage}%`}),v.searchActive&&e.jsx(Zt,{query:v.searchQuery,onQueryChange:v.setSearchQuery,matchCount:v.searchMatches.length,currentIndex:v.currentMatchIndex,onNext:v.nextMatch,onPrev:v.prevMatch,onClose:v.clearSearch})]}),v.helpActive&&e.jsx(es,{onClose:v.toggleHelp})]})}function Ta({file:t,onRevealInTree:n,renderPlantUml:o,onToggleRender:c,editMode:r,onToggleEdit:i}){const{t:f}=le(["terminal"]),l=s.useRef(null),u=s.useRef(null),[g,j]=s.useState(null),[p,y]=s.useState(!1),[C,R]=s.useState(null),x=_s({containerRef:u,isEnabled:!0,content:t.content});s.useEffect(()=>{if(!o&&l.current){const d=Ft(t.extension);Os(d).then(()=>{l.current&&Gs(l.current)})}},[t,o]),s.useEffect(()=>{if(!o)return;if(!t.content.trim()){j(null),R("Diagram is empty");return}const d=new AbortController;return y(!0),R(null),(async()=>{try{const w=await fetch(va,{method:"POST",headers:{"Content-Type":"text/plain; charset=utf-8",Accept:"image/svg+xml"},body:t.content,signal:d.signal});if(!w.ok)throw new Error(`Render failed (${w.status})`);const S=await w.text();if(!S.includes("<svg"))throw new Error("Invalid SVG output");j(Ea(S))}catch(w){if(d.signal.aborted)return;const S=w instanceof Error?w.message:"Failed to render diagram";R(S),j(null)}finally{d.signal.aborted||y(!1)}})(),()=>d.abort()},[t.path,t.content,o]);const N=e.jsx("div",{className:"file-viewer-header-buttons",children:e.jsx("button",{className:`file-viewer-render-toggle ${o?"active":""}`,onClick:c,title:f(o?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderDiagram"),children:o?"</>":f("terminal:fileExplorer.diagram")})});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:N,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[o?e.jsxs("div",{className:"file-viewer-diagram-wrapper",children:[p&&e.jsx("div",{className:"file-viewer-placeholder",children:f("terminal:fileExplorer.renderingDiagram")}),!p&&g&&e.jsx("img",{src:g,alt:t.filename,className:"file-viewer-diagram-image"}),!p&&C&&e.jsxs("div",{className:"file-viewer-diagram-error",children:[e.jsxs("div",{children:[f("terminal:fileExplorer.couldNotRender"),": ",C]}),e.jsx("button",{className:"file-viewer-render-toggle",onClick:c,children:f("terminal:fileExplorer.showSource")})]})]}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:l,className:"language-plaintext",children:t.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${x.currentLine}/${x.totalLines}`,children:x.scrollPercentage===100?"END":x.scrollPercentage===0?"TOP":`${x.scrollPercentage}%`}),x.searchActive&&e.jsx(Zt,{query:x.searchQuery,onQueryChange:x.setSearchQuery,matchCount:x.searchMatches.length,currentIndex:x.currentMatchIndex,onNext:x.nextMatch,onPrev:x.prevMatch,onClose:x.clearSearch})]}),x.helpActive&&e.jsx(es,{onClose:x.toggleHelp})]})}function Ma({file:t,onRevealInTree:n}){const{t:o}=le(["common","terminal"]),c=()=>{if(t.dataUrl){const r=document.createElement("a");r.href=t.dataUrl,r.download=t.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:o("common:buttons.download"),children:o("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-image-wrapper",children:t.dataUrl?e.jsx("img",{src:t.dataUrl,alt:t.filename,className:"file-viewer-image"}):e.jsx("div",{className:"file-viewer-placeholder",children:o("terminal:fileExplorer.failedToLoadImage")})})]})}function Da({file:t,onRevealInTree:n}){const{t:o}=le(["common","terminal"]),c=()=>{if(t.dataUrl){const r=document.createElement("a");r.href=t.dataUrl,r.download=t.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:o("common:buttons.download"),children:o("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-pdf-wrapper",children:t.dataUrl?e.jsx("iframe",{src:t.dataUrl,title:t.filename,className:"file-viewer-pdf"}):e.jsx("div",{className:"file-viewer-placeholder",children:o("terminal:fileExplorer.failedToLoadPdf")})})]})}function Ra({file:t,onRevealInTree:n}){const{t:o}=le(["terminal","common"]),c=()=>{if(t.dataUrl){const i=document.createElement("a");i.href=t.dataUrl,i.download=t.filename,i.click()}},r=()=>{const i=t.extension.toLowerCase();return[".xlsx",".xls"].includes(i)?e.jsx(M,{name:"dashboard",size:48}):[".docx",".doc"].includes(i)?e.jsx(M,{name:"edit",size:48}):[".pptx",".ppt"].includes(i)?e.jsx(M,{name:"film",size:48}):[".zip",".tar",".gz",".rar",".7z"].includes(i)?e.jsx(M,{name:"file-zip",size:48}):[".mp3",".wav",".flac",".ogg"].includes(i)?e.jsx(M,{name:"music-note",size:48}):[".mp4",".avi",".mov",".mkv",".webm"].includes(i)?e.jsx(M,{name:"film",size:48}):[".exe",".dmg",".app",".msi"].includes(i)?e.jsx(M,{name:"gear",size:48}):[".apk",".aab",".ipa"].includes(i)?e.jsx(M,{name:"mobile",size:48}):[".jar",".war",".ear"].includes(i)?e.jsx(M,{name:"coffee",size:48}):[".iso",".img"].includes(i)?e.jsx(M,{name:"disc",size:48}):[".so",".dll",".dylib"].includes(i)?e.jsx(M,{name:"wrench",size:48}):e.jsx(M,{name:"folder",size:48})};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n}),e.jsxs("div",{className:"file-viewer-binary",children:[e.jsx("div",{className:"file-viewer-binary-icon",children:r()}),e.jsx("div",{className:"file-viewer-binary-name",children:t.filename}),e.jsx("div",{className:"file-viewer-binary-size",children:As(t.size)}),e.jsx("div",{className:"file-viewer-binary-message",children:o("terminal:fileExplorer.cannotPreview")}),e.jsx("button",{className:"file-viewer-download-btn large",onClick:c,children:o("terminal:fileExplorer.downloadFile")})]})]})}function Fa({file:t,loading:n,error:o,onRevealInTree:c,onFileEdited:r}){const{t:i}=le(["terminal","common"]),[f,l]=Na(),[u,g]=ka(),[j,p]=s.useState(!1);s.useEffect(()=>{p(!1)},[t==null?void 0:t.path]);const y=s.useCallback(async w=>{if(!t)return;const S=await Y(K("/api/files/write"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,content:w})});if(!S.ok){const A=await S.json().catch(()=>({error:"Save failed"}));throw new Error(A.error||"Save failed")}},[t]),C=s.useCallback(()=>{p(w=>(w&&t&&(r==null||r(t.path)),!w))},[t,r]),R=s.useCallback(()=>{t&&(r==null||r(t.path))},[t,r]);if(n)return e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")});if(o)return e.jsx("div",{className:"file-viewer-placeholder error",children:o});if(!t)return e.jsxs("div",{className:"file-viewer-placeholder",children:[e.jsx("div",{className:"placeholder-icon",children:e.jsx(M,{name:"folder-open",size:32})}),e.jsx("div",{className:"placeholder-text",children:i("terminal:fileExplorer.selectFileToView")})]});const x=t.fileType||"text",N=x==="text"&&wa(t.extension),d=x==="text"&&Ca(t.extension),v=N||d;return v&&j&&t.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ue,{file:t,onRevealInTree:c,editMode:!0,onToggleEdit:C}),e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:t.content,extension:t.extension,onSave:y,onCancel:C},t.path)})]}):x==="text"&&!v&&t.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ue,{file:t,onRevealInTree:c}),e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:t.content,extension:t.extension,onSave:y,onCancel:R},t.path)})]}):e.jsxs("div",{className:"file-viewer-content",children:[N&&e.jsx(Sa,{file:t,onRevealInTree:c,renderMarkdown:f,onToggleRender:l,editMode:j,onToggleEdit:C}),d&&!N&&e.jsx(Ta,{file:t,onRevealInTree:c,renderPlantUml:u,onToggleRender:g,editMode:j,onToggleEdit:C}),x==="image"&&e.jsx(Ma,{file:t,onRevealInTree:c}),x==="pdf"&&e.jsx(Da,{file:t,onRevealInTree:c}),x==="binary"&&e.jsx(Ra,{file:t,onRevealInTree:c})]})}const Vs=s.memo(Fa,(t,n)=>t.loading!==n.loading||t.error!==n.error?!1:t.file===null&&n.file===null?!0:t.file===null||n.file===null?!1:t.file.path===n.file.path&&t.file.content===n.file.content&&t.file.modified===n.file.modified);Vs.displayName="FileViewer";function Ks({text:t,query:n}){if(!n)return e.jsx(e.Fragment,{children:t});const o=Hn(t,n);if(o)return e.jsxs(e.Fragment,{children:[t.slice(0,o.start),e.jsx("mark",{className:"search-highlight",children:t.slice(o.start,o.end)}),t.slice(o.end)]});const c=n.toLowerCase(),i=t.toLowerCase().indexOf(c);return i===-1?e.jsx(e.Fragment,{children:t}):e.jsxs(e.Fragment,{children:[t.slice(0,i),e.jsx("mark",{className:"search-highlight",children:t.slice(i,i+n.length)}),t.slice(i+n.length)]})}const Ia=s.memo(function({node:n,query:o,isSelected:c,onSelect:r,lineNumber:i}){const f=n.isDirectory?null:Xt(n),l=n.path.split("/");l[l.length-1];const u=l.slice(0,-1).join("/");return e.jsxs("div",{className:`search-result-item ${c?"selected":""}`,onClick:()=>r(n),children:[n.isDirectory?e.jsx("span",{className:"search-result-icon",children:e.jsx(M,{name:"folder",size:14})}):f?e.jsx("span",{className:"search-result-icon",style:{backgroundImage:`url('${f}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"search-result-icon",children:e.jsx(M,{name:"file-text",size:14})}),e.jsxs("div",{className:"search-result-info",children:[e.jsxs("span",{className:"search-result-name",children:[e.jsx(Ks,{text:n.name,query:o}),i&&e.jsxs("span",{className:"search-result-line-badge",children:[":",i]})]}),e.jsx("span",{className:"search-result-path",children:u})]})]})}),Pa=s.memo(function({match:n,query:o,isSelected:c,onSelect:r}){const{t:i}=le(["terminal"]),f={name:n.name,path:n.path,isDirectory:!1,extension:n.extension},l=Xt(f),u=n.path.split("/"),g=u[u.length-1],j=u.slice(0,-1).join("/");return e.jsxs("div",{className:`content-search-item ${c?"selected":""}`,children:[e.jsxs("div",{className:`content-search-header ${c?"selected":""}`,onClick:()=>r(n.path),children:[l?e.jsx("span",{className:"content-search-icon",style:{backgroundImage:`url('${l}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"content-search-icon",children:e.jsx(M,{name:"file-text",size:14})}),e.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:"2px"},children:[e.jsx("span",{className:"content-search-name",children:g}),e.jsx("span",{className:"search-result-path",style:{fontSize:"10px"},children:j})]}),e.jsx("span",{className:"content-search-count",children:n.matches.length})]}),e.jsxs("div",{className:"content-search-matches",children:[n.matches.slice(0,5).map((p,y)=>e.jsxs("div",{className:"content-search-match",onClick:()=>r(n.path,p.line),children:[e.jsx("span",{className:"content-search-line-num",children:p.line}),e.jsx("span",{className:"content-search-line-content",children:e.jsx(Ks,{text:p.content.trim(),query:o})})]},`${n.path}-${p.line}-${y}`)),n.matches.length>5&&e.jsxs("div",{className:"content-search-match",style:{opacity:.6,cursor:"default"},children:[e.jsx("span",{className:"content-search-line-num",children:"..."}),e.jsx("span",{className:"content-search-line-content",children:i("terminal:fileExplorer.moreMatches",{count:n.matches.length-5})})]})]})]})});function La({filenameResults:t,contentResults:n,onSelectFile:o,onSelectContent:c,selectedPath:r,query:i,lineNumber:f}){const{t:l}=le(["terminal"]),u=t.length>0,g=n.length>0;return!u&&!g?e.jsx("div",{className:"search-no-results",children:l("terminal:fileExplorer.noMatchesFound")}):e.jsxs("div",{className:"unified-search-results",children:[u&&e.jsxs("div",{className:"unified-search-section",children:[e.jsxs("div",{className:"unified-search-section-header",children:[e.jsx("span",{className:"unified-search-section-icon",children:e.jsx(M,{name:"file-text",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:l("terminal:fileExplorer.files")}),e.jsx("span",{className:"unified-search-section-count",children:t.length})]}),e.jsx("div",{className:"unified-search-section-content",children:t.map(j=>e.jsx(Ia,{node:j,query:i,isSelected:r===j.path,onSelect:o,lineNumber:f},j.path))})]}),g&&e.jsxs("div",{className:"unified-search-section",children:[e.jsxs("div",{className:"unified-search-section-header",children:[e.jsx("span",{className:"unified-search-section-icon",children:e.jsx(M,{name:"edit",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:l("terminal:fileExplorer.content")}),e.jsx("span",{className:"unified-search-section-count",children:l("terminal:fileExplorer.matchesInFiles",{matches:n.reduce((j,p)=>j+p.matches.length,0),files:n.length})})]}),e.jsx("div",{className:"unified-search-section-content",children:n.map(j=>e.jsx(Pa,{match:j,query:i,isSelected:r===j.path,onSelect:c},j.path))})]})]})}const Ws=s.memo(La,(t,n)=>!(t.query!==n.query||t.selectedPath!==n.selectedPath||t.filenameResults.length!==n.filenameResults.length||t.contentResults.length!==n.contentResults.length));Ws.displayName="UnifiedSearchResults";const $a=s.memo(function({file:n,isSelected:o,onSelect:c,onStage:r,isStaging:i,showDirPath:f,isChecked:l,onToggleCheck:u,onContextMenu:g,onDiscard:j}){const{t:p}=le(["terminal"]),y=n.status,C=pt[y],R=y==="deleted",x=y==="untracked"&&r,N=n.name.includes(".")?"."+n.name.split(".").pop():"",d=f&&n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return e.jsxs("div",{className:`git-file-item ${o?"selected":""}`,onClick:()=>!R&&c(n.path,y),onContextMenu:v=>{v.preventDefault(),g==null||g(v,n,y)},style:{cursor:R?"not-allowed":"pointer"},title:n.path,children:[u&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:l||!1,onChange:v=>{v.stopPropagation(),u(n.path)},onClick:v=>v.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(N),alt:"file"}),e.jsxs("span",{className:"git-file-name",children:[n.name,d&&e.jsx("span",{className:"git-file-dir",children:d})]}),e.jsx("span",{className:"git-file-status",style:{color:C.color},children:C.icon}),n.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:[e.jsx(M,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.oldPath.split("/").pop()]}),x&&e.jsx("button",{className:`git-stage-btn ${i?"staging":""}`,onClick:v=>{v.stopPropagation(),i||r(n.path)},title:p("terminal:fileExplorer.stageFile"),disabled:i,children:i?"...":"+"}),j&&e.jsx("button",{className:"git-discard-btn",onClick:v=>{v.stopPropagation(),j(n,y)},title:y==="untracked"||y==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}),Ha=16,za=22,Aa=s.memo(function t({node:n,depth:o,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:l,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:y,onDiscard:C}){const{t:R}=le(["terminal"]),x=o*Ha;if(!n.isDirectory){const d=n.file.status,v=pt[d];return e.jsxs("div",{className:`git-file-item ${i===n.path?"selected":""}`,onClick:()=>d!=="deleted"&&f(n.file.path,d),onContextMenu:w=>{w.preventDefault(),p==null||p(w,n.file,d)},style:{paddingLeft:`${x+za}px`,cursor:d==="deleted"?"not-allowed":"pointer"},title:n.file.path,children:[j&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:(g==null?void 0:g.has(n.file.path))||!1,onChange:w=>{w.stopPropagation(),j(n.file.path)},onClick:w=>w.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(n.file.name.includes(".")?"."+n.file.name.split(".").pop():""),alt:"file"}),e.jsx("span",{className:"git-file-name",children:n.file.name}),e.jsx("span",{className:"git-file-status",style:{color:v.color},children:v.icon}),n.file.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:[e.jsx(M,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.file.oldPath.split("/").pop()]}),d==="untracked"&&l&&e.jsx("button",{className:`git-stage-btn ${u!=null&&u.has(n.path)?"staging":""}`,onClick:w=>{w.stopPropagation(),u!=null&&u.has(n.path)||l(n.file.path)},title:R("terminal:fileExplorer.stageFile"),disabled:u==null?void 0:u.has(n.path),children:u!=null&&u.has(n.path)?"...":"+"}),C&&e.jsx("button",{className:"git-discard-btn",onClick:w=>{w.stopPropagation(),C(n.file,d)},title:d==="untracked"||d==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}const N=c.has(n.path);return e.jsxs("div",{className:"tree-node-wrapper",children:[e.jsxs("div",{className:`tree-node directory ${N?"expanded":""}`,style:{paddingLeft:`${x}px`},onClick:()=>r(n.path),onContextMenu:d=>{d.preventDefault(),d.stopPropagation(),y==null||y(d,n)},children:[e.jsx("span",{className:`tree-arrow ${N?"expanded":""}`,children:e.jsx(M,{name:"caret-right",size:10})}),e.jsx("img",{className:"tree-folder-icon",src:N?"/assets/vscode-icons/default_folder_opened.svg":"/assets/vscode-icons/default_folder.svg",alt:"folder"}),e.jsx("span",{className:"tree-name",children:n.name}),e.jsx("span",{className:"git-tree-file-count",children:R("terminal:fileExplorer.fileCount",{count:n.fileCount})})]}),N&&e.jsx("div",{className:"tree-children",children:n.children.map(d=>e.jsx(t,{node:d,depth:o+1,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:l,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:y,onDiscard:C},d.path))})]})}),qt=s.memo(function({groupLabel:n,groupIcon:o,groupColor:c,files:r,treeNodes:i,viewMode:f,selectedPath:l,expandedDirs:u,onToggleDir:g,onFileSelect:j,onStageFile:p,onStageAll:y,stagingPaths:C,checkedFiles:R,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscardFile:v,onDiscardAll:w}){const{t:S}=le(["terminal"]);if(r.length===0)return null;const A=r.some(z=>z.status==="untracked"),H=A&&y&&r.length>0,G=C?r.every(z=>C.has(z.path)):!1;return e.jsxs("div",{className:"git-status-group",children:[e.jsxs("div",{className:"git-status-group-header",style:{color:c},children:[e.jsx("span",{className:"git-status-badge",style:{background:c},children:o}),n," (",r.length,")",H&&e.jsx("button",{className:`git-stage-all-btn ${G?"staging":""}`,onClick:z=>{z.stopPropagation(),G||y()},title:S("terminal:fileExplorer.stageAllUntracked"),disabled:G,children:G?"...":S("terminal:fileExplorer.stageAll")}),w&&e.jsxs("button",{className:"git-discard-all-btn",onClick:z=>{z.stopPropagation(),w()},title:A?`Delete all ${r.length} files`:`Discard all ${r.length} changes`,children:[e.jsx(M,{name:"revert",size:12})," All"]})]}),f==="tree"?e.jsx("div",{className:"git-tree-content",children:i.map(z=>e.jsx(Aa,{node:z,depth:0,expandedDirs:u,onToggleDir:g,selectedPath:l,onSelect:j,onStage:p,stagingPaths:C,checkedFiles:R,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscard:v},z.path))}):e.jsx("div",{className:"git-flat-content",children:r.map(z=>e.jsx($a,{file:z,isSelected:l===z.path,onSelect:j,onStage:z.status==="untracked"?p:void 0,isStaging:C==null?void 0:C.has(z.path),showDirPath:!0,isChecked:R==null?void 0:R.has(z.path),onToggleCheck:x,onContextMenu:N,onDiscard:v},z.path))})]})});function Oa({gitStatus:t,loading:n,onFileSelect:o,selectedPath:c,onRefresh:r,onStageFiles:i,stagingPaths:f,currentFolder:l,onCommitComplete:u,mergeInProgress:g,mergingBranch:j,onMergeContinue:p,onMergeAbort:y,onConflictOpen:C,onRevealInTree:R}){const{t:x}=le(["terminal","common"]),[N,d]=s.useState("tree"),[v,w]=s.useState(new Set),[S,A]=s.useState(""),[H,G]=s.useState(""),[z,ae]=s.useState(!1),[ee,D]=s.useState(new Set),[F,I]=s.useState(!1),[re,_]=s.useState(null),ge=s.useRef(null),{showToast:O}=Us(),[Z,L]=s.useState(null),[T,W]=s.useState(null),[ne,be]=s.useState(null),de=s.useCallback((k,P)=>{be({files:[k],label:k.name})},[]),m=s.useCallback(async()=>{if(!(!ne||!l))try{const k=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:ne.files.map(B=>({path:B.path,status:B.status})),directory:l})}),P=await k.json();k.ok&&P.success?(O("success","Discarded",`Reverted ${ne.files.length} file(s)`),r()):O("error","Discard Failed",P.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}finally{be(null)}},[ne,l,r,O]),q=s.useCallback((k,P,B)=>{k.preventDefault(),k.stopPropagation(),L({isOpen:!0,position:{x:k.clientX,y:k.clientY},file:P,status:B})},[]),ie=s.useCallback(async(k,P)=>{if(l)try{const B=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{path:k.path,status:P}],directory:l})}),ke=await B.json();B.ok&&ke.success?(O("success","Discarded",`Restored ${k.name}`),r()):O("error","Discard Failed",ke.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}},[l,r,O]),ue=s.useCallback(async k=>{try{await navigator.clipboard.writeText(k),O("success","Copied","Full path copied")}catch{O("error","Copy Failed","Could not copy path")}},[O]),V=s.useCallback(async k=>{const P=l&&k.startsWith(l+"/")?k.slice(l.length+1):k;try{await navigator.clipboard.writeText(P),O("success","Copied","Relative path copied")}catch{O("error","Copy Failed","Could not copy path")}},[l,O]),E=s.useMemo(()=>{if(!Z)return[];const{file:k,status:P}=Z,B=[];return P==="conflict"&&C?B.push({id:"open-conflict",label:x("terminal:fileExplorer.gitContextMenu.openConflictResolver"),icon:e.jsx(M,{name:"warn",size:14}),onClick:()=>C(k.path)}):P!=="deleted"&&B.push({id:"open-file",label:x("terminal:fileExplorer.gitContextMenu.openFile"),icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>o(k.path,P)}),P!=="conflict"&&B.push({id:"stage-file",label:x("terminal:fileExplorer.gitContextMenu.stageFile"),icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i([k.path])}}),B.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),(P==="modified"||P==="deleted"||P==="renamed"||P==="conflict")&&B.push({id:"discard-changes",label:x("terminal:fileExplorer.gitContextMenu.discardChanges"),icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{ie(k,P)}}),(P==="untracked"||P==="added")&&B.push({id:"delete-file",label:x("terminal:fileExplorer.gitContextMenu.deleteFile"),icon:e.jsx(M,{name:"trash",size:14}),danger:!0,onClick:()=>{ie(k,P)}}),B.push({id:"divider-2",label:"",divider:!0,onClick:()=>{}}),B.push({id:"copy-full-path",label:x("terminal:fileExplorer.gitContextMenu.copyFullPath"),icon:e.jsx(M,{name:"pin",size:14}),onClick:()=>{ue(k.path)}}),B.push({id:"copy-relative-path",label:x("terminal:fileExplorer.gitContextMenu.copyRelativePath"),icon:e.jsx(M,{name:"clipboard",size:14}),onClick:()=>{V(k.path)}}),R&&P!=="deleted"&&B.push({id:"reveal-in-tree",label:x("terminal:fileExplorer.gitContextMenu.revealInTree"),icon:e.jsx(M,{name:"target",size:14}),onClick:()=>R(k.path)}),B},[Z,o,i,C,R,ie,ue,V,x]),Q=s.useCallback((k,P)=>{k.preventDefault(),k.stopPropagation(),W({isOpen:!0,position:{x:k.clientX,y:k.clientY},node:P})},[]),te=s.useCallback(k=>!k.isDirectory&&k.file?[k.file]:k.children.flatMap(P=>te(P)),[]),Ne=s.useCallback(async k=>{if(!l)return;const P=te(k);if(P.length!==0)try{const B=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:P.map(Te=>({path:Te.path,status:Te.status})),directory:l})}),ke=await B.json();B.ok&&ke.success?(O("success","Discarded",`Reverted ${P.length} file(s) in ${k.name}`),r()):O("error","Discard Failed",ke.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}},[l,te,r,O]),xe=s.useMemo(()=>{if(!T)return[];const{node:k}=T,P=te(k);return[{id:"discard-dir",label:`Discard Changes (${P.length} files)`,icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{Ne(k)}},{id:"stage-dir",label:`Stage All (${P.length} files)`,icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i(P.map(B=>B.path))}}]},[T,te,Ne,i]),U=s.useCallback(k=>{w(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),{conflictFiles:se,conflictTree:pe,changesFiles:me,changesTree:Be,untrackedFiles:Se,untrackedTree:It,allDirPaths:He}=s.useMemo(()=>{if(!t||!t.isGitRepo||t.files.length===0)return{conflictFiles:[],conflictTree:[],changesFiles:[],changesTree:[],untrackedFiles:[],untrackedTree:[],allDirPaths:new Set};const k=new Set,P=t.files.filter(Re=>Re.status==="conflict"),B=Mt(P);Dt(B,k);const ke=t.files.filter(Re=>Re.status==="modified"||Re.status==="added"||Re.status==="deleted"||Re.status==="renamed"),Te=Mt(ke);Dt(Te,k);const ot=t.files.filter(Re=>Re.status==="untracked"),We=Mt(ot);return Dt(We,k),{conflictFiles:P,conflictTree:B,changesFiles:ke,changesTree:Te,untrackedFiles:ot,untrackedTree:We,allDirPaths:k}},[t]);s.useEffect(()=>{w(He)},[He]),s.useEffect(()=>{t!=null&&t.files&&D(new Set(t.files.map(k=>k.path)))},[t==null?void 0:t.files]);const Pt=s.useCallback(()=>{me.length!==0&&be({files:me,label:`${me.length} changed files`})},[me]),_e=s.useCallback(()=>{Se.length!==0&&be({files:Se,label:`${Se.length} unversioned files`})},[Se]),Lt=s.useCallback(()=>{se.length!==0&&be({files:se,label:`${se.length} conflicted files`})},[se]),Ve=se.length>0;s.useEffect(()=>{if(re){const k=re.type==="error"?8e3:4e3,P=setTimeout(()=>_(null),k);return()=>clearTimeout(P)}},[re]);const gt=s.useCallback(async()=>{const k=!z;if(ae(k),k&&l){G(S);try{const B=await(await Y(K(`/api/files/git-log-message?path=${encodeURIComponent(l)}`))).json();B.message&&A(B.message)}catch{}}else A(H)},[z,l,S,H]),je=s.useCallback(k=>{D(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),$t=s.useCallback(()=>{if(!(t!=null&&t.files))return;const k=t.files.map(B=>B.path),P=k.every(B=>ee.has(B));D(P?new Set:new Set(k))},[t==null?void 0:t.files,ee]),ve=s.useCallback(async k=>{if(!(!l||!S.trim()||ee.size===0||F)){I(!0),_(null);try{const P=await Y(K("/api/files/git-commit"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:l,message:S.trim(),amend:z,paths:Array.from(ee)})}),B=await P.json();if(!P.ok||!B.success){_({type:"error",text:B.error||"Commit failed"}),I(!1);return}if(k)try{const ke=await Y(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:l})}),Te=await ke.json();ke.ok&&Te.success?_({type:"success",text:x("terminal:fileExplorer.committedAndPushed")}):_({type:"error",text:x("terminal:fileExplorer.committedButPushFailed",{error:Te.error||"Unknown error"})})}catch{_({type:"error",text:x("terminal:fileExplorer.committedButPushFailed",{error:"Network error"})})}else _({type:"success",text:x("terminal:fileExplorer.committedSuccessfully")});A(""),G(""),ae(!1),r(),u==null||u()}catch(P){_({type:"error",text:P.message||"Commit failed"})}finally{I(!1)}}},[l,S,z,ee,F,r,u]);if(n)return e.jsx("div",{className:"git-changes-loading",children:x("terminal:fileExplorer.loadingGitStatus")});if(!t||!t.isGitRepo)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"package",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.notGitRepo")})]});if(t.files.length===0)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"sparkle",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.workingTreeClean")}),e.jsx("div",{className:"git-empty-branch",children:x("terminal:fileExplorer.onBranch",{branch:t.branch})})]});const xt=k=>{i([k])},Ke=()=>{const k=Se.map(P=>P.path);k.length>0&&i(k)},De=(k,P)=>{P==="conflict"&&C?C(k):o(k,P)};return e.jsxs("div",{className:"git-changes",children:[e.jsxs("div",{className:"git-changes-header",children:[e.jsxs("span",{className:"git-branch",children:[e.jsx("span",{className:"git-branch-icon",children:e.jsx(M,{name:"git-branch",size:12})}),t.branch]}),t.counts&&e.jsxs("div",{className:"git-changes-summary",children:[(t.counts.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[t.counts.conflict,"C"]}),t.counts.modified>0&&e.jsxs("span",{className:"git-count modified",children:[t.counts.modified,"M"]}),t.counts.added>0&&e.jsxs("span",{className:"git-count added",children:[t.counts.added,"A"]}),t.counts.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[t.counts.deleted,"D"]}),t.counts.untracked>0&&e.jsxs("span",{className:"git-count untracked",children:[t.counts.untracked,"?"]})]}),e.jsxs("div",{className:"git-view-toggle",children:[e.jsx("button",{className:`git-view-toggle-btn ${N==="flat"?"active":""}`,onClick:()=>d("flat"),title:x("terminal:fileExplorer.flatList"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"2",y:"3",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"7",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"11",width:"12",height:"1.5",rx:"0.5"})]})}),e.jsx("button",{className:`git-view-toggle-btn ${N==="tree"?"active":""}`,onClick:()=>d("tree"),title:x("terminal:fileExplorer.directoryTree"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"1",y:"2",width:"6",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"5.5",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"9",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"7",y:"12.5",width:"7",height:"1.5",rx:"0.5"})]})})]}),e.jsx("button",{className:"git-refresh-btn",onClick:r,title:x("common:buttons.refresh"),children:e.jsx(M,{name:"refresh",size:12})})]}),g&&e.jsxs("div",{className:"git-merge-banner",children:[e.jsx("span",{className:"git-merge-banner-icon",children:"⚠"}),e.jsx("span",{className:"git-merge-banner-text",children:x("terminal:fileExplorer.mergeInProgress",{branch:j?` (${j})`:""})}),e.jsxs("div",{className:"git-merge-actions",children:[e.jsx("button",{className:"git-merge-continue-btn",onClick:p,disabled:Ve,title:x(Ve?"terminal:fileExplorer.resolveAllConflictsFirst":"terminal:fileExplorer.continueMerge"),children:x("terminal:fileExplorer.continue")}),e.jsx("button",{className:"git-merge-abort-btn",onClick:y,title:x("terminal:fileExplorer.abortMerge"),children:x("terminal:fileExplorer.abort")})]})]}),e.jsxs("div",{className:"git-changes-list",children:[e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.conflicts"),groupIcon:"C",groupColor:"#ff5555",files:se,treeNodes:pe,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Lt}),e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.changes"),groupIcon:"~",groupColor:"#c89a5a",files:me,treeNodes:Be,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Pt}),e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.unversioned"),groupIcon:"?",groupColor:"#6ab8c8",files:Se,treeNodes:It,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,onStageFile:xt,onStageAll:Ke,stagingPaths:f,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:_e})]}),e.jsxs("div",{className:"git-commit-panel",children:[e.jsxs("div",{className:"git-commit-options",children:[e.jsxs("label",{className:"git-commit-amend-label",children:[e.jsx("input",{type:"checkbox",className:"git-commit-amend-checkbox",checked:z,onChange:gt}),x("terminal:fileExplorer.amend")]}),e.jsx("span",{className:"git-commit-file-count",children:x("terminal:fileExplorer.fileCount",{count:ee.size})}),e.jsx("button",{className:"git-commit-select-toggle",onClick:$t,title:ee.size===t.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll"),children:ee.size===t.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll")})]}),e.jsx("textarea",{ref:ge,className:"git-commit-message",placeholder:x("terminal:fileExplorer.commitMessagePlaceholder"),value:S,onChange:k=>A(k.target.value),onKeyDown:k=>{(k.metaKey||k.ctrlKey)&&k.key==="Enter"&&(k.preventDefault(),ve(!1)),(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="Enter"&&(k.preventDefault(),ve(!0)),k.stopPropagation()},rows:3,disabled:F}),re&&e.jsx("div",{className:`git-commit-status ${re.type}`,children:re.text}),e.jsxs("div",{className:"git-commit-actions",children:[e.jsx("button",{className:"git-commit-btn",onClick:()=>ve(!1),disabled:!S.trim()||ee.size===0||F,title:x("terminal:fileExplorer.commitCtrlEnter"),children:x(F?"terminal:fileExplorer.committing":"terminal:fileExplorer.commitAction")}),e.jsx("button",{className:"git-commit-push-btn",onClick:()=>ve(!0),disabled:!S.trim()||ee.size===0||F,title:x("terminal:fileExplorer.commitAndPushCtrlShiftEnter"),children:F?"...":x("terminal:fileExplorer.commitAndPush")})]})]}),Z&&e.jsx(it,{isOpen:Z.isOpen,position:Z.position,worldPosition:{x:0,z:0},actions:E,onClose:()=>L(null)}),T&&e.jsx(it,{isOpen:T.isOpen,position:T.position,worldPosition:{x:0,z:0},actions:xe,onClose:()=>W(null)}),ne&&e.jsx("div",{className:"git-discard-confirm-overlay",onClick:()=>be(null),children:e.jsxs("div",{className:"git-discard-confirm",onClick:k=>k.stopPropagation(),children:[e.jsx("p",{children:ne.files.some(k=>k.status==="untracked"||k.status==="added")?e.jsxs(e.Fragment,{children:["Delete ",e.jsx("strong",{children:ne.label}),"?"]}):e.jsxs(e.Fragment,{children:["Discard changes to ",e.jsx("strong",{children:ne.label}),"?"]})}),e.jsx("p",{className:"git-discard-confirm-hint",children:"This cannot be undone."}),e.jsxs("div",{className:"git-discard-confirm-actions",children:[e.jsx("button",{className:"git-discard-confirm-cancel",onClick:()=>be(null),children:"Cancel"}),e.jsx("button",{className:"git-discard-confirm-btn",onClick:m,children:ne.files.some(k=>k.status==="untracked"||k.status==="added")?"Delete":"Discard"})]})]})})]})}const Ys=s.memo(Oa,(t,n)=>t.loading!==n.loading||t.selectedPath!==n.selectedPath||t.stagingPaths!==n.stagingPaths||t.currentFolder!==n.currentFolder||t.mergeInProgress!==n.mergeInProgress||t.mergingBranch!==n.mergingBranch?!1:t.gitStatus===null&&n.gitStatus===null?!0:!(t.gitStatus===null||n.gitStatus===null||t.gitStatus.isGitRepo!==n.gitStatus.isGitRepo||t.gitStatus.branch!==n.gitStatus.branch||t.gitStatus.files.length!==n.gitStatus.files.length||t.gitStatus.mergeInProgress!==n.gitStatus.mergeInProgress));Ys.displayName="GitChanges";const Ga=s.memo(function({tab:n,isActive:o,onSelect:c,onClose:r,onContextMenu:i}){const{t:f}=le(["terminal"]),l={name:n.filename,path:n.path,isDirectory:!1,extension:n.extension},u=s.useCallback(()=>{c(n.path)},[c,n.path]),g=s.useCallback(y=>{y.button===1&&(y.preventDefault(),y.stopPropagation(),r(n.path))},[r,n.path]),j=s.useCallback(y=>{y.preventDefault(),y.stopPropagation(),r(n.path)},[r,n.path]),p=s.useCallback(y=>{y.preventDefault(),y.stopPropagation(),i(y,n)},[i,n]);return e.jsxs("div",{className:`file-tab ${o?"active":""}`,onClick:u,onMouseDown:g,onContextMenu:p,title:n.path,children:[e.jsx("img",{className:"file-tab-icon",src:Xt(l),alt:"file"}),e.jsx("span",{className:"file-tab-name",children:n.filename}),e.jsx("button",{className:"file-tab-close",onClick:j,title:f("terminal:fileExplorer.closeMiddleClick"),children:"×"})]})});function Ua(t){return typeof t.path=="string"&&t.path.startsWith("/")}function Ba({tabs:t,activeTabPath:n,onSelectTab:o,onCloseTab:c,onCloseAllTabs:r,onShowGitHistory:i}){const{t:f}=le(["terminal"]),[l,u]=s.useState(null),g=s.useCallback((y,C)=>{u({isOpen:!0,position:{x:y.clientX,y:y.clientY},tab:C})},[]),j=s.useCallback(()=>u(null),[]),p=s.useMemo(()=>{if(!l)return[];const y=l.tab,C=!!i&&Ua(y),R=[{id:"git-history",label:f("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(M,{name:"git-commit",size:14}),disabled:!C,onClick:()=>{C&&i(y.path)}}];return r&&R.push({id:"divider-close-all",label:"",divider:!0,onClick:()=>{}},{id:"close-all-tabs",label:f("terminal:fileExplorer.closeAllTabs")??"Close all tabs",icon:e.jsx(M,{name:"cross",size:14}),danger:!0,onClick:()=>r()}),R},[l,i,r,f]);return t.length===0?null:e.jsxs("div",{className:"file-tabs-bar",children:[e.jsx("div",{className:"file-tabs-container",children:t.map(y=>e.jsx(Ga,{tab:y,isActive:n===y.path,onSelect:o,onClose:c,onContextMenu:g},y.path))}),l&&e.jsx(it,{isOpen:l.isOpen,position:l.position,worldPosition:{x:0,z:0},actions:p,onClose:j})]})}const qs=s.memo(Ba,(t,n)=>{if(t.activeTabPath!==n.activeTabPath||t.tabs.length!==n.tabs.length||t.onShowGitHistory!==n.onShowGitHistory||t.onCloseAllTabs!==n.onCloseAllTabs)return!1;for(let o=0;o<t.tabs.length;o++)if(t.tabs[o].path!==n.tabs[o].path)return!1;return!0});qs.displayName="FileTabs";const _a=s.memo(function({currentFolder:n,gitStatus:o,onBranchChanged:c,onMerge:r,onCompare:i,onPullConflicts:f}){const{t:l}=le(["terminal","common"]),[u,g]=s.useState(!1),[j,p]=s.useState(""),[y,C]=s.useState(!1),[R,x]=s.useState(""),[N,d]=s.useState(!1),[v,w]=s.useState(null),[S,A]=s.useState(null),H=s.useRef(null),G=s.useRef(null),z=s.useRef(null),{branches:ae,loading:ee,operationInProgress:D,loadBranches:F,checkoutBranch:I,createBranch:re,pullFromRemote:_,pushToRemote:ge}=Qt();s.useEffect(()=>{u&&n&&(F(n),setTimeout(()=>{var E;return(E=G.current)==null?void 0:E.focus()},50)),u||(p(""),C(!1),x(""),w(null))},[u,n,F]),s.useEffect(()=>{if(v){const E=v.type==="error"?8e3:3e3,Q=setTimeout(()=>w(null),E);return()=>clearTimeout(Q)}},[v]),s.useEffect(()=>{y&&setTimeout(()=>{var E;return(E=z.current)==null?void 0:E.focus()},50)},[y]),s.useEffect(()=>{if(!u)return;const E=te=>{const Ne=te.target;!Ne.closest(".branch-widget-selector")&&!Ne.closest(".branch-widget-dropdown")&&g(!1)},Q=te=>{te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),g(!1))};return document.addEventListener("click",E),document.addEventListener("keydown",Q,!0),()=>{document.removeEventListener("click",E),document.removeEventListener("keydown",Q,!0)}},[u]);const O=s.useCallback(async E=>{if(!n||D||E.isCurrent)return;const Q=await I(n,E.name);Q.success?(w({type:"success",text:l("terminal:fileExplorer.switchedToBranch",{branch:Q.branch||E.name})}),c(),F(n)):w({type:"error",text:Q.error||l("terminal:fileExplorer.checkoutFailed")})},[n,D,I,c,F]),Z=s.useCallback(async()=>{if(!n||!R.trim()||D)return;const E=await re(n,R.trim());E.success?(w({type:"success",text:l("terminal:fileExplorer.createdBranch",{branch:E.branch})}),C(!1),x(""),c(),F(n)):w({type:"error",text:E.error||l("terminal:fileExplorer.createBranchFailed")})},[n,R,D,re,c,F]),L=s.useCallback(async()=>{if(!n||D)return;const E=await _(n);E.success?(E.stashConflicts&&E.stashConflicts.length>0?(w({type:"error",text:`Pull succeeded but stash pop had conflicts: ${E.stashConflicts.length} file(s). Resolve manually.`}),f==null||f(E.stashConflicts),g(!1)):E.stashed?w({type:"success",text:"Pull complete. Local changes were auto-stashed and restored."}):w({type:"success",text:l("terminal:fileExplorer.pullComplete")}),c(),F(n)):E.conflicts&&E.conflicts.length>0?(w({type:"error",text:`Pull conflicts: ${E.conflicts.length} file(s)`}),f==null||f(E.conflicts),g(!1)):w({type:"error",text:E.error||l("terminal:fileExplorer.pullFailed")})},[n,D,_,c,F,f]),T=s.useCallback(async()=>{if(!n||D)return;const E=await ge(n);E.success?w({type:"success",text:l("terminal:fileExplorer.pushComplete")}):w({type:"error",text:E.error||l("terminal:fileExplorer.pushFailed")})},[n,D,ge]),[W,ne]=s.useState(!1),be=s.useCallback(async()=>{if(!(!n||D||W)){ne(!0);try{const E=await Y(K("/api/files/git-fetch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(E.ok)w({type:"success",text:"Fetch complete"}),c(),F(n);else{const Q=await E.json().catch(()=>({error:"Fetch failed"}));w({type:"error",text:Q.error||"Fetch failed"})}}catch{w({type:"error",text:"Fetch failed"})}finally{ne(!1)}}},[n,D,W,c,F]),de=(o==null?void 0:o.branch)||"unknown",m=!!D,q=s.useCallback((E,Q)=>{Q.isCurrent||(E.preventDefault(),E.stopPropagation(),A({isOpen:!0,position:{x:E.clientX,y:E.clientY},branch:Q.name}))},[]),ie=s.useMemo(()=>{if(!S)return[];const E=!!D||(o==null?void 0:o.mergeInProgress);return[{id:"compare",label:l("terminal:fileExplorer.showDiffWith",{branch:S.branch}),icon:e.jsx(M,{name:"arrows-horizontal",size:14}),disabled:!!D,onClick:()=>{i==null||i(S.branch),g(!1)}},{id:"merge",label:l("terminal:fileExplorer.mergeInto",{source:S.branch,target:de}),icon:"⤵",disabled:!!E,onClick:()=>{r&&r(S.branch),g(!1)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"checkout",label:l("terminal:fileExplorer.checkoutBranch",{branch:S.branch}),icon:e.jsx(M,{name:"git-branch",size:14}),disabled:!!D,onClick:()=>{const Q=ae.find(te=>te.name===S.branch);Q&&O(Q)}}]},[S,D,o==null?void 0:o.mergeInProgress,de,r,i,ae,O]),ue=s.useMemo(()=>{const E=ae.filter(te=>!te.isRemote);if(!j)return E;const Q=j.toLowerCase();return E.filter(te=>te.name.toLowerCase().includes(Q))},[ae,j]),V=s.useMemo(()=>{const E=ae.filter(te=>te.isRemote);if(!j)return E;const Q=j.toLowerCase();return E.filter(te=>te.name.toLowerCase().includes(Q))},[ae,j]);return e.jsxs("div",{className:"branch-widget",style:{position:"relative"},children:[e.jsxs("div",{className:"branch-widget-selector",onClick:E=>{E.stopPropagation(),g(!u)},title:`Branch: ${de}`,children:[e.jsx("svg",{className:"branch-widget-icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M5 3.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm0 2.122a2.25 2.25 0 1 0-1 0v1.836A2.25 2.25 0 0 0 5.75 9.5h1.378a2.251 2.251 0 1 0 0-1H5.75a1.25 1.25 0 0 1-1.25-1.25V5.372Zm7.75 4.878a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3-8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"})}),e.jsx("span",{className:"branch-widget-name",children:de}),e.jsx("span",{className:"branch-widget-arrow",children:"▼"})]}),u&&e.jsxs("div",{className:"branch-widget-dropdown",ref:H,children:[e.jsx("div",{className:"branch-widget-search",children:e.jsx("input",{ref:G,type:"text",className:"branch-widget-search-input",placeholder:l("terminal:fileExplorer.searchBranches"),value:j,onChange:E=>p(E.target.value),onKeyDown:E=>E.stopPropagation()})}),v&&e.jsx("div",{className:`branch-widget-status ${v.type}`,children:v.text}),e.jsx("div",{className:"branch-widget-section-header",children:l("terminal:fileExplorer.actions")}),e.jsxs("div",{className:"branch-widget-actions",children:[e.jsxs("div",{className:`branch-widget-action-item ${m||W?"disabled":""}`,onClick:be,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 13l-3-3h2V6h2v4h2l-3 3zM8 3l3 3h-2v4H7V6H5l3-3z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:W?"Fetching...":"Fetch"})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:L,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 12l-4-4h2.5V3h3v5H12L8 12z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:l(D==="pull"?"terminal:fileExplorer.pulling":"terminal:fileExplorer.pull")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:T,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 4l4 4h-2.5v5h-3V8H4l4-4z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:l(D==="push"?"terminal:fileExplorer.pushing":"terminal:fileExplorer.push")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:()=>{m||C(!y)},children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 2v5H3v2h5v5h2V9h5V7H10V2H8z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:l("terminal:fileExplorer.newBranch")})]})]}),y&&e.jsxs("div",{className:"branch-widget-new-branch",children:[e.jsx("input",{ref:z,type:"text",className:"branch-widget-new-branch-input",placeholder:l("terminal:fileExplorer.branchNamePlaceholder"),value:R,onChange:E=>x(E.target.value),onKeyDown:E=>{E.stopPropagation(),E.key==="Enter"&&Z(),E.key==="Escape"&&(C(!1),x(""))}}),e.jsx("button",{className:"branch-widget-new-branch-confirm",onClick:Z,disabled:!R.trim()||m,children:D==="create"?"...":l("common:buttons.create")})]}),e.jsxs("div",{className:"branch-widget-section-header",children:[l("terminal:fileExplorer.localBranches"),ee&&e.jsxs("span",{className:"branch-widget-loading-hint",children:[" ",l("terminal:fileExplorer.loading")]})]}),e.jsxs("div",{className:"branch-widget-branch-list",children:[ue.length===0&&!ee&&e.jsx("div",{className:"branch-widget-empty",children:l("terminal:fileExplorer.noBranchesFound")}),ue.map(E=>e.jsxs("div",{className:`branch-widget-branch-item ${E.isCurrent?"current":""} ${m?"disabled":""}`,onClick:()=>O(E),onContextMenu:Q=>q(Q,E),title:E.lastMessage||E.name,children:[e.jsxs("span",{className:"branch-widget-branch-name",children:[E.isCurrent&&e.jsx("span",{className:"branch-widget-current-marker",children:"*"}),E.name]}),E.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:E.lastCommit})]},E.name))]}),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"branch-widget-section-header clickable",onClick:()=>d(!N),children:[e.jsx("span",{className:"branch-widget-section-toggle",children:N?"▾":"▸"}),l("terminal:fileExplorer.remoteBranches",{count:V.length})]}),N&&e.jsx("div",{className:"branch-widget-branch-list",children:V.map(E=>e.jsxs("div",{className:`branch-widget-branch-item remote ${m?"disabled":""}`,onClick:()=>O(E),onContextMenu:Q=>q(Q,E),title:E.lastMessage||E.name,children:[e.jsx("span",{className:"branch-widget-branch-name",children:E.name}),E.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:E.lastCommit})]},E.name))})]})]}),S&&e.jsx(it,{isOpen:S.isOpen,position:S.position,worldPosition:{x:0,z:0},actions:ie,onClose:()=>A(null)})]})});function Va(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function St(t,n){if(!t)return"";const o=Es.languages[n];return o?Es.highlight(t,o,n):Va(t)}function Ka(t){const n=[],o=t.split(`
|
|
9
9
|
`);let c=[],r=!1,i=[],f=[],l=!1;for(const u of o)u.startsWith("<<<<<<<")?(c.length>0&&(n.push({type:"unchanged",content:c.join(`
|
|
10
10
|
`)}),c=[]),r=!0,l=!1,i=[],f=[]):u.startsWith("=======")&&r?l=!0:u.startsWith(">>>>>>>")&&r?(n.push({type:"conflict",ours:i.join(`
|