@tencent-ai/agent-sdk 0.3.206-dev.0c715ff.202607102010 → 0.3.206

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/cli/dist/codebuddy-headless.js +178 -226
  2. package/cli/dist/web-ui/assets/{index-D0Z5-Zvd.js → index-BZjhFKbY.js} +2 -2
  3. package/cli/dist/web-ui/index.html +1 -1
  4. package/cli/dist/web-ui/sw.js +1 -1
  5. package/cli/package.json +2 -3
  6. package/cli/product.cloudhosted.json +2 -2
  7. package/cli/product.internal.json +2 -2
  8. package/cli/product.ioa.json +2 -2
  9. package/cli/product.json +2 -2
  10. package/cli/product.selfhosted.json +2 -2
  11. package/cli/vendor/shim/genie-safe-delete.cjs +781 -4
  12. package/cli/vendor/shim/safe-bin/safe-delete-bash-env.sh +1 -1
  13. package/cli/vendor/shim/safe-bin/safe-delete-common.sh +34 -95
  14. package/cli/vendor/shim/sitecustomize.py +22 -551
  15. package/package.json +2 -3
  16. package/cli/vendor/native-builds.json +0 -18
  17. package/cli/vendor/shim/broker-ipc-client.cjs +0 -158
  18. package/cli/vendor/shim/brokered-bin/codebuddy-toybox-dispatch +0 -381
  19. package/cli/vendor/shim/brokered-sandbox-bash-env.sh +0 -10
  20. package/cli/vendor/shim/native/binding.gyp +0 -13
  21. package/cli/vendor/shim/native/brokered_sandbox_native.c +0 -293
  22. package/cli/vendor/shim/native/darwin-arm64/brokered-sandbox-native.node +0 -0
  23. package/cli/vendor/shim/native/darwin-x64/brokered-sandbox-native.node +0 -0
  24. package/cli/vendor/shim/node-brokered-fs-shim.cjs +0 -932
  25. package/cli/vendor/shim/node-language-shim.cjs +0 -35
  26. package/cli/vendor/shim/node-safe-delete-shim.cjs +0 -810
  27. package/cli/vendor/shim/safe-delete-broker-delete.cjs +0 -166
  28. package/cli/vendor/shim/shell-runtime-bash-env.sh +0 -8
  29. package/cli/vendor/toybox-macos/LICENSE +0 -12
  30. package/cli/vendor/toybox-macos/toybox +0 -0
  31. package/cli/vendor/toybox-macos/toybox.sb +0 -19
  32. package/cli/vendor/zsh-macos/LICENSE +0 -37
  33. package/cli/vendor/zsh-macos/bin/zsh +0 -0
@@ -830,7 +830,7 @@ WARNING: This link could potentially be dangerous`)){const b=window.open();if(b)
830
830
  Example: /goal all tests pass`,"goal.status.tooLong":"Goal condition is limited to {max} characters (got {actual})","goal.status.hooksDisabled":"/goal cannot run while hooks are disabled (disableAllHooks or allowManagedHooksOnly is set).","goal.status.set":"Goal set: {condition}","goal.status.setReplaced":"Goal replaced: {prev} → {condition}","goal.status.cleared":"Goal cleared: {prev}","goal.status.noGoal":"No goal set","goal.status.active":"Goal active: {condition}","goal.progress.title":"Goal not yet met… continuing","goal.progress.expand":"click to expand","goal.progress.condition":"Goal","goal.progress.reason":"Reason","goal.recap.active":"Goal active","goal.recap.achieved":"Goal achieved","goal.recap.impossible":"Goal could not be achieved","goal.recap.empty.title":"No goal set yet","goal.recap.empty.hint":"Use /goal <condition> to set a session-scoped stop hook.","goal.recap.empty.example":"Example: /goal all tests pass","goal.recap.footer.setAnother":"/goal <condition>","goal.recap.footer.toSetAnother":" to set another · ","goal.recap.footer.escDismiss":"to dismiss","goal.recap.stats.turn":"turn","goal.recap.stats.turns":"turns","goal.recap.stats.token":"token","goal.recap.stats.tokens":"tokens"}};function c_(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>{const s=t[n];return s==null?r:String(s)}):e}function de(){const{mode:e,resolved:t,setLocale:r,toggle:n}=cl();function s(l,o){const c=l_[t][l]??l;return c_(c,o)}function a(l,o){const c=l_[t][l];if(c!==void 0)return c_(c,o)}return{t:s,tryT:a,locale:e,resolved:t,setLocale:r,toggleLocale:n}}const Or=Ke(e=>({info:null,loading:!1,fetch:async()=>{e({loading:!0});try{const t=await Ve("/api/v1/info",{headers:ve()});if(t.ok){const r=await t.json(),n=r.data??r;e({info:n,loading:!1})}else e({loading:!1})}catch{e({loading:!1})}}})),S0=4;let IR=0;function NR(){return`pane-${Date.now()}-${++IR}`}function k0(e){return{id:NR(),ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}function Ai(e){return e.type==="leaf"?1:Ai(e.children[0])+Ai(e.children[1])}function dl(e){return e.type==="leaf"?[e.paneId]:[...dl(e.children[0]),...dl(e.children[1])]}function Kd(e,t,r,n){return e.type==="leaf"?e.paneId===t?{type:"split",direction:r,children:[{type:"leaf",paneId:t},{type:"leaf",paneId:n}],ratio:.5}:e:{...e,children:[Kd(e.children[0],t,r,n),Kd(e.children[1],t,r,n)]}}function Yd(e,t){if(e.type==="leaf")return e.paneId===t?null:e;const r=Yd(e.children[0],t),n=Yd(e.children[1],t);return r===null?n:n===null?r:{...e,children:[r,n]}}function C0(e,t,r){if(t.length===0)return e.type==="split"?{...e,ratio:r}:e;if(e.type==="split"){const[n,...s]=t,a=[...e.children];return a[n]=C0(a[n],s,r),{...e,children:a}}return e}function d_(e){const t=ve({"Content-Type":"application/json"});fetch(`/api/v1/pty/${e}`,{method:"DELETE",headers:t}).catch(()=>{})}function A0(){const e=k0();return{panes:{[e.id]:e},layout:{type:"leaf",paneId:e.id},activePaneId:e.id}}const qc=A0(),De=Ke()(Gs((e,t)=>({mode:"chat",mainView:"chat",terminalTitle:null,panes:qc.panes,layout:qc.layout,activePaneId:qc.activePaneId,setMode:r=>{e({mode:r,mainView:r==="terminal"?"terminal":"chat"})},setMainView:r=>{e({mainView:r,mode:r==="terminal"?"terminal":"chat"})},setTerminalTitle:r=>e({terminalTitle:r}),splitPane:(r,n)=>{const s=t(),a=n??s.activePaneId;if(Ai(s.layout)>=S0)return;const l=k0(),o=Kd(s.layout,a,r,l.id),c={...s.panes,[l.id]:l};e({layout:o,panes:c,activePaneId:l.id})},closePane:r=>{const n=t();if(Ai(n.layout)<=1)return;const s=Yd(n.layout,r);if(!s)return;const a=n.panes[r];a!=null&&a.ptySessionId&&d_(a.ptySessionId);const l={...n.panes};delete l[r];const o=dl(s),c=o.includes(n.activePaneId)?n.activePaneId:o[0];e({layout:s,panes:l,activePaneId:c})},setActivePaneId:r=>e({activePaneId:r}),setRatio:(r,n)=>{const s=Math.max(.1,Math.min(.9,n)),a=C0(t().layout,r,s);e({layout:a})},setPaneSession:(r,n)=>{const s={...t().panes};s[r]&&(s[r]={...s[r],ptySessionId:n},e({panes:s}))},setPaneStatus:(r,n)=>{const s={...t().panes};s[r]&&(s[r]={...s[r],ptyStatus:n},e({panes:s}))},setPaneError:(r,n)=>{const s={...t().panes};s[r]&&(s[r]={...s[r],errorMessage:n},e({panes:s}))},setPaneTitle:(r,n)=>{const s={...t().panes};s[r]&&(s[r]={...s[r],title:n},e({panes:s}))},reset:()=>{const r=t().panes;for(const s of Object.values(r))s.ptySessionId&&d_(s.ptySessionId);const n=A0();e({panes:n.panes,layout:n.layout,activePaneId:n.activePaneId})}}),{namespace:"terminal",fields:["layout","panes","mainView"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{if(e.mainView){const r=window.location.hash.slice(2);!r||r===""?window.location.hash=`/${e.mainView}`:delete e.mainView}if(e.layout&&e.panes){const r=e.layout,n=e.panes,s=dl(r);if(s.every(a=>a in n)){const a=De.getState().panes,l={};for(const c of s){const d=a[c],u=n[c];l[c]={...u,ptySessionId:(d==null?void 0:d.ptySessionId)??u.ptySessionId??null,ptyStatus:"disconnected",errorMessage:null}}for(const[c,d]of Object.entries(n))if(!l[c]){const u=a[c];l[c]={...d,ptySessionId:(u==null?void 0:u.ptySessionId)??d.ptySessionId??null,ptyStatus:"disconnected",errorMessage:null}}const o={layout:r,panes:l,activePaneId:s[0]};e.mainView&&(o.mainView=e.mainView),t(o);return}}e.mainView&&t({mainView:e.mainView})}})),RR=e=>(t,r,n)=>{const s=n.subscribe;return n.subscribe=((l,o,c)=>{let d=l;if(o){const u=(c==null?void 0:c.equalityFn)||Object.is;let h=l(n.getState());d=p=>{const m=l(p);if(!u(h,m)){const v=h;o(h=m,v)}},c!=null&&c.fireImmediately&&o(h,h)}return s(d)}),e(t,r,n)},LR=RR;async function ds(e,t){var s;const r=await fetch("/api/v1/fs/list",{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({path:e,depth:t})});if(!r.ok)throw new Error(`List directory failed: HTTP ${r.status}`);const n=await r.json();return((s=n.data)==null?void 0:s.entries)??n.entries??[]}async function Qc(e){const t=await fetch(`/api/v1/files/download?path=${encodeURIComponent(e)}`,{headers:ve()});if(!t.ok)throw new Error(`Read file failed: HTTP ${t.status}`);const r=await t.text();if(r.length===0){const n=Number(t.headers.get("Content-Length"));if(Number.isFinite(n)&&n>0)throw new Error(`Read file failed: empty body but Content-Length=${n}`)}return r}async function u_(e,t){const r=await fetch(`/api/v1/files/upload?path=${encodeURIComponent(e)}`,{method:"POST",headers:{...ve(),"Content-Type":"application/octet-stream"},body:t});if(!r.ok)throw new Error(`Write file failed: HTTP ${r.status}`)}async function DR(e){const t=await fetch("/api/v1/fs/mkdir",{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Create directory failed: HTTP ${t.status}`)}async function MR(e){const t=await fetch("/api/v1/fs/remove",{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Remove failed: HTTP ${t.status}`)}async function $R(e){try{return await ds(e,1),"directory"}catch{return"file"}}async function h_(e,t){const r=await fetch("/api/v1/fs/move",{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({source:e,destination:t})});if(!r.ok)throw new Error(`Move failed: HTTP ${r.status}`)}function p_(e,t,r,n){let s=!1;const a=new AbortController;return fetch("/api/v1/fs/watch",{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({path:e,recursive:t}),signal:a.signal}).then(async l=>{if(s)return;if(!l.ok||!l.body){n==null||n();return}const o=l.body.getReader(),c=new TextDecoder;let d="";for(;!s;){const{done:u,value:h}=await o.read();if(u||s)break;d+=c.decode(h,{stream:!0});const p=d.split(`
831
831
 
832
832
  `);d=p.pop()||"";for(const m of p){if(s)break;const v=m.split(`
833
- `);let x="",f="";for(const b of v)b.startsWith("event: ")?x=b.slice(7):b.startsWith("data: ")&&(f=b.slice(6));if(x==="fs_event"&&f)try{const b=JSON.parse(f);r(b)}catch{}}}}).catch(()=>{s||n==null||n()}),{close(){s=!0,a.abort()}}}function _o(e){const r=De.getState().panes,n={...r};for(const s of e){const a=r[s];a!=null&&a.ptySessionId&&fetch(`/api/v1/pty/${a.ptySessionId}`,{method:"DELETE",headers:ve()}).catch(()=>{}),delete n[s]}De.setState({panes:n})}let OR=0;function Vc(){return`ide-term-${Date.now()}-${++OR}`}function xo(e){const t=De.getState();if(!t.panes[e]){const r={...t.panes,[e]:{id:e,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}};De.setState({panes:r})}}const yt=Ke()(Gs((e,t)=>({activePanel:"explorer",sidePanelWidth:260,sidePanelCollapsed:!1,bottomPanelHeight:250,bottomPanelCollapsed:!0,bottomPanelMaximized:!1,bottomTerminals:[],activeBottomTerminalId:null,scmViewMode:"list",activeMobilePanel:"explorer",setActivePanel:r=>{e(r===null?{activePanel:null,sidePanelCollapsed:!0}:{activePanel:r,sidePanelCollapsed:!1})},toggleActivePanel:r=>{const{activePanel:n,sidePanelCollapsed:s}=t();e(n===r&&!s?{sidePanelCollapsed:!0}:{activePanel:r,sidePanelCollapsed:!1})},setSidePanelWidth:r=>e({sidePanelWidth:r}),setSidePanelCollapsed:r=>e({sidePanelCollapsed:r}),setBottomPanelHeight:r=>e({bottomPanelHeight:r}),setBottomPanelCollapsed:r=>e({bottomPanelCollapsed:r}),toggleBottomPanel:()=>{const{bottomPanelCollapsed:r,bottomTerminals:n}=t();if(r)if(n.length===0){const s=Vc();xo(s),e({bottomPanelCollapsed:!1,bottomTerminals:[s],activeBottomTerminalId:s})}else e({bottomPanelCollapsed:!1});else e({bottomPanelCollapsed:!0})},createBottomTerminal:()=>{const r=Vc();return xo(r),e(n=>({bottomTerminals:[...n.bottomTerminals,r],activeBottomTerminalId:r,bottomPanelCollapsed:!1})),r},closeBottomTerminal:r=>{_o([r]),e(n=>{const s=n.bottomTerminals.filter(l=>l!==r),a=n.activeBottomTerminalId===r?s[s.length-1]??null:n.activeBottomTerminalId;return{bottomTerminals:s,activeBottomTerminalId:a,bottomPanelCollapsed:s.length===0?!0:n.bottomPanelCollapsed}})},closeOtherBottomTerminals:r=>{const{bottomTerminals:n}=t(),s=n.filter(a=>a!==r);_o(s),e({bottomTerminals:[r],activeBottomTerminalId:r})},closeBottomTerminalsToRight:r=>{const{bottomTerminals:n,activeBottomTerminalId:s}=t(),a=n.indexOf(r);if(a<0)return;const l=n.slice(a+1);_o(l);const o=n.slice(0,a+1),c=o.includes(s)?s:o[o.length-1]??null;e({bottomTerminals:o,activeBottomTerminalId:c})},closeAllBottomTerminals:()=>{const{bottomTerminals:r}=t();_o(r),e({bottomTerminals:[],activeBottomTerminalId:null,bottomPanelCollapsed:!0})},setActiveBottomTerminal:r=>e({activeBottomTerminalId:r}),toggleBottomPanelMaximize:()=>{const{bottomPanelMaximized:r,bottomPanelCollapsed:n,bottomTerminals:s}=t();if(n)if(s.length===0){const a=Vc();xo(a),e({bottomPanelCollapsed:!1,bottomPanelMaximized:!0,bottomTerminals:[a],activeBottomTerminalId:a})}else e({bottomPanelCollapsed:!1,bottomPanelMaximized:!0});else e({bottomPanelMaximized:!r})},setScmViewMode:r=>e({scmViewMode:r}),setActiveMobilePanel:r=>e({activeMobilePanel:r})}),{namespace:"ide-layout",fields:["sidePanelWidth","bottomPanelHeight","activePanel","sidePanelCollapsed","bottomPanelCollapsed","bottomPanelMaximized","bottomTerminals","activeBottomTerminalId","scmViewMode","activeMobilePanel"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{const r=e.bottomTerminals;if(r&&r.length>0)for(const s of r)xo(s);const n=e.activeBottomTerminalId;n&&r&&!r.includes(n)&&(e.activeBottomTerminalId=r[0]??null),t(e)}})),jR={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".md":"markdown",".mdx":"markdown",".css":"css",".scss":"scss",".less":"less",".html":"html",".htm":"html",".xml":"xml",".svg":"xml",".yaml":"yaml",".yml":"yaml",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".sh":"shell",".bash":"shell",".zsh":"shell",".sql":"sql",".graphql":"graphql",".gql":"graphql",".vue":"html",".lua":"lua",".r":"r",".R":"r",".dockerfile":"dockerfile",".toml":"ini",".ini":"ini",".cfg":"ini",".env":"ini",".gitignore":"ini"};function Kc(e){const t=e.substring(e.lastIndexOf("/")+1);if(t==="Dockerfile"||t.startsWith("Dockerfile."))return"dockerfile";if(t==="Makefile"||t==="GNUmakefile")return"makefile";const r=e.substring(e.lastIndexOf("."));return jR[r]||"plaintext"}const BR=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".zip",".gz",".tar",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".otf",".eot",".sqlite",".db"]);function E0(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return BR.has(t)}const PR=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif"]);function FR(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return PR.has(t)?"image":t===".svg"?"svg":t===".md"||t===".mdx"?"markdown":t===".pdf"?"pdf":E0(e)?"binary":"editor"}const zR=2*1024*1024,UR=10;function Yc(e,t,r){const n=e.filter(s=>s.path!==t);return[{path:t,name:r,timestamp:Date.now()},...n].slice(0,UR)}function HR(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function Zc(e){return HR(e).map(t=>({name:t.name,path:t.path,type:t.type,children:(t.type==="directory",void 0)}))}function Zd(e,t,r){return e.path===t?{...e,children:r,isLoading:!1}:e.children?{...e,children:e.children.map(n=>Zd(n,t,r))}:e}function sh(e,t){const r=[];if(e.children)for(const n of e.children)r.push(n.path),n.type==="directory"&&t.has(n.path)&&n.children&&r.push(...sh(n,t));return r}function Xd(e,t,r){return e.path===t?{...e,isLoading:r}:e.children?{...e,children:e.children.map(n=>Xd(n,t,r))}:e}function GR(e){const t=new Map,r=new Map;for(const n of e)r.set(n.name,(r.get(n.name)||0)+1);for(const n of e)if(r.get(n.name)>1){const s=n.path.split("/"),a=s.length>=2?s[s.length-2]:"";t.set(n.id,a?`${a}/`:"")}else t.set(n.id,"");return t}const mt=Ke()(Gs((e,t)=>({rootPath:null,tree:null,treeLoading:!1,treeError:!1,expandedPaths:new Set,selectedPath:null,selectedPaths:new Set,renamingPath:null,renamingIsNew:!1,tabs:[],activeTabId:null,tabsMeta:[],recentFiles:[],pendingReveal:null,setPendingReveal:r=>e({pendingReveal:r}),splitRatio:.22,setRootPath:async r=>{var n;e({rootPath:r,treeLoading:!0,tree:null,treeError:!1});try{const s=await ds(r),a=Zc(s),l={name:r.split("/").pop()||r,path:r,type:"directory",children:a},o=t().expandedPaths,c=o instanceof Set?o:new Set,d=new Set([r,...c]);e({tree:l,treeLoading:!1,expandedPaths:d});const u=[...d].filter(h=>h!==r);if(u.length>0){u.sort((h,p)=>h.split("/").length-p.split("/").length);for(const h of u)try{const p=await ds(h),m=Zc(p),v=t().tree;v&&e({tree:Zd(v,h,m)})}catch{const p=t().expandedPaths,m=new Set(p);m.delete(h),e({expandedPaths:m})}}}catch(s){console.error("[editor-store] setRootPath failed:",s);const a=(n=Or.getState().info)==null?void 0:n.cwd;a&&r!==a?t().setRootPath(a):e({treeLoading:!1,treeError:!0})}},loadDirectory:async r=>{const{tree:n}=t();if(n){e({tree:Xd(n,r,!0)});try{const s=await ds(r),a=Zc(s),l=Zd(t().tree,r,a);e({tree:l})}catch{const s=t().tree;s&&e({tree:Xd(s,r,!1)})}}},toggleExpand:r=>{const{expandedPaths:n}=t(),s=new Set(n);if(s.has(r))s.delete(r);else{s.add(r);const{tree:a}=t();if(a){const l=c=>{if(c.path===r)return c;if(c.children)for(const d of c.children){const u=l(d);if(u)return u}return null},o=l(a);o&&o.type==="directory"&&!o.children&&t().loadDirectory(r)}}e({expandedPaths:s})},selectPath:(r,n)=>{const{selectedPaths:s,selectedPath:a,tree:l,expandedPaths:o}=t();if(n!=null&&n.ctrl){const c=new Set(s);c.has(r)?(c.delete(r),e({selectedPaths:c,selectedPath:c.size>0?[...c][c.size-1]:null})):(c.add(r),e({selectedPaths:c,selectedPath:r}))}else if(n!=null&&n.shift&&a&&l){const c=sh(l,o),d=c.indexOf(a),u=c.indexOf(r);if(d>=0&&u>=0){const h=Math.min(d,u),p=Math.max(d,u),m=new Set(c.slice(h,p+1));e({selectedPaths:m,selectedPath:r})}}else e({selectedPath:r,selectedPaths:new Set([r])})},refreshTree:async()=>{const{rootPath:r}=t();r&&await t().setRootPath(r)},collapseAll:()=>{const{rootPath:r}=t(),n=new Set;r&&n.add(r),e({expandedPaths:n})},createNewFile:()=>{const{selectedPath:r,rootPath:n,tree:s,expandedPaths:a}=t();let l=n;if(r&&s){const c=u=>{if(u.path===r)return u;if(u.children)for(const h of u.children){const p=c(h);if(p)return p}return null},d=c(s);d&&(l=d.type==="directory"?d.path:d.path.substring(0,d.path.lastIndexOf("/")))}if(!l)return;a.has(l)||t().toggleExpand(l);const o=l+"/__new_file__";t().startCreateFile(o)},createNewFolder:()=>{const{selectedPath:r,rootPath:n,tree:s,expandedPaths:a}=t();let l=n;if(r&&s){const c=u=>{if(u.path===r)return u;if(u.children)for(const h of u.children){const p=c(h);if(p)return p}return null},d=c(s);d&&(l=d.type==="directory"?d.path:d.path.substring(0,d.path.lastIndexOf("/")))}if(!l)return;a.has(l)||t().toggleExpand(l);const o=l+"/__new_folder__";t().startCreateFolder(o)},startRename:r=>{e({renamingPath:r,renamingIsNew:!1,selectedPath:r})},startCreateFile:r=>{const n=r.substring(0,r.lastIndexOf("/")),{tree:s}=t();if(!s)return;const a={name:"",path:r,type:"file"},l=o=>o.path===n?{...o,children:[a,...o.children||[]]}:o.children?{...o,children:o.children.map(c=>l(c))}:o;e({tree:l(s),renamingPath:r,renamingIsNew:!0,selectedPath:r})},startCreateFolder:r=>{const n=r.substring(0,r.lastIndexOf("/")),{tree:s}=t();if(!s)return;const a={name:"",path:r,type:"directory"},l=o=>o.path===n?{...o,children:[a,...o.children||[]]}:o.children?{...o,children:o.children.map(c=>l(c))}:o;e({tree:l(s),renamingPath:r,renamingIsNew:!0,selectedPath:r})},confirmRename:async(r,n)=>{const{renamingIsNew:s}=t();if(!n.trim()){if(s){const o=r.substring(0,r.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(o)}else e({renamingPath:null,renamingIsNew:!1});return}const a=r.substring(0,r.lastIndexOf("/")),l=a+"/"+n.trim();if(s){try{const{tree:o}=t(),c=u=>{if(u.path===r)return u;if(u.children)for(const h of u.children){const p=c(h);if(p)return p}return null},d=o?c(o):null;(d==null?void 0:d.type)==="directory"?await DR(l):await u_(l,""),e({renamingPath:null,renamingIsNew:!1,selectedPath:l}),await t().loadDirectory(a),(d==null?void 0:d.type)!=="directory"&&await t().openFile(l,n.trim())}catch{e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(a)}return}if(l===r){e({renamingPath:null,renamingIsNew:!1});return}try{await h_(r,l),e(o=>({renamingPath:null,renamingIsNew:!1,selectedPath:l,tabs:o.tabs.map(c=>c.path===r?{...c,id:l,path:l,name:n.trim()}:c),activeTabId:o.activeTabId===r?l:o.activeTabId})),await t().loadDirectory(a)}catch{e({renamingPath:null,renamingIsNew:!1})}},cancelRename:()=>{const{renamingIsNew:r,renamingPath:n}=t();if(r&&n){const s=n.substring(0,n.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),t().loadDirectory(s)}else e({renamingPath:null,renamingIsNew:!1})},openFile:async(r,n,s)=>{yt.getState().bottomPanelMaximized&&yt.setState({bottomPanelMaximized:!1});const a=s?{path:r,...s}:null,{tabs:l}=t(),o=l.find(h=>h.path===r);if(o){e({activeTabId:o.id,selectedPath:r,pendingReveal:a});return}const c=n||r.substring(r.lastIndexOf("/")+1),d=Kc(r),u=FR(r);if(u==="image"||u==="pdf"||u==="binary"){const h={id:r,path:r,name:c,content:"",originalContent:"",language:d,isDirty:!1,isPinned:!1,viewMode:u};e(p=>({tabs:[...p.tabs,h],activeTabId:h.id,selectedPath:r,pendingReveal:a,recentFiles:Yc(p.recentFiles,r,c)}));return}try{const h=await Qc(r);if(h.length>zR)return;const p={id:r,path:r,name:c,content:h,originalContent:h,language:d,isDirty:!1,isPinned:!1,viewMode:u};e(m=>({tabs:[...m.tabs,p],activeTabId:p.id,selectedPath:r,pendingReveal:a,recentFiles:Yc(m.recentFiles,r,c)}))}catch{}},openDiffTab:(r,n)=>{const s=`diff://${r}@${n.staged?"staged":"unstaged"}`,{tabs:a}=t();if(a.find(d=>d.id===s)){e(d=>({tabs:d.tabs.map(u=>u.id===s?{...u,diffData:n}:u),activeTabId:s}));return}const o=r.substring(r.lastIndexOf("/")+1),c={id:s,path:r,name:`${o} (Diff)`,content:"",originalContent:"",language:Kc(r),isDirty:!1,isPinned:!1,viewMode:"diff",diffData:n};e(d=>({tabs:[...d.tabs,c],activeTabId:s}))},closeTab:r=>{e(n=>{const s=n.tabs.find(d=>d.id===r),a=n.tabs.findIndex(d=>d.id===r),l=n.tabs.filter(d=>d.id!==r);let o=n.activeTabId;n.activeTabId===r&&(o=l.length>0?l[Math.min(a,l.length-1)].id:null);const c=s?Yc(n.recentFiles,s.path,s.name):n.recentFiles;return{tabs:l,activeTabId:o,recentFiles:c}})},closeOtherTabs:r=>{e(n=>({tabs:n.tabs.filter(s=>s.id===r||s.isPinned),activeTabId:r}))},closeAllTabs:()=>{e(r=>{const n=r.tabs.filter(s=>s.isPinned);return{tabs:n,activeTabId:n.length>0?n[0].id:null}})},closeTabsToRight:r=>{e(n=>{const s=n.tabs.findIndex(o=>o.id===r);if(s<0)return n;const a=n.tabs.filter((o,c)=>c<=s||o.isPinned),l=a.some(o=>o.id===n.activeTabId);return{tabs:a,activeTabId:l?n.activeTabId:r}})},closeSavedTabs:()=>{e(r=>{const n=r.tabs.filter(a=>a.isPinned||a.isDirty),s=n.some(a=>a.id===r.activeTabId);return{tabs:n,activeTabId:s?r.activeTabId:n.length>0?n[0].id:null}})},setActiveTab:r=>{const n=t().tabs.find(s=>s.id===r);if(e({activeTabId:r,selectedPath:(n==null?void 0:n.path)||null}),n!=null&&n.needsLoad){const s=n.viewMode;s==="image"||s==="pdf"||s==="binary"?e(a=>({tabs:a.tabs.map(l=>l.id===r?{...l,needsLoad:!1}:l)})):Qc(n.path).then(a=>{e(l=>({tabs:l.tabs.map(o=>o.id===r?{...o,content:a,originalContent:a,needsLoad:!1}:o)}))}).catch(()=>{e(a=>{const l=a.tabs.filter(o=>o.id!==r);return{tabs:l,activeTabId:l.length>0?l[0].id:null}})})}},updateTabContent:(r,n)=>{e(s=>({tabs:s.tabs.map(a=>a.id===r?{...a,content:n,isDirty:n!==a.originalContent}:a)}))},saveTab:async r=>{const n=t().tabs.find(s=>s.id===r);if(!(!n||!n.isDirty))try{await u_(n.path,n.content),e(s=>({tabs:s.tabs.map(a=>a.id===r?{...a,originalContent:a.content,isDirty:!1}:a)}))}catch{}},deleteSelected:async()=>{const{selectedPaths:r,tabs:n}=t();if(r.size===0)return;const s=[...r],a=new Set(s.map(l=>l.substring(0,l.lastIndexOf("/"))));try{await Promise.all(s.map(o=>MR(o)));const l=n.filter(o=>!s.some(c=>o.path===c||o.path.startsWith(c+"/")));e(o=>({selectedPaths:new Set,selectedPath:null,tabs:l,activeTabId:l.length>0?l.find(c=>c.id===o.activeTabId)?o.activeTabId:l[0].id:null}));for(const o of a)await t().loadDirectory(o)}catch{for(const l of a)await t().loadDirectory(l)}},moveToDirectory:async(r,n)=>{if(r.length===0)return;const s=new Set(r.map(a=>a.substring(0,a.lastIndexOf("/"))));s.add(n);try{for(const a of r){const l=a.substring(a.lastIndexOf("/")+1),o=n+"/"+l;a!==o&&await h_(a,o)}e({selectedPaths:new Set,selectedPath:null});for(const a of s)await t().loadDirectory(a)}catch{for(const a of s)await t().loadDirectory(a)}},revealInTree:async r=>{const{rootPath:n}=t();if(!n||!r.startsWith(n))return;const a=r.slice(n.length).replace(/^\//,"").split("/").filter(Boolean),l=new Set(t().expandedPaths);let o=n;l.add(n);for(const c of a)if(o=o+"/"+c,o!==r){l.add(o);const{tree:d}=t();if(d){const u=p=>{if(p.path===o)return p;if(p.children)for(const m of p.children){const v=u(m);if(v)return v}return null},h=u(d);h&&h.type==="directory"&&!h.children&&await t().loadDirectory(o)}}e({expandedPaths:l,selectedPath:r})},reorderTabs:(r,n)=>{e(s=>{const a=[...s.tabs],[l]=a.splice(r,1);return a.splice(n,0,l),{tabs:a}})},pinTab:r=>{e(n=>{const s=n.tabs.findIndex(c=>c.id===r);if(s<0)return n;const a=[...n.tabs];a[s]={...a[s],isPinned:!0};const[l]=a.splice(s,1),o=a.reduce((c,d,u)=>d.isPinned?u:c,-1);return a.splice(o+1,0,l),{tabs:a}})},unpinTab:r=>{e(n=>({tabs:n.tabs.map(s=>s.id===r?{...s,isPinned:!1}:s)}))},setSplitRatio:r=>{const n=Math.max(.12,Math.min(.5,r));e({splitRatio:n})}}),{namespace:"editor",fields:["rootPath","splitRatio","expandedPaths","recentFiles","tabsMeta","activeTabId"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{const r={};if(e.rootPath&&typeof e.rootPath=="string"&&(r.rootPath=e.rootPath),e.splitRatio!==void 0&&(r.splitRatio=e.splitRatio),e.expandedPaths){const n=e.expandedPaths;r.expandedPaths=new Set(Array.isArray(n)?n:[])}if(e.recentFiles&&(r.recentFiles=e.recentFiles),e.tabsMeta){const n=e.tabsMeta;if(Array.isArray(n)&&n.length>0){const s=n.map(a=>({id:a.path,path:a.path,name:a.name,content:"",originalContent:"",language:Kc(a.path),isDirty:!1,isPinned:a.isPinned,viewMode:a.viewMode,needsLoad:!0}));r.tabs=s,r.tabsMeta=n}}if(e.activeTabId&&(r.activeTabId=e.activeTabId),Object.keys(r).length>0&&(t(r),r.activeTabId&&r.tabs)){const n=r.tabs.find(s=>s.id===r.activeTabId);if(n!=null&&n.needsLoad){const s=n.viewMode;s!=="image"&&s!=="pdf"&&s!=="binary"?Qc(n.path).then(a=>{t({tabs:mt.getState().tabs.map(l=>l.id===n.id?{...l,content:a,originalContent:a,needsLoad:!1}:l)})}).catch(()=>{const a=mt.getState().tabs.filter(l=>l.id!==n.id);t({tabs:a,activeTabId:a.length>0?a[0].id:null})}):t({tabs:mt.getState().tabs.map(a=>a.id===n.id?{...a,needsLoad:!1}:a)})}}}}));mt.subscribe((e,t)=>{if(e.tabs!==t.tabs){const r=e.tabs.map(s=>({path:s.path,name:s.name,isPinned:s.isPinned,viewMode:s.viewMode})),n=e.tabsMeta;JSON.stringify(r)!==JSON.stringify(n)&&mt.setState({tabsMeta:r})}});const Ei=Ke()(LR(()=>({cwd:null})));function ih(){var n;const e=mt.getState().rootPath,t=((n=Or.getState().info)==null?void 0:n.cwd)??null,r=e||t;r!==Ei.getState().cwd&&Ei.setState({cwd:r})}mt.subscribe((e,t)=>{e.rootPath!==t.rootPath&&ih()});Or.subscribe(ih);ih();function jl(){return Ei.getState().cwd||void 0}function WR(e){return Ei.subscribe(t=>t.cwd,e)}const qR="chat",m_=new Set(["chat","tasks","plugins","terminal","canvas","canvas-pane","remote-control","settings","docs","editor","changes","metrics","workers","logs","keybindings","stats","traces"]);function ah(){let t=window.location.hash.slice(1);t.startsWith("/")&&(t=t.slice(1));const r=t.split("?")[0]||"";if(m_.has(r))return r;const n=r.split("/")[0];return m_.has(n)?n:qR}function f_(e){const t=new URLSearchParams(window.location.search),r=window.location.hash.slice(1),n=r.indexOf("?");n!==-1&&new URLSearchParams(r.slice(n+1)).forEach((o,c)=>{t.has(c)||t.set(c,o)});const s=t.toString(),a=s?`#/${e}?${s}`:`#/${e}`;window.location.hash=a}function QR(e){const t=()=>{const r=ah();e(r)};return window.addEventListener("hashchange",t),()=>{window.removeEventListener("hashchange",t)}}function ul(){const t=window.location.hash.slice(1).replace(/^\//,"").split("?")[0],r=t.indexOf("/");return r>0?t.slice(r+1):void 0}function la(e,t){const n=new URLSearchParams(window.location.search).toString(),s=n?`#/${e}/${t}?${n}`:`#/${e}/${t}`;window.location.hash=s}function hl(){const e=window.location.hash.slice(1),t=e.indexOf("?");return t>=0?new URLSearchParams(e.slice(t+1)):new URLSearchParams}function oh(e,t,r){const n=new URLSearchParams(window.location.search);n.set("path",e),t!=null&&n.set("line",String(t)),r!=null&&n.set("col",String(r)),window.location.hash=`#/editor?${n.toString()}`}function VR({searchAddon:e,onClose:t,onFocusTerminal:r}){const{t:n}=de(),s=C.useRef(null),[a,l]=C.useState(""),[o,c]=C.useState(!1),[d,u]=C.useState(!1),[h,p]=C.useState(!1),[m,v]=C.useState(null);C.useEffect(()=>{var k,A;(k=s.current)==null||k.focus(),(A=s.current)==null||A.select()},[]),C.useEffect(()=>{if(!e)return;const k=e.onDidChangeResults(A=>{v(A)});return()=>k.dispose()},[e]);const x={caseSensitive:o,wholeWord:d,regex:h,decorations:{matchBackground:"#e8a63880",matchBorder:"#e8a638",matchOverviewRuler:"#e8a638cc",activeMatchBackground:"#515c6a",activeMatchBorder:"#74879f",activeMatchColorOverviewRuler:"#74879fcc"}},f=C.useCallback(()=>{!e||!a||e.findNext(a,x)},[e,a,o,d,h]),b=C.useCallback(()=>{!e||!a||e.findPrevious(a,x)},[e,a,o,d,h]);C.useEffect(()=>{e&&(a?e.findNext(a,x)===!1&&v({resultIndex:-1,resultCount:0}):(e.clearDecorations(),v(null)))},[e,a,o,d,h]);const g=C.useCallback(()=>{e==null||e.clearDecorations(),t(),r()},[e,t,r]),_=C.useCallback(k=>{k.key==="Escape"?(k.preventDefault(),g()):k.key==="Enter"||k.key==="ArrowDown"?(k.preventDefault(),k.shiftKey?b():f()):k.key==="ArrowUp"&&(k.preventDefault(),b())},[g,f,b]),y=a.length>0,S=y&&m!==null&&m.resultCount===0,w=y?m===null||m.resultCount===0?n("terminal.search.noResults"):`${m.resultIndex+1} of ${m.resultCount}`:n("terminal.search.noResults");return i.jsxs("div",{className:"terminal-search-bar",onKeyDown:_,onClick:k=>k.stopPropagation(),onMouseDown:k=>k.stopPropagation(),children:[i.jsxs("div",{className:"terminal-search-input-wrapper",children:[i.jsx("input",{ref:s,type:"text",className:"terminal-search-input",placeholder:n("terminal.search.placeholder"),value:a,onChange:k=>l(k.target.value),spellCheck:!1,autoComplete:"off"}),i.jsx("button",{className:`terminal-search-toggle ${o?"active":""}`,onClick:()=>c(!o),title:n("terminal.search.caseSensitive"),children:"Aa"}),i.jsx("button",{className:`terminal-search-toggle ${d?"active":""}`,onClick:()=>u(!d),title:n("terminal.search.wholeWord"),children:i.jsx("span",{className:"terminal-search-toggle-ab",children:"ab"})}),i.jsx("button",{className:`terminal-search-toggle ${h?"active":""}`,onClick:()=>p(!h),title:n("terminal.search.regex"),children:".*"})]}),i.jsx("span",{className:`terminal-search-results ${S?"no-results":""}`,children:w}),i.jsx("button",{className:"terminal-search-btn",onClick:b,title:n("terminal.search.previous"),disabled:!a,children:i.jsx(GC,{size:16})}),i.jsx("button",{className:"terminal-search-btn",onClick:f,title:n("terminal.search.next"),disabled:!a,children:i.jsx(rt,{size:16})}),i.jsx("button",{className:"terminal-search-btn",onClick:g,title:n("terminal.search.close"),children:i.jsx(at,{size:16})})]})}const g_={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},b_={background:"#191a1b",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#191a1b",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"},KR=2e3;function Bl(){return ve({"Content-Type":"application/json"})}function YR(e){const t=window.location,r=t.protocol==="https:"?"wss:":"ws:",n=Il(),s=n?`?token=${encodeURIComponent(n)}`:"";return`${r}//${t.host}/api/v1/pty/${e}/ws${s}`}async function y_(e){try{return(await fetch(`/api/v1/pty/${e}`,{headers:Bl()})).ok}catch{return!1}}async function __(e,t,r){const n={cols:e,rows:t};r&&(n.cwd=r);const s=await fetch("/api/v1/pty",{method:"POST",headers:Bl(),body:JSON.stringify(n)});if(!s.ok){const o=await s.json().catch(()=>null),c=typeof(o==null?void 0:o.error)=="string"?o.error:typeof(o==null?void 0:o.message)=="string"?o.message:`HTTP ${s.status}`;throw new Error(c)}const a=await s.json(),l=a.data??a;return{sessionId:l.sessionId,cwd:typeof l.cwd=="string"?l.cwd:"",shell:typeof l.shell=="string"?l.shell:void 0}}async function x_(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:Bl()});if(!t.ok)return null;const r=await t.json(),n=r.data??r;return{cwd:typeof(n==null?void 0:n.cwd)=="string"?n.cwd:""}}catch{return null}}async function ZR(){try{const e=await fetch("/api/v1/pty",{headers:Bl()});if(!e.ok)return[];const t=await e.json();return(t.data??t).sessions||[]}catch{return[]}}function XR(e){const t=De.getState().panes,r=new Set;for(const[n,s]of Object.entries(t))n!==e&&s.ptySessionId&&r.add(s.ptySessionId);return r}function Pl({paneId:e,initialCwd:t,onPtyCreated:r}){const{t:n}=de(),{resolved:s}=Jt(),a=De(B=>B.panes[e]),l=De(B=>B.activePaneId),o=De(B=>B.layout),c=De(B=>B.mainView),d=De(B=>B.setActivePaneId),u=De(B=>B.closePane),h=De(B=>B.setPaneSession),p=De(B=>B.setPaneStatus),m=De(B=>B.setPaneError),v=De(B=>B.setPaneTitle),x=De(B=>B.setTerminalTitle),f=l===e,b=Ai(o),[g,_]=C.useState(!1),y=C.useRef(null),S=C.useRef(null),w=C.useRef(null),k=C.useRef(null),A=C.useRef(null),N=C.useRef(null),j=C.useRef(null),$=C.useRef(!0),L=C.useRef(!1),E=C.useRef(!1),M=C.useRef(null),O=C.useRef(null),z=C.useRef(!1),U=C.useRef(!1),Q=C.useRef(t);Q.current=t;const I=C.useRef(r);I.current=r;const T=C.useCallback(()=>{const B=j.current;B&&(B.close(),j.current=null)},[]),D=C.useCallback((B,F)=>{T(),p(e,"connecting"),O.current=F;const Z=new WebSocket(YR(F));j.current=Z;let J=null,te=null;const ne=()=>{if(!$.current)return;const ye=w.current;if(U.current=!0,ye)try{ye.fit()}catch{}B.refresh(0,B.rows-1),z.current||B.scrollToBottom(),requestAnimationFrame(()=>{$.current&&(z.current||B.scrollToBottom(),U.current=!1)})},re=()=>{te&&clearTimeout(te),te=setTimeout(()=>{te=null,ne()},0)},me=(ye,be)=>{var $e;if(!z.current){B.write(ye,be);return}const le=($e=y.current)==null?void 0:$e.querySelector(".xterm-viewport");if(!le){B.write(ye,be);return}const _e=le.scrollTop;U.current=!0;const Te=()=>{le.scrollTop=_e};le.addEventListener("scroll",Te),B.write(ye,()=>{le.scrollTop=_e,requestAnimationFrame(()=>{le.scrollTop=_e,le.removeEventListener("scroll",Te),U.current=!1}),be==null||be()})};Z.onopen=()=>{$.current&&(p(e,"connected"),m(e,null),requestAnimationFrame(()=>{if(!$.current)return;const ye=w.current;if(ye)try{const be=ye.proposeDimensions();be&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"resize",cols:be.cols,rows:be.rows}))}catch{}}),B.focus(),J=setInterval(()=>{Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"ping"}))},25e3))},Z.onmessage=ye=>{if($.current)try{const be=JSON.parse(ye.data);switch(be.type){case"output":be.data&&me(be.data,re);break;case"exit":h(e,null),p(e,"disconnected"),E.current=!1,O.current=null,B.write(`\r
833
+ `);let x="",f="";for(const b of v)b.startsWith("event: ")?x=b.slice(7):b.startsWith("data: ")&&(f=b.slice(6));if(x==="fs_event"&&f)try{const b=JSON.parse(f);r(b)}catch{}}}}).catch(()=>{s||n==null||n()}),{close(){s=!0,a.abort()}}}function _o(e){const r=De.getState().panes,n={...r};for(const s of e){const a=r[s];a!=null&&a.ptySessionId&&fetch(`/api/v1/pty/${a.ptySessionId}`,{method:"DELETE",headers:ve()}).catch(()=>{}),delete n[s]}De.setState({panes:n})}let OR=0;function Vc(){return`ide-term-${Date.now()}-${++OR}`}function xo(e){const t=De.getState();if(!t.panes[e]){const r={...t.panes,[e]:{id:e,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}};De.setState({panes:r})}}const yt=Ke()(Gs((e,t)=>({activePanel:"explorer",sidePanelWidth:260,sidePanelCollapsed:!1,bottomPanelHeight:250,bottomPanelCollapsed:!0,bottomPanelMaximized:!1,bottomTerminals:[],activeBottomTerminalId:null,scmViewMode:"list",activeMobilePanel:"explorer",setActivePanel:r=>{e(r===null?{activePanel:null,sidePanelCollapsed:!0}:{activePanel:r,sidePanelCollapsed:!1})},toggleActivePanel:r=>{const{activePanel:n,sidePanelCollapsed:s}=t();e(n===r&&!s?{sidePanelCollapsed:!0}:{activePanel:r,sidePanelCollapsed:!1})},setSidePanelWidth:r=>e({sidePanelWidth:r}),setSidePanelCollapsed:r=>e({sidePanelCollapsed:r}),setBottomPanelHeight:r=>e({bottomPanelHeight:r}),setBottomPanelCollapsed:r=>e({bottomPanelCollapsed:r}),toggleBottomPanel:()=>{const{bottomPanelCollapsed:r,bottomTerminals:n}=t();if(r)if(n.length===0){const s=Vc();xo(s),e({bottomPanelCollapsed:!1,bottomTerminals:[s],activeBottomTerminalId:s})}else e({bottomPanelCollapsed:!1});else e({bottomPanelCollapsed:!0})},createBottomTerminal:()=>{const r=Vc();return xo(r),e(n=>({bottomTerminals:[...n.bottomTerminals,r],activeBottomTerminalId:r,bottomPanelCollapsed:!1})),r},closeBottomTerminal:r=>{_o([r]),e(n=>{const s=n.bottomTerminals.filter(l=>l!==r),a=n.activeBottomTerminalId===r?s[s.length-1]??null:n.activeBottomTerminalId;return{bottomTerminals:s,activeBottomTerminalId:a,bottomPanelCollapsed:s.length===0?!0:n.bottomPanelCollapsed}})},closeOtherBottomTerminals:r=>{const{bottomTerminals:n}=t(),s=n.filter(a=>a!==r);_o(s),e({bottomTerminals:[r],activeBottomTerminalId:r})},closeBottomTerminalsToRight:r=>{const{bottomTerminals:n,activeBottomTerminalId:s}=t(),a=n.indexOf(r);if(a<0)return;const l=n.slice(a+1);_o(l);const o=n.slice(0,a+1),c=o.includes(s)?s:o[o.length-1]??null;e({bottomTerminals:o,activeBottomTerminalId:c})},closeAllBottomTerminals:()=>{const{bottomTerminals:r}=t();_o(r),e({bottomTerminals:[],activeBottomTerminalId:null,bottomPanelCollapsed:!0})},setActiveBottomTerminal:r=>e({activeBottomTerminalId:r}),toggleBottomPanelMaximize:()=>{const{bottomPanelMaximized:r,bottomPanelCollapsed:n,bottomTerminals:s}=t();if(n)if(s.length===0){const a=Vc();xo(a),e({bottomPanelCollapsed:!1,bottomPanelMaximized:!0,bottomTerminals:[a],activeBottomTerminalId:a})}else e({bottomPanelCollapsed:!1,bottomPanelMaximized:!0});else e({bottomPanelMaximized:!r})},setScmViewMode:r=>e({scmViewMode:r}),setActiveMobilePanel:r=>e({activeMobilePanel:r})}),{namespace:"ide-layout",fields:["sidePanelWidth","bottomPanelHeight","activePanel","sidePanelCollapsed","bottomPanelCollapsed","bottomPanelMaximized","bottomTerminals","activeBottomTerminalId","scmViewMode","activeMobilePanel"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{const r=e.bottomTerminals;if(r&&r.length>0)for(const s of r)xo(s);const n=e.activeBottomTerminalId;n&&r&&!r.includes(n)&&(e.activeBottomTerminalId=r[0]??null),t(e)}})),jR={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".md":"markdown",".mdx":"markdown",".css":"css",".scss":"scss",".less":"less",".html":"html",".htm":"html",".xml":"xml",".svg":"xml",".yaml":"yaml",".yml":"yaml",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".sh":"shell",".bash":"shell",".zsh":"shell",".sql":"sql",".graphql":"graphql",".gql":"graphql",".vue":"html",".lua":"lua",".r":"r",".R":"r",".dockerfile":"dockerfile",".toml":"ini",".ini":"ini",".cfg":"ini",".env":"ini",".gitignore":"ini"};function Kc(e){const t=e.substring(e.lastIndexOf("/")+1);if(t==="Dockerfile"||t.startsWith("Dockerfile."))return"dockerfile";if(t==="Makefile"||t==="GNUmakefile")return"makefile";const r=e.substring(e.lastIndexOf("."));return jR[r]||"plaintext"}const BR=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".zip",".gz",".tar",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".otf",".eot",".sqlite",".db"]);function E0(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return BR.has(t)}const PR=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif"]);function FR(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return PR.has(t)?"image":t===".svg"?"svg":t===".md"||t===".mdx"?"editor":t===".pdf"?"pdf":E0(e)?"binary":"editor"}const zR=2*1024*1024,UR=10;function Yc(e,t,r){const n=e.filter(s=>s.path!==t);return[{path:t,name:r,timestamp:Date.now()},...n].slice(0,UR)}function HR(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function Zc(e){return HR(e).map(t=>({name:t.name,path:t.path,type:t.type,children:(t.type==="directory",void 0)}))}function Zd(e,t,r){return e.path===t?{...e,children:r,isLoading:!1}:e.children?{...e,children:e.children.map(n=>Zd(n,t,r))}:e}function sh(e,t){const r=[];if(e.children)for(const n of e.children)r.push(n.path),n.type==="directory"&&t.has(n.path)&&n.children&&r.push(...sh(n,t));return r}function Xd(e,t,r){return e.path===t?{...e,isLoading:r}:e.children?{...e,children:e.children.map(n=>Xd(n,t,r))}:e}function GR(e){const t=new Map,r=new Map;for(const n of e)r.set(n.name,(r.get(n.name)||0)+1);for(const n of e)if(r.get(n.name)>1){const s=n.path.split("/"),a=s.length>=2?s[s.length-2]:"";t.set(n.id,a?`${a}/`:"")}else t.set(n.id,"");return t}const mt=Ke()(Gs((e,t)=>({rootPath:null,tree:null,treeLoading:!1,treeError:!1,expandedPaths:new Set,selectedPath:null,selectedPaths:new Set,renamingPath:null,renamingIsNew:!1,tabs:[],activeTabId:null,tabsMeta:[],recentFiles:[],pendingReveal:null,setPendingReveal:r=>e({pendingReveal:r}),splitRatio:.22,setRootPath:async r=>{var n;e({rootPath:r,treeLoading:!0,tree:null,treeError:!1});try{const s=await ds(r),a=Zc(s),l={name:r.split("/").pop()||r,path:r,type:"directory",children:a},o=t().expandedPaths,c=o instanceof Set?o:new Set,d=new Set([r,...c]);e({tree:l,treeLoading:!1,expandedPaths:d});const u=[...d].filter(h=>h!==r);if(u.length>0){u.sort((h,p)=>h.split("/").length-p.split("/").length);for(const h of u)try{const p=await ds(h),m=Zc(p),v=t().tree;v&&e({tree:Zd(v,h,m)})}catch{const p=t().expandedPaths,m=new Set(p);m.delete(h),e({expandedPaths:m})}}}catch(s){console.error("[editor-store] setRootPath failed:",s);const a=(n=Or.getState().info)==null?void 0:n.cwd;a&&r!==a?t().setRootPath(a):e({treeLoading:!1,treeError:!0})}},loadDirectory:async r=>{const{tree:n}=t();if(n){e({tree:Xd(n,r,!0)});try{const s=await ds(r),a=Zc(s),l=Zd(t().tree,r,a);e({tree:l})}catch{const s=t().tree;s&&e({tree:Xd(s,r,!1)})}}},toggleExpand:r=>{const{expandedPaths:n}=t(),s=new Set(n);if(s.has(r))s.delete(r);else{s.add(r);const{tree:a}=t();if(a){const l=c=>{if(c.path===r)return c;if(c.children)for(const d of c.children){const u=l(d);if(u)return u}return null},o=l(a);o&&o.type==="directory"&&!o.children&&t().loadDirectory(r)}}e({expandedPaths:s})},selectPath:(r,n)=>{const{selectedPaths:s,selectedPath:a,tree:l,expandedPaths:o}=t();if(n!=null&&n.ctrl){const c=new Set(s);c.has(r)?(c.delete(r),e({selectedPaths:c,selectedPath:c.size>0?[...c][c.size-1]:null})):(c.add(r),e({selectedPaths:c,selectedPath:r}))}else if(n!=null&&n.shift&&a&&l){const c=sh(l,o),d=c.indexOf(a),u=c.indexOf(r);if(d>=0&&u>=0){const h=Math.min(d,u),p=Math.max(d,u),m=new Set(c.slice(h,p+1));e({selectedPaths:m,selectedPath:r})}}else e({selectedPath:r,selectedPaths:new Set([r])})},refreshTree:async()=>{const{rootPath:r}=t();r&&await t().setRootPath(r)},collapseAll:()=>{const{rootPath:r}=t(),n=new Set;r&&n.add(r),e({expandedPaths:n})},createNewFile:()=>{const{selectedPath:r,rootPath:n,tree:s,expandedPaths:a}=t();let l=n;if(r&&s){const c=u=>{if(u.path===r)return u;if(u.children)for(const h of u.children){const p=c(h);if(p)return p}return null},d=c(s);d&&(l=d.type==="directory"?d.path:d.path.substring(0,d.path.lastIndexOf("/")))}if(!l)return;a.has(l)||t().toggleExpand(l);const o=l+"/__new_file__";t().startCreateFile(o)},createNewFolder:()=>{const{selectedPath:r,rootPath:n,tree:s,expandedPaths:a}=t();let l=n;if(r&&s){const c=u=>{if(u.path===r)return u;if(u.children)for(const h of u.children){const p=c(h);if(p)return p}return null},d=c(s);d&&(l=d.type==="directory"?d.path:d.path.substring(0,d.path.lastIndexOf("/")))}if(!l)return;a.has(l)||t().toggleExpand(l);const o=l+"/__new_folder__";t().startCreateFolder(o)},startRename:r=>{e({renamingPath:r,renamingIsNew:!1,selectedPath:r})},startCreateFile:r=>{const n=r.substring(0,r.lastIndexOf("/")),{tree:s}=t();if(!s)return;const a={name:"",path:r,type:"file"},l=o=>o.path===n?{...o,children:[a,...o.children||[]]}:o.children?{...o,children:o.children.map(c=>l(c))}:o;e({tree:l(s),renamingPath:r,renamingIsNew:!0,selectedPath:r})},startCreateFolder:r=>{const n=r.substring(0,r.lastIndexOf("/")),{tree:s}=t();if(!s)return;const a={name:"",path:r,type:"directory"},l=o=>o.path===n?{...o,children:[a,...o.children||[]]}:o.children?{...o,children:o.children.map(c=>l(c))}:o;e({tree:l(s),renamingPath:r,renamingIsNew:!0,selectedPath:r})},confirmRename:async(r,n)=>{const{renamingIsNew:s}=t();if(!n.trim()){if(s){const o=r.substring(0,r.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(o)}else e({renamingPath:null,renamingIsNew:!1});return}const a=r.substring(0,r.lastIndexOf("/")),l=a+"/"+n.trim();if(s){try{const{tree:o}=t(),c=u=>{if(u.path===r)return u;if(u.children)for(const h of u.children){const p=c(h);if(p)return p}return null},d=o?c(o):null;(d==null?void 0:d.type)==="directory"?await DR(l):await u_(l,""),e({renamingPath:null,renamingIsNew:!1,selectedPath:l}),await t().loadDirectory(a),(d==null?void 0:d.type)!=="directory"&&await t().openFile(l,n.trim())}catch{e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(a)}return}if(l===r){e({renamingPath:null,renamingIsNew:!1});return}try{await h_(r,l),e(o=>({renamingPath:null,renamingIsNew:!1,selectedPath:l,tabs:o.tabs.map(c=>c.path===r?{...c,id:l,path:l,name:n.trim()}:c),activeTabId:o.activeTabId===r?l:o.activeTabId})),await t().loadDirectory(a)}catch{e({renamingPath:null,renamingIsNew:!1})}},cancelRename:()=>{const{renamingIsNew:r,renamingPath:n}=t();if(r&&n){const s=n.substring(0,n.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),t().loadDirectory(s)}else e({renamingPath:null,renamingIsNew:!1})},openFile:async(r,n,s)=>{yt.getState().bottomPanelMaximized&&yt.setState({bottomPanelMaximized:!1});const a=s?{path:r,...s}:null,{tabs:l}=t(),o=l.find(h=>h.path===r);if(o){e({activeTabId:o.id,selectedPath:r,pendingReveal:a});return}const c=n||r.substring(r.lastIndexOf("/")+1),d=Kc(r),u=FR(r);if(u==="image"||u==="pdf"||u==="binary"){const h={id:r,path:r,name:c,content:"",originalContent:"",language:d,isDirty:!1,isPinned:!1,viewMode:u};e(p=>({tabs:[...p.tabs,h],activeTabId:h.id,selectedPath:r,pendingReveal:a,recentFiles:Yc(p.recentFiles,r,c)}));return}try{const h=await Qc(r);if(h.length>zR)return;const p={id:r,path:r,name:c,content:h,originalContent:h,language:d,isDirty:!1,isPinned:!1,viewMode:u};e(m=>({tabs:[...m.tabs,p],activeTabId:p.id,selectedPath:r,pendingReveal:a,recentFiles:Yc(m.recentFiles,r,c)}))}catch{}},openDiffTab:(r,n)=>{const s=`diff://${r}@${n.staged?"staged":"unstaged"}`,{tabs:a}=t();if(a.find(d=>d.id===s)){e(d=>({tabs:d.tabs.map(u=>u.id===s?{...u,diffData:n}:u),activeTabId:s}));return}const o=r.substring(r.lastIndexOf("/")+1),c={id:s,path:r,name:`${o} (Diff)`,content:"",originalContent:"",language:Kc(r),isDirty:!1,isPinned:!1,viewMode:"diff",diffData:n};e(d=>({tabs:[...d.tabs,c],activeTabId:s}))},closeTab:r=>{e(n=>{const s=n.tabs.find(d=>d.id===r),a=n.tabs.findIndex(d=>d.id===r),l=n.tabs.filter(d=>d.id!==r);let o=n.activeTabId;n.activeTabId===r&&(o=l.length>0?l[Math.min(a,l.length-1)].id:null);const c=s?Yc(n.recentFiles,s.path,s.name):n.recentFiles;return{tabs:l,activeTabId:o,recentFiles:c}})},closeOtherTabs:r=>{e(n=>({tabs:n.tabs.filter(s=>s.id===r||s.isPinned),activeTabId:r}))},closeAllTabs:()=>{e(r=>{const n=r.tabs.filter(s=>s.isPinned);return{tabs:n,activeTabId:n.length>0?n[0].id:null}})},closeTabsToRight:r=>{e(n=>{const s=n.tabs.findIndex(o=>o.id===r);if(s<0)return n;const a=n.tabs.filter((o,c)=>c<=s||o.isPinned),l=a.some(o=>o.id===n.activeTabId);return{tabs:a,activeTabId:l?n.activeTabId:r}})},closeSavedTabs:()=>{e(r=>{const n=r.tabs.filter(a=>a.isPinned||a.isDirty),s=n.some(a=>a.id===r.activeTabId);return{tabs:n,activeTabId:s?r.activeTabId:n.length>0?n[0].id:null}})},setActiveTab:r=>{const n=t().tabs.find(s=>s.id===r);if(e({activeTabId:r,selectedPath:(n==null?void 0:n.path)||null}),n!=null&&n.needsLoad){const s=n.viewMode;s==="image"||s==="pdf"||s==="binary"?e(a=>({tabs:a.tabs.map(l=>l.id===r?{...l,needsLoad:!1}:l)})):Qc(n.path).then(a=>{e(l=>({tabs:l.tabs.map(o=>o.id===r?{...o,content:a,originalContent:a,needsLoad:!1}:o)}))}).catch(()=>{e(a=>{const l=a.tabs.filter(o=>o.id!==r);return{tabs:l,activeTabId:l.length>0?l[0].id:null}})})}},updateTabContent:(r,n)=>{e(s=>({tabs:s.tabs.map(a=>a.id===r?{...a,content:n,isDirty:n!==a.originalContent}:a)}))},saveTab:async r=>{const n=t().tabs.find(s=>s.id===r);if(!(!n||!n.isDirty))try{await u_(n.path,n.content),e(s=>({tabs:s.tabs.map(a=>a.id===r?{...a,originalContent:a.content,isDirty:!1}:a)}))}catch{}},deleteSelected:async()=>{const{selectedPaths:r,tabs:n}=t();if(r.size===0)return;const s=[...r],a=new Set(s.map(l=>l.substring(0,l.lastIndexOf("/"))));try{await Promise.all(s.map(o=>MR(o)));const l=n.filter(o=>!s.some(c=>o.path===c||o.path.startsWith(c+"/")));e(o=>({selectedPaths:new Set,selectedPath:null,tabs:l,activeTabId:l.length>0?l.find(c=>c.id===o.activeTabId)?o.activeTabId:l[0].id:null}));for(const o of a)await t().loadDirectory(o)}catch{for(const l of a)await t().loadDirectory(l)}},moveToDirectory:async(r,n)=>{if(r.length===0)return;const s=new Set(r.map(a=>a.substring(0,a.lastIndexOf("/"))));s.add(n);try{for(const a of r){const l=a.substring(a.lastIndexOf("/")+1),o=n+"/"+l;a!==o&&await h_(a,o)}e({selectedPaths:new Set,selectedPath:null});for(const a of s)await t().loadDirectory(a)}catch{for(const a of s)await t().loadDirectory(a)}},revealInTree:async r=>{const{rootPath:n}=t();if(!n||!r.startsWith(n))return;const a=r.slice(n.length).replace(/^\//,"").split("/").filter(Boolean),l=new Set(t().expandedPaths);let o=n;l.add(n);for(const c of a)if(o=o+"/"+c,o!==r){l.add(o);const{tree:d}=t();if(d){const u=p=>{if(p.path===o)return p;if(p.children)for(const m of p.children){const v=u(m);if(v)return v}return null},h=u(d);h&&h.type==="directory"&&!h.children&&await t().loadDirectory(o)}}e({expandedPaths:l,selectedPath:r})},reorderTabs:(r,n)=>{e(s=>{const a=[...s.tabs],[l]=a.splice(r,1);return a.splice(n,0,l),{tabs:a}})},pinTab:r=>{e(n=>{const s=n.tabs.findIndex(c=>c.id===r);if(s<0)return n;const a=[...n.tabs];a[s]={...a[s],isPinned:!0};const[l]=a.splice(s,1),o=a.reduce((c,d,u)=>d.isPinned?u:c,-1);return a.splice(o+1,0,l),{tabs:a}})},unpinTab:r=>{e(n=>({tabs:n.tabs.map(s=>s.id===r?{...s,isPinned:!1}:s)}))},setSplitRatio:r=>{const n=Math.max(.12,Math.min(.5,r));e({splitRatio:n})}}),{namespace:"editor",fields:["rootPath","splitRatio","expandedPaths","recentFiles","tabsMeta","activeTabId"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{const r={};if(e.rootPath&&typeof e.rootPath=="string"&&(r.rootPath=e.rootPath),e.splitRatio!==void 0&&(r.splitRatio=e.splitRatio),e.expandedPaths){const n=e.expandedPaths;r.expandedPaths=new Set(Array.isArray(n)?n:[])}if(e.recentFiles&&(r.recentFiles=e.recentFiles),e.tabsMeta){const n=e.tabsMeta;if(Array.isArray(n)&&n.length>0){const s=n.map(a=>({id:a.path,path:a.path,name:a.name,content:"",originalContent:"",language:Kc(a.path),isDirty:!1,isPinned:a.isPinned,viewMode:a.viewMode,needsLoad:!0}));r.tabs=s,r.tabsMeta=n}}if(e.activeTabId&&(r.activeTabId=e.activeTabId),Object.keys(r).length>0&&(t(r),r.activeTabId&&r.tabs)){const n=r.tabs.find(s=>s.id===r.activeTabId);if(n!=null&&n.needsLoad){const s=n.viewMode;s!=="image"&&s!=="pdf"&&s!=="binary"?Qc(n.path).then(a=>{t({tabs:mt.getState().tabs.map(l=>l.id===n.id?{...l,content:a,originalContent:a,needsLoad:!1}:l)})}).catch(()=>{const a=mt.getState().tabs.filter(l=>l.id!==n.id);t({tabs:a,activeTabId:a.length>0?a[0].id:null})}):t({tabs:mt.getState().tabs.map(a=>a.id===n.id?{...a,needsLoad:!1}:a)})}}}}));mt.subscribe((e,t)=>{if(e.tabs!==t.tabs){const r=e.tabs.map(s=>({path:s.path,name:s.name,isPinned:s.isPinned,viewMode:s.viewMode})),n=e.tabsMeta;JSON.stringify(r)!==JSON.stringify(n)&&mt.setState({tabsMeta:r})}});const Ei=Ke()(LR(()=>({cwd:null})));function ih(){var n;const e=mt.getState().rootPath,t=((n=Or.getState().info)==null?void 0:n.cwd)??null,r=e||t;r!==Ei.getState().cwd&&Ei.setState({cwd:r})}mt.subscribe((e,t)=>{e.rootPath!==t.rootPath&&ih()});Or.subscribe(ih);ih();function jl(){return Ei.getState().cwd||void 0}function WR(e){return Ei.subscribe(t=>t.cwd,e)}const qR="chat",m_=new Set(["chat","tasks","plugins","terminal","canvas","canvas-pane","remote-control","settings","docs","editor","changes","metrics","workers","logs","keybindings","stats","traces"]);function ah(){let t=window.location.hash.slice(1);t.startsWith("/")&&(t=t.slice(1));const r=t.split("?")[0]||"";if(m_.has(r))return r;const n=r.split("/")[0];return m_.has(n)?n:qR}function f_(e){const t=new URLSearchParams(window.location.search),r=window.location.hash.slice(1),n=r.indexOf("?");n!==-1&&new URLSearchParams(r.slice(n+1)).forEach((o,c)=>{t.has(c)||t.set(c,o)});const s=t.toString(),a=s?`#/${e}?${s}`:`#/${e}`;window.location.hash=a}function QR(e){const t=()=>{const r=ah();e(r)};return window.addEventListener("hashchange",t),()=>{window.removeEventListener("hashchange",t)}}function ul(){const t=window.location.hash.slice(1).replace(/^\//,"").split("?")[0],r=t.indexOf("/");return r>0?t.slice(r+1):void 0}function la(e,t){const n=new URLSearchParams(window.location.search).toString(),s=n?`#/${e}/${t}?${n}`:`#/${e}/${t}`;window.location.hash=s}function hl(){const e=window.location.hash.slice(1),t=e.indexOf("?");return t>=0?new URLSearchParams(e.slice(t+1)):new URLSearchParams}function oh(e,t,r){const n=new URLSearchParams(window.location.search);n.set("path",e),t!=null&&n.set("line",String(t)),r!=null&&n.set("col",String(r)),window.location.hash=`#/editor?${n.toString()}`}function VR({searchAddon:e,onClose:t,onFocusTerminal:r}){const{t:n}=de(),s=C.useRef(null),[a,l]=C.useState(""),[o,c]=C.useState(!1),[d,u]=C.useState(!1),[h,p]=C.useState(!1),[m,v]=C.useState(null);C.useEffect(()=>{var k,A;(k=s.current)==null||k.focus(),(A=s.current)==null||A.select()},[]),C.useEffect(()=>{if(!e)return;const k=e.onDidChangeResults(A=>{v(A)});return()=>k.dispose()},[e]);const x={caseSensitive:o,wholeWord:d,regex:h,decorations:{matchBackground:"#e8a63880",matchBorder:"#e8a638",matchOverviewRuler:"#e8a638cc",activeMatchBackground:"#515c6a",activeMatchBorder:"#74879f",activeMatchColorOverviewRuler:"#74879fcc"}},f=C.useCallback(()=>{!e||!a||e.findNext(a,x)},[e,a,o,d,h]),b=C.useCallback(()=>{!e||!a||e.findPrevious(a,x)},[e,a,o,d,h]);C.useEffect(()=>{e&&(a?e.findNext(a,x)===!1&&v({resultIndex:-1,resultCount:0}):(e.clearDecorations(),v(null)))},[e,a,o,d,h]);const g=C.useCallback(()=>{e==null||e.clearDecorations(),t(),r()},[e,t,r]),_=C.useCallback(k=>{k.key==="Escape"?(k.preventDefault(),g()):k.key==="Enter"||k.key==="ArrowDown"?(k.preventDefault(),k.shiftKey?b():f()):k.key==="ArrowUp"&&(k.preventDefault(),b())},[g,f,b]),y=a.length>0,S=y&&m!==null&&m.resultCount===0,w=y?m===null||m.resultCount===0?n("terminal.search.noResults"):`${m.resultIndex+1} of ${m.resultCount}`:n("terminal.search.noResults");return i.jsxs("div",{className:"terminal-search-bar",onKeyDown:_,onClick:k=>k.stopPropagation(),onMouseDown:k=>k.stopPropagation(),children:[i.jsxs("div",{className:"terminal-search-input-wrapper",children:[i.jsx("input",{ref:s,type:"text",className:"terminal-search-input",placeholder:n("terminal.search.placeholder"),value:a,onChange:k=>l(k.target.value),spellCheck:!1,autoComplete:"off"}),i.jsx("button",{className:`terminal-search-toggle ${o?"active":""}`,onClick:()=>c(!o),title:n("terminal.search.caseSensitive"),children:"Aa"}),i.jsx("button",{className:`terminal-search-toggle ${d?"active":""}`,onClick:()=>u(!d),title:n("terminal.search.wholeWord"),children:i.jsx("span",{className:"terminal-search-toggle-ab",children:"ab"})}),i.jsx("button",{className:`terminal-search-toggle ${h?"active":""}`,onClick:()=>p(!h),title:n("terminal.search.regex"),children:".*"})]}),i.jsx("span",{className:`terminal-search-results ${S?"no-results":""}`,children:w}),i.jsx("button",{className:"terminal-search-btn",onClick:b,title:n("terminal.search.previous"),disabled:!a,children:i.jsx(GC,{size:16})}),i.jsx("button",{className:"terminal-search-btn",onClick:f,title:n("terminal.search.next"),disabled:!a,children:i.jsx(rt,{size:16})}),i.jsx("button",{className:"terminal-search-btn",onClick:g,title:n("terminal.search.close"),children:i.jsx(at,{size:16})})]})}const g_={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},b_={background:"#191a1b",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#191a1b",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"},KR=2e3;function Bl(){return ve({"Content-Type":"application/json"})}function YR(e){const t=window.location,r=t.protocol==="https:"?"wss:":"ws:",n=Il(),s=n?`?token=${encodeURIComponent(n)}`:"";return`${r}//${t.host}/api/v1/pty/${e}/ws${s}`}async function y_(e){try{return(await fetch(`/api/v1/pty/${e}`,{headers:Bl()})).ok}catch{return!1}}async function __(e,t,r){const n={cols:e,rows:t};r&&(n.cwd=r);const s=await fetch("/api/v1/pty",{method:"POST",headers:Bl(),body:JSON.stringify(n)});if(!s.ok){const o=await s.json().catch(()=>null),c=typeof(o==null?void 0:o.error)=="string"?o.error:typeof(o==null?void 0:o.message)=="string"?o.message:`HTTP ${s.status}`;throw new Error(c)}const a=await s.json(),l=a.data??a;return{sessionId:l.sessionId,cwd:typeof l.cwd=="string"?l.cwd:"",shell:typeof l.shell=="string"?l.shell:void 0}}async function x_(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:Bl()});if(!t.ok)return null;const r=await t.json(),n=r.data??r;return{cwd:typeof(n==null?void 0:n.cwd)=="string"?n.cwd:""}}catch{return null}}async function ZR(){try{const e=await fetch("/api/v1/pty",{headers:Bl()});if(!e.ok)return[];const t=await e.json();return(t.data??t).sessions||[]}catch{return[]}}function XR(e){const t=De.getState().panes,r=new Set;for(const[n,s]of Object.entries(t))n!==e&&s.ptySessionId&&r.add(s.ptySessionId);return r}function Pl({paneId:e,initialCwd:t,onPtyCreated:r}){const{t:n}=de(),{resolved:s}=Jt(),a=De(B=>B.panes[e]),l=De(B=>B.activePaneId),o=De(B=>B.layout),c=De(B=>B.mainView),d=De(B=>B.setActivePaneId),u=De(B=>B.closePane),h=De(B=>B.setPaneSession),p=De(B=>B.setPaneStatus),m=De(B=>B.setPaneError),v=De(B=>B.setPaneTitle),x=De(B=>B.setTerminalTitle),f=l===e,b=Ai(o),[g,_]=C.useState(!1),y=C.useRef(null),S=C.useRef(null),w=C.useRef(null),k=C.useRef(null),A=C.useRef(null),N=C.useRef(null),j=C.useRef(null),$=C.useRef(!0),L=C.useRef(!1),E=C.useRef(!1),M=C.useRef(null),O=C.useRef(null),z=C.useRef(!1),U=C.useRef(!1),Q=C.useRef(t);Q.current=t;const I=C.useRef(r);I.current=r;const T=C.useCallback(()=>{const B=j.current;B&&(B.close(),j.current=null)},[]),D=C.useCallback((B,F)=>{T(),p(e,"connecting"),O.current=F;const Z=new WebSocket(YR(F));j.current=Z;let J=null,te=null;const ne=()=>{if(!$.current)return;const ye=w.current;if(U.current=!0,ye)try{ye.fit()}catch{}B.refresh(0,B.rows-1),z.current||B.scrollToBottom(),requestAnimationFrame(()=>{$.current&&(z.current||B.scrollToBottom(),U.current=!1)})},re=()=>{te&&clearTimeout(te),te=setTimeout(()=>{te=null,ne()},0)},me=(ye,be)=>{var $e;if(!z.current){B.write(ye,be);return}const le=($e=y.current)==null?void 0:$e.querySelector(".xterm-viewport");if(!le){B.write(ye,be);return}const _e=le.scrollTop;U.current=!0;const Te=()=>{le.scrollTop=_e};le.addEventListener("scroll",Te),B.write(ye,()=>{le.scrollTop=_e,requestAnimationFrame(()=>{le.scrollTop=_e,le.removeEventListener("scroll",Te),U.current=!1}),be==null||be()})};Z.onopen=()=>{$.current&&(p(e,"connected"),m(e,null),requestAnimationFrame(()=>{if(!$.current)return;const ye=w.current;if(ye)try{const be=ye.proposeDimensions();be&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"resize",cols:be.cols,rows:be.rows}))}catch{}}),B.focus(),J=setInterval(()=>{Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"ping"}))},25e3))},Z.onmessage=ye=>{if($.current)try{const be=JSON.parse(ye.data);switch(be.type){case"output":be.data&&me(be.data,re);break;case"exit":h(e,null),p(e,"disconnected"),E.current=!1,O.current=null,B.write(`\r
834
834
  ${n("terminal.processExited")}\r
835
835
  `);break;case"pong":break}}catch{}},Z.onerror=()=>{$.current&&(p(e,"error"),m(e,n("terminal.wsConnectionFailed")))},Z.onclose=()=>{var be;if(!$.current)return;((be=De.getState().panes[e])==null?void 0:be.ptyStatus)==="connected"&&(p(e,"error"),m(e,n("terminal.connectionLost")))};const he=B.onData(ye=>{Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"input",data:ye}))}),pe=B.onResize(({cols:ye,rows:be})=>{Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"resize",cols:ye,rows:be}))});E.current=!0;const ae=()=>{J&&(clearInterval(J),J=null),he.dispose(),pe.dispose(),T(),O.current=null};return M.current=ae,ae},[T,e,h,p,m]),R=C.useCallback(()=>{const B=y.current;if(!B||L.current)return;const F=s==="dark"?b_:g_;for(;B.firstChild;)B.removeChild(B.firstChild);const Z=new ER.Terminal({cursorBlink:!0,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:F,allowProposedApi:!0,scrollback:5e4}),J=new eT.FitAddon;Z.loadAddon(J);let te=null;const ne=(xe,Ne)=>{te&&te.remove(),te=document.createElement("div"),te.textContent=Ne,te.className="xterm-link-tooltip",Object.assign(te.style,{position:"fixed",left:`${xe.clientX}px`,top:`${xe.clientY+16}px`,padding:"2px 8px",borderRadius:"4px",fontSize:"12px",pointerEvents:"none",zIndex:"10000",maxWidth:"600px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",background:"var(--color-bg-tertiary, #333)",color:"var(--color-text-primary, #eee)",border:"1px solid var(--color-border-muted, #555)"}),document.body.appendChild(te)},re=()=>{te&&(te.remove(),te=null)},me=new GI.WebLinksAddon((xe,Ne)=>{window.open(Ne,"_blank","noopener")},{hover(xe,Ne){ne(xe,Ne)},leave:re});Z.loadAddon(me);const he=/(?:(?:\.{1,2}\/|\/)[a-zA-Z0-9._\-~@+/]+[a-zA-Z0-9._\-~@+])(?::(\d+)(?::(\d+))?)?/g,pe=["/api/","/http","/dev/","/proc/","/sys/","/tmp/"];Z.registerLinkProvider({provideLinks(xe,Ne){const ir=Z.buffer.active.getLine(xe-1);if(!ir){Ne(void 0);return}const Ys=ir.translateToString(!0),zr=[];he.lastIndex=0;let vn;for(;(vn=he.exec(Ys))!==null;){const _s=vn[0],so=vn.index,io=_s.indexOf(":"),Ur=io>=0?_s.slice(0,io):_s;if(pe.some(Gn=>Ur.startsWith(Gn))||!Ur.includes(".")&&!Ur.endsWith("/"))continue;const Zi=vn[1]?parseInt(vn[1],10):void 0,Xi=vn[2]?parseInt(vn[2],10):void 0,oc=Zi?`${Ur}:${Zi}${Xi?":"+Xi:""}`:Ur;zr.push({range:{start:{x:so+1,y:xe},end:{x:so+_s.length+1,y:xe}},text:_s,activate(){var ln;const Gn=jl()||((ln=Or.getState().info)==null?void 0:ln.cwd),lc=Ur.startsWith("/")?Ur:Gn?`${Gn}/${Ur}`:Ur;oh(lc,Zi,Xi)},hover(Gn){ne(Gn,`${oc} — Click to open in editor`)},leave:re})}Ne(zr.length>0?zr:void 0)}}),Z.attachCustomKeyEventHandler(xe=>xe.key==="f"&&(xe.metaKey||xe.ctrlKey)&&!xe.shiftKey&&!xe.altKey?(xe.type==="keydown"&&(xe.preventDefault(),_(!0)),!1):xe.key==="Enter"&&xe.shiftKey?(xe.type==="keydown"&&Z.input("\x1B[13;2u",!0),!1):!0),Z.open(B);const ae=new UI;Z.loadAddon(ae),Z.unicode.activeVersion="11";const ye=new mI;Z.loadAddon(ye);const be=new cI;Z.loadAddon(be),A.current=be;const le=new Y2;Z.loadAddon(le);try{const xe=new CR;xe.onContextLoss(()=>{xe.dispose(),k.current=null,N.current&&(N.current.dispose(),N.current=null)}),Z.loadAddon(xe),k.current=xe;const Ne=new NT;Z.loadAddon(Ne),N.current=Ne}catch{}const _e=B.querySelector(".xterm-helper-textarea");_e&&(_e.setAttribute("autocomplete","off"),_e.setAttribute("autocorrect","off"),_e.setAttribute("autocapitalize","off"),_e.setAttribute("spellcheck","false"),_e.setAttribute("unselectable","on")),S.current=Z,w.current=J,L.current=!0;const Te=B.querySelector(".xterm-viewport"),$e=()=>{if(U.current||!Te)return;const xe=Te.scrollHeight-Te.scrollTop-Te.clientHeight<5;z.current=!xe};Te==null||Te.addEventListener("scroll",$e);const Ze=Z.onTitleChange(xe=>{$.current&&xe&&(x(xe),v(e,xe))});let ce=B.offsetParent===null;const Ce=()=>{if($.current)try{U.current=!0;const xe=B.offsetParent!==null,Ne=ce&&xe;ce=!xe;const ir=J.proposeDimensions();if(ir&&(ir.cols!==Z.cols||ir.rows!==Z.rows))J.fit();else if(Ne){const Ys=Z.cols,zr=Z.rows;Z.resize(Ys-1,zr),Z.resize(Ys,zr)}Z.refresh(0,Z.rows-1),z.current||Z.scrollToBottom(),requestAnimationFrame(()=>{$.current&&(z.current||Z.scrollToBottom(),U.current=!1)})}catch{U.current=!1}};let Le=null;const lt=()=>{const xe=B.offsetParent!==null;if(ce&&xe){Le&&clearTimeout(Le),Le=null,Ce();return}Le&&clearTimeout(Le),Le=setTimeout(Ce,50)},jt=new ResizeObserver(lt);jt.observe(B),window.addEventListener("resize",lt);const Qt=()=>{document.visibilityState==="visible"&&lt()};return document.addEventListener("visibilitychange",Qt),()=>{Te==null||Te.removeEventListener("scroll",$e),Ze.dispose(),jt.disconnect(),window.removeEventListener("resize",lt),document.removeEventListener("visibilitychange",Qt),Le&&clearTimeout(Le),te&&(te.remove(),te=null)}},[]),G=C.useCallback(async()=>{var ne,re;const B=S.current,F=w.current;if(!B||!F||!$.current||E.current)return;let Z=80,J=24;try{const me=F.proposeDimensions();me&&(Z=me.cols,J=me.rows)}catch{}const te=(ne=De.getState().panes[e])==null?void 0:ne.ptySessionId;if(te&&await y_(te)&&$.current){if(D(B,te),I.current){const he=await x_(te);he&&$.current&&I.current({sessionId:te,cwd:he.cwd})}return}if($.current){if(!te){const me=XR(e),pe=(await ZR()).find(ae=>!ae.hasClient&&!me.has(ae.id));if(pe&&$.current){if(h(e,pe.id),D(B,pe.id),I.current){const ae=await x_(pe.id);ae&&$.current&&I.current({sessionId:pe.id,cwd:ae.cwd})}return}}if($.current){p(e,"connecting");try{const me=Q.current||void 0,{sessionId:he,cwd:pe,shell:ae}=await __(Z,J,me);if(!$.current)return;h(e,he),ae&&v(e,ae),D(B,he),(re=I.current)==null||re.call(I,{sessionId:he,cwd:pe})}catch(me){if(!$.current)return;p(e,"error"),m(e,me.message||n("terminal.createSessionFailed"))}}}},[D,e,h,p,m]),P=C.useRef(null);C.useEffect(()=>{$.current=!0;const B=y.current;if(!B)return;const F=()=>{if(!$.current)return;const{clientWidth:J,clientHeight:te}=B;J===0||te===0||(L.current||(P.current=R()||null),S.current&&w.current&&(E.current||G()))};if(B.clientWidth>0&&B.clientHeight>0){const J=requestAnimationFrame(F);return()=>cancelAnimationFrame(J)}const Z=new ResizeObserver(J=>{for(const te of J){const{width:ne,height:re}=te.contentRect;if(ne>0&&re>0){Z.disconnect(),F();break}}});return Z.observe(B),()=>Z.disconnect()},[R,G]),C.useEffect(()=>()=>{var B,F,Z;$.current=!1,(B=M.current)==null||B.call(M),(F=P.current)==null||F.call(P);try{(Z=S.current)==null||Z.dispose()}catch{}S.current=null,w.current=null,k.current=null,A.current=null,N.current=null,L.current=!1,E.current=!1},[]),C.useEffect(()=>{const B=S.current;if(B){const F=s==="dark"?b_:g_;B.options.theme=F;try{B.refresh(0,B.rows-1)}catch{}}},[s,c]);const H=C.useCallback(async()=>{var F,Z,J;if(T(),E.current=!1,p(e,"connecting"),m(e,null),await new Promise(te=>setTimeout(te,KR)),!$.current)return;const B=S.current;if(B)try{B.clear();try{(F=w.current)==null||F.fit()}catch{}const te=B.cols||80,ne=B.rows||24,re=(Z=De.getState().panes[e])==null?void 0:Z.ptySessionId;if(re&&await y_(re)&&$.current){D(B,re);return}if(!$.current)return;const me=Q.current||void 0,{sessionId:he,cwd:pe}=await __(te,ne,me);if(!$.current)return;h(e,he),D(B,he),(J=I.current)==null||J.call(I,{sessionId:he,cwd:pe})}catch(te){if(!$.current)return;p(e,"error"),m(e,te.message||n("terminal.reconnectFailed"))}},[T,D,e,h,p,m]),q=C.useCallback(()=>{var B;f||d(e),(B=S.current)==null||B.focus()},[f,e,d]);return a?i.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full min-h-0 ${f&&b>1?"active":""}`,style:{backgroundColor:"var(--ide-side-panel-bg)"},onClick:q,children:[g&&i.jsx(VR,{searchAddon:A.current,onClose:()=>_(!1),onFocusTerminal:()=>{var B;return(B=S.current)==null?void 0:B.focus()}}),b>1&&i.jsx("div",{className:"terminal-pane-toolbar",children:i.jsx("button",{onClick:B=>{B.stopPropagation(),u(e)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:n("terminal.closePane"),children:i.jsx(at,{size:14})})}),i.jsx("div",{ref:y,className:"flex-1 w-full min-h-0",style:{overflow:"hidden",padding:"4px"}}),a.ptyStatus==="connecting"&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{backgroundColor:"var(--ide-side-panel-bg)"},children:i.jsx(He,{size:20,className:"animate-spin",style:{color:"var(--color-text-tertiary)"}})}),a.ptyStatus==="error"&&i.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[i.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[i.jsx(YC,{size:14}),i.jsx("span",{children:a.errorMessage||n("terminal.error")})]}),i.jsxs("button",{onClick:H,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[i.jsx(St,{size:12}),i.jsx("span",{children:n("terminal.reconnect")})]})]})]}):i.jsx("div",{})}const v_=400,w_=300,Xc=200,Jc=150,ed=.1,td=5,hn=20,S_=3,T0=8,JR=10,I0=32,eL=I0;function N0(){return ve({"Content-Type":"application/json"})}async function tL(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:N0()});if(!t.ok)return null;const r=await t.json(),n=r.data??r;return typeof(n==null?void 0:n.cwd)=="string"?n.cwd:null}catch{return null}}function R0(e){const t=Object.values(e);if(t.length===0)return;const n={...De.getState().panes};let s=!1;for(const a of t){const l=n[a.paneId];l?a.ptySessionId&&l.ptySessionId!==a.ptySessionId&&(n[a.paneId]={...l,ptySessionId:a.ptySessionId},s=!0):(n[a.paneId]={id:a.paneId,ptySessionId:a.ptySessionId??null,ptyStatus:"disconnected",errorMessage:null},s=!0)}s&&De.setState({panes:n})}const it=Ke()(Gs((e,t)=>({viewport:{panX:0,panY:0,zoom:1},tiles:{},nextZIndex:1,selectedTileIds:[],setViewport:r=>{e({viewport:r})},addTile:()=>{const r=`tile-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,n=`canvas-pane-${r}`,{nextZIndex:s,viewport:a}=t(),l=a.zoom||1,o=(-a.panX+window.innerWidth/2)/l-v_/2,c=(-a.panY+window.innerHeight/2)/l-w_/2,d=Math.round(o/hn)*hn,u=Math.round(c/hn)*hn,h={id:r,type:"terminal",x:d,y:u,width:v_,height:w_,zIndex:s,paneId:n,windowState:"normal",ptySessionId:null,cwd:null},p=De.getState();if(!p.panes[n]){const m={...p.panes,[n]:{id:n,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}};De.setState({panes:m})}return e(m=>({tiles:{...m.tiles,[r]:h},nextZIndex:m.nextZIndex+1})),r},duplicateTile:r=>{var g,_,y,S;const n=t().tiles[r];if(!n)return null;const s=`tile-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=`canvas-pane-${s}`,{nextZIndex:l}=t(),o=((g=n.prevBounds)==null?void 0:g.width)??n.width,c=((_=n.prevBounds)==null?void 0:_.height)??n.height,d=((y=n.prevBounds)==null?void 0:y.x)??n.x,u=((S=n.prevBounds)==null?void 0:S.y)??n.y,h=hn*2,p=Math.round((d+h)/hn)*hn,m=Math.round((u+h)/hn)*hn,v={id:s,type:"terminal",x:p,y:m,width:o,height:c,zIndex:l,paneId:a,windowState:"normal",ptySessionId:null,cwd:n.cwd??null},x=De.getState();x.panes[a]||De.setState({panes:{...x.panes,[a]:{id:a,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}}),e(w=>({tiles:{...w.tiles,[s]:v},nextZIndex:w.nextZIndex+1}));const f=De.getState().panes[n.paneId],b=f==null?void 0:f.ptySessionId;return b&&tL(b).then(w=>{w&&(t().updateTile(n.id,{cwd:w}),t().updateTile(s,{cwd:w}))}),s},removeTile:r=>{const n=t().tiles[r];if(n){const s=De.getState(),a=s.panes[n.paneId];if(a!=null&&a.ptySessionId&&fetch(`/api/v1/pty/${a.ptySessionId}`,{method:"DELETE",headers:N0()}).catch(()=>{}),s.panes[n.paneId]){const{[n.paneId]:l,...o}=s.panes;De.setState({panes:o})}}e(s=>{const{[r]:a,...l}=s.tiles;return{tiles:l,selectedTileIds:s.selectedTileIds.filter(o=>o!==r)}})},updateTile:(r,n)=>{e(s=>{const a=s.tiles[r];return a?{tiles:{...s.tiles,[r]:{...a,...n}}}:s})},selectTile:r=>e({selectedTileIds:[r]}),deselectAll:()=>e({selectedTileIds:[]}),selectTiles:r=>e({selectedTileIds:r}),bringToFront:r=>{e(n=>{const s=n.tiles[r];return s?{tiles:{...n.tiles,[r]:{...s,zIndex:n.nextZIndex}},nextZIndex:n.nextZIndex+1}:n})},maximizeTile:r=>{e(n=>{const s=n.tiles[r];if(!s)return n;const a=s.windowState==="normal"?{x:s.x,y:s.y,width:s.width,height:s.height}:s.prevBounds;return{tiles:{...n.tiles,[r]:{...s,windowState:"maximized",prevBounds:a,zIndex:n.nextZIndex}},nextZIndex:n.nextZIndex+1}})},minimizeTile:r=>{e(n=>{const s=n.tiles[r];if(!s)return n;const a=s.windowState==="normal"?{x:s.x,y:s.y,width:s.width,height:s.height}:s.prevBounds;return{tiles:{...n.tiles,[r]:{...s,height:eL,windowState:"minimized",prevBounds:a}}}})},restoreTile:r=>{e(n=>{const s=n.tiles[r];return!s||!s.prevBounds?s?{tiles:{...n.tiles,[r]:{...s,windowState:"normal"}}}:n:{tiles:{...n.tiles,[r]:{...s,x:s.prevBounds.x,y:s.prevBounds.y,width:s.prevBounds.width,height:s.prevBounds.height,windowState:"normal",prevBounds:void 0}}}})},toggleMaximize:r=>{const n=t().tiles[r];n&&(n.windowState==="maximized"?t().restoreTile(r):t().maximizeTile(r))},toggleMinimize:r=>{const n=t().tiles[r];n&&(n.windowState==="minimized"?t().restoreTile(r):t().minimizeTile(r))},setTilePty:(r,n,s)=>{let a=null;if(e(l=>{const o=l.tiles[r];if(!o)return l;a=o.paneId;const c={...o,ptySessionId:n};return s!==void 0&&(c.cwd=s),{tiles:{...l.tiles,[r]:c}}}),a){const l=De.getState(),o=l.panes[a];o&&o.ptySessionId!==n&&De.setState({panes:{...l.panes,[a]:{...o,ptySessionId:n}}})}},loadFromStorage:()=>{}}),{namespace:"canvas",fields:["viewport","tiles","nextZIndex"],scope:"workspace",debounceMs:1e3,onLoad:(e,t)=>{const r={};e.viewport&&(r.viewport=e.viewport),e.tiles&&(r.tiles=e.tiles),e.nextZIndex!==void 0&&(r.nextZIndex=e.nextZIndex),Object.keys(r).length>0&&(t(r),r.tiles&&R0(r.tiles))}}));R0(it.getState().tiles);function rL(){const{t:e}=de(),[t,r]=C.useState(()=>hl().get("paneId")||"");C.useEffect(()=>{const o=()=>{r(hl().get("paneId")||"")};return window.addEventListener("hashchange",o),()=>window.removeEventListener("hashchange",o)},[]);const n=it(o=>Object.values(o.tiles).find(c=>c.paneId===t)??null),s=De(o=>{var c;return t?(c=o.panes[t])==null?void 0:c.title:null}),a=it(o=>o.setTilePty),l=C.useCallback(o=>{n&&a(n.id,o.sessionId,o.cwd||null)},[n,a]);return C.useEffect(()=>{if(!t)return;const o=De.getState();o.panes[t]||De.setState({panes:{...o.panes,[t]:{id:t,ptySessionId:(n==null?void 0:n.ptySessionId)??null,ptyStatus:"disconnected",errorMessage:null}}})},[t,n==null?void 0:n.ptySessionId]),t?i.jsxs("div",{className:"flex flex-col h-full w-full bg-bg-primary",children:[i.jsxs("div",{className:"flex items-center gap-2 px-3 select-none",style:{height:32,background:"var(--color-canvas-tile-header)",color:"var(--color-canvas-tile-header-text)",borderBottom:"1px solid var(--color-border-default)"},children:[i.jsx(qs,{size:14,style:{opacity:.6}}),i.jsx("span",{className:"text-xs truncate",style:{fontSize:12,fontWeight:500},children:s||e("canvas.defaultTitle")})]}),i.jsx("div",{className:"flex-1 min-h-0 relative",children:i.jsx(Pl,{paneId:t,initialCwd:(n==null?void 0:n.cwd)??null,onPtyCreated:l})})]}):i.jsx("div",{className:"flex items-center justify-center h-full w-full bg-bg-primary text-text-secondary text-sm",children:e("canvas.standalone.missingPaneId")})}class Go{constructor(){fe(this,"panX",0);fe(this,"panY",0);fe(this,"zoom",1)}getState(){return{panX:this.panX,panY:this.panY,zoom:this.zoom}}setState(t){this.panX=t.panX,this.panY=t.panY,this.zoom=Math.max(ed,Math.min(td,t.zoom))}screenToWorld(t,r){return this.zoom===0?{x:0,y:0}:{x:(t-this.panX)/this.zoom,y:(r-this.panY)/this.zoom}}worldToScreen(t,r){return{x:t*this.zoom+this.panX,y:r*this.zoom+this.panY}}applyZoom(t,r,n){const s=this.zoom,a=Math.exp(-t*.6/100),l=Math.max(ed,Math.min(td,s*a));if(s===0)return this.zoom=l,this.getState();const o=l/s-1;return this.panX-=(r-this.panX)*o,this.panY-=(n-this.panY)*o,this.zoom=l,this.getState()}applyPan(t,r){return this.panX+=t,this.panY+=r,this.getState()}fitTiles(t,r,n,s=40){if(t.length===0)return this.resetView();let a=1/0,l=1/0,o=-1/0,c=-1/0;for(const f of t)a=Math.min(a,f.x),l=Math.min(l,f.y),o=Math.max(o,f.x+f.width),c=Math.max(c,f.y+f.height);const d=o-a,u=c-l;if(d<=0||u<=0)return this.resetView();const h=r-s*2,p=n-s*2;if(h<=0||p<=0)return this.resetView();const m=Math.max(ed,Math.min(td,Math.min(h/d,p/u))),v=(r-d*m)/2-a*m,x=(n-u*m)/2-l*m;return this.panX=v,this.panY=x,this.zoom=m,this.getState()}resetView(){return this.panX=0,this.panY=0,this.zoom=1,this.getState()}}const k_=120;function nL(){const{t:e}=de(),t=it(b=>b.viewport),r=it(b=>b.tiles),n=it(b=>b.setViewport),s=it(b=>b.addTile),a=C.useRef(null),l=Math.round(t.zoom*100),o=typeof window<"u"&&window.location.hash.includes("standalone");if(Object.values(r).some(b=>b.windowState==="maximized"))return null;const d=()=>{var g;const b=(g=a.current)==null?void 0:g.parentElement;return{w:(b==null?void 0:b.clientWidth)??window.innerWidth,h:(b==null?void 0:b.clientHeight)??window.innerHeight}},u=()=>{const b=new Go;b.setState(t);const{w:g,h:_}=d(),y=b.applyZoom(-k_,g/2,_/2);n(y)},h=()=>{const b=new Go;b.setState(t);const{w:g,h:_}=d(),y=b.applyZoom(k_,g/2,_/2);n(y)},p=()=>{const b=new Go;b.setState(t);const{w:g,h:_}=d(),y=Object.values(r);y.length===0?n(b.resetView()):n(b.fitTiles(y,g,_,60))},m=()=>{s()},v=()=>{const b=new URLSearchParams(window.location.search),g=new URLSearchParams;g.set("standalone","1"),b.forEach((y,S)=>{g.has(S)||g.set(S,y)});const _=`${window.location.pathname}${window.location.search}#/canvas?${g.toString()}`;window.open(_,"canvas-standalone","noopener,noreferrer")},x="w-8 h-8 flex items-center justify-center rounded-lg transition-colors",f={border:"none",background:"transparent",color:"var(--color-text-secondary)",cursor:"pointer"};return i.jsxs("div",{ref:a,className:"canvas-toolbar fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 px-2 py-1 rounded-xl",style:{background:"var(--color-bg-card)",border:"1px solid var(--color-border-default)",boxShadow:"0 2px 12px rgba(0,0,0,0.12)",zIndex:1e4},children:[i.jsx("button",{className:x,style:f,onClick:m,title:e("canvas.addTerminal"),children:i.jsx(Ot,{size:16})}),i.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),i.jsx("button",{className:x,style:f,onClick:h,title:e("canvas.zoomOut"),children:i.jsx(P2,{size:16})}),i.jsxs("span",{className:"text-xs tabular-nums select-none",style:{minWidth:40,textAlign:"center",color:"var(--color-text-secondary)"},children:[l,"%"]}),i.jsx("button",{className:x,style:f,onClick:u,title:e("canvas.zoomIn"),children:i.jsx(j2,{size:16})}),i.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),i.jsx("button",{className:x,style:f,onClick:p,title:e("canvas.fitView"),children:i.jsx(mE,{size:16})}),!o&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),i.jsx("button",{className:x,style:f,onClick:v,title:e("canvas.openStandalone"),children:i.jsx(Ar,{size:16})})]})]})}function ei(e,t=hn,r=JR){const n=(e%t+t)%t;return n<=r?e-n:t-n<=r?e+(t-n):e}function sL(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}class iL{constructor(){fe(this,"dragState",null);fe(this,"spacePressed",!1);fe(this,"callbacks",null);fe(this,"keydownHandler",null);fe(this,"keyupHandler",null);fe(this,"dragStarted",!1);fe(this,"panSamples",[])}attach(t){this.callbacks=t,this.keydownHandler=r=>{if(r.code==="Space"&&!r.repeat){if(sL(r.target))return;this.spacePressed=!0,r.preventDefault()}},this.keyupHandler=r=>{r.code==="Space"&&(this.spacePressed=!1)},window.addEventListener("keydown",this.keydownHandler),window.addEventListener("keyup",this.keyupHandler)}detach(){this.keydownHandler&&(window.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null),this.keyupHandler&&(window.removeEventListener("keyup",this.keyupHandler),this.keyupHandler=null),this.callbacks=null,this.dragState=null}get isSpacePressed(){return this.spacePressed}get isDragging(){return this.dragState!==null&&this.dragStarted}get currentDrag(){return this.dragState}handlePointerDown(t,r,n,s){var c,d,u;const a=t.clientX,l=t.clientY;this.dragStarted=!1,this.panSamples=[],(d=(c=this.callbacks)==null?void 0:c.onInteractionStart)==null||d.call(c);const o=(u=this.callbacks)==null?void 0:u.getViewport();if(this.spacePressed||!r&&!n){const h=t.shiftKey||t.ctrlKey||t.metaKey;!this.spacePressed&&h?this.dragState={type:"select",startScreenX:a,startScreenY:l}:(this.dragState={type:"pan",startScreenX:a,startScreenY:l,initialViewport:o?{...o}:void 0},this.panSamples=[{t:performance.now(),x:a,y:l}]);return}if(r&&n){const h=s[r];if(!h)return;this.dragState={type:"resize",startScreenX:a,startScreenY:l,tileId:r,handle:n,initialTiles:{[r]:{x:h.x,y:h.y,width:h.width,height:h.height}}};return}if(r){const h=s[r];if(!h)return;const p={};p[r]={x:h.x,y:h.y,width:h.width,height:h.height},this.dragState={type:"move",startScreenX:a,startScreenY:l,tileId:r,initialTiles:p}}}handlePointerMove(t){var a,l;if(!this.dragState||!this.callbacks)return;const r=t.clientX-this.dragState.startScreenX,n=t.clientY-this.dragState.startScreenY;if(!this.dragStarted){if(Math.abs(r)<S_&&Math.abs(n)<S_)return;this.dragStarted=!0}const s=this.callbacks.getViewport();switch(this.dragState.type){case"pan":{const o=this.dragState.initialViewport;if(o){const u=r,h=n;this.callbacks.onViewportPan(o.panX+u-s.panX,o.panY+h-s.panY)}const c=performance.now();this.panSamples.push({t:c,x:t.clientX,y:t.clientY});const d=c-100;for(;this.panSamples.length>2&&this.panSamples[0].t<d;)this.panSamples.shift();break}case"move":{if(this.dragState.tileId&&s.zoom!==0){const o=r/s.zoom,c=n/s.zoom,d=(a=this.dragState.initialTiles)==null?void 0:a[this.dragState.tileId];d&&this.callbacks.onTileMove(this.dragState.tileId,ei(d.x+o),ei(d.y+c))}break}case"resize":{if(this.dragState.tileId&&this.dragState.handle&&s.zoom!==0){const o=(l=this.dragState.initialTiles)==null?void 0:l[this.dragState.tileId];if(o){const c=r/s.zoom,d=n/s.zoom,u=this.applyResize(this.dragState.handle,o,c,d);this.callbacks.onTileResize(this.dragState.tileId,u)}}break}case"select":{const o={x:Math.min(this.dragState.startScreenX,t.clientX),y:Math.min(this.dragState.startScreenY,t.clientY),width:Math.abs(r),height:Math.abs(n)};this.callbacks.onSelectionBox(o);break}}}handlePointerUp(t){var s,a,l,o;if(!this.callbacks){this.dragState=null;return}const r=((s=this.dragState)==null?void 0:s.type)==="pan",n=this.dragStarted;if(this.dragStarted?((o=this.dragState)==null?void 0:o.type)==="select"&&(this.callbacks.onSelectionBox(null),this.callbacks.onBoxSelectEnd([])):(a=this.dragState)!=null&&a.tileId?this.callbacks.onTileClick(this.dragState.tileId):((l=this.dragState)==null?void 0:l.type)==="select"&&this.callbacks.onCanvasClick(),r&&n&&this.panSamples.length>=2&&this.callbacks.onPanInertiaStart){const c=this.panSamples[this.panSamples.length-1],d=this.panSamples[0],u=c.t-d.t;if(u>0){const h=(c.x-d.x)/u,p=(c.y-d.y)/u;Math.hypot(h,p)>.05&&this.callbacks.onPanInertiaStart(h,p)}}this.dragState=null,this.dragStarted=!1,this.panSamples=[]}getSelectedTileIds(t,r){const n=[],s=t.x,a=t.y,l=t.width,o=t.height;for(const c of Object.values(r))c.x<s+l&&c.x+c.width>s&&c.y<a+o&&c.y+c.height>a&&n.push(c.id);return n}getResizeHandle(t,r,n,s=T0){const{x:a,y:l,width:o,height:c}=t,d=a+o/2,u=l+c/2,h=a+o,p=l+c;return this.hitTest(r,n,a,l,s)?"nw":this.hitTest(r,n,h,l,s)?"ne":this.hitTest(r,n,a,p,s)?"sw":this.hitTest(r,n,h,p,s)?"se":this.hitTest(r,n,d,l,s)?"n":this.hitTest(r,n,d,p,s)?"s":this.hitTest(r,n,a,u,s)?"w":this.hitTest(r,n,h,u,s)?"e":null}applyResize(t,r,n,s){let{x:a,y:l,width:o,height:c}=r;switch(t){case"n":l=r.y+s,c=r.height-s;break;case"s":c=r.height+s;break;case"w":a=r.x+n,o=r.width-n;break;case"e":o=r.width+n;break;case"nw":a=r.x+n,l=r.y+s,o=r.width-n,c=r.height-s;break;case"ne":l=r.y+s,o=r.width+n,c=r.height-s;break;case"sw":a=r.x+n,o=r.width-n,c=r.height+s;break;case"se":o=r.width+n,c=r.height+s;break}return o<Xc&&((t==="w"||t==="nw"||t==="sw")&&(a=r.x+r.width-Xc),o=Xc),c<Jc&&((t==="n"||t==="nw"||t==="ne")&&(l=r.y+r.height-Jc),c=Jc),a=ei(a),l=ei(l),o=ei(o),c=ei(c),{x:a,y:l,width:o,height:c}}isInTileHeader(t,r,n,s){const a=I0*s;return r>=t.x&&r<=t.x+t.width&&n>=t.y&&n<=t.y+a}hitTest(t,r,n,s,a){return Math.abs(t-n)<=a&&Math.abs(r-s)<=a}}const aL=[{position:"n",cursor:"ns-resize",className:"top-0 left-2 right-2 h-1.5 -translate-y-1/2"},{position:"s",cursor:"ns-resize",className:"bottom-0 left-2 right-2 h-1.5 translate-y-1/2"},{position:"e",cursor:"ew-resize",className:"right-0 top-2 bottom-2 w-1.5 translate-x-1/2"},{position:"w",cursor:"ew-resize",className:"left-0 top-2 bottom-2 w-1.5 -translate-x-1/2"},{position:"nw",cursor:"nwse-resize",className:"top-0 left-0 w-3 h-3 -translate-x-1/2 -translate-y-1/2"},{position:"ne",cursor:"nesw-resize",className:"top-0 right-0 w-3 h-3 translate-x-1/2 -translate-y-1/2"},{position:"sw",cursor:"nesw-resize",className:"bottom-0 left-0 w-3 h-3 -translate-x-1/2 translate-y-1/2"},{position:"se",cursor:"nwse-resize",className:"bottom-0 right-0 w-3 h-3 translate-x-1/2 translate-y-1/2"}];function oL({tile:e,viewport:t,isSelected:r}){const{t:n}=de(),s=it(T=>T.removeTile),a=it(T=>T.duplicateTile),l=it(T=>T.toggleMaximize),o=it(T=>T.toggleMinimize),c=it(T=>T.setTilePty),d=it(T=>T.selectTile),u=it(T=>T.bringToFront),h=De(T=>{var D;return(D=T.panes[e.paneId])==null?void 0:D.title}),{panX:p,panY:m,zoom:v}=t,x=e.x*v+p,f=e.y*v+m,b=e.windowState==="maximized",g=e.windowState==="minimized",_=r?"var(--color-canvas-tile-border-selected)":"var(--color-canvas-tile-border)",y=C.useCallback(()=>{l(e.id)},[e.id,l]),S=C.useCallback(()=>{o(e.id)},[e.id,o]),w=C.useCallback(()=>{a(e.id)},[e.id,a]),k=C.useCallback(T=>{T.target.closest("button")||(T.stopPropagation(),g?o(e.id):l(e.id))},[e.id,g,l,o]),A=C.useCallback(T=>{c(e.id,T.sessionId,T.cwd||null)},[e.id,c]),N=C.useRef(null),[j,$]=C.useState(!1);C.useEffect(()=>{const T=D=>{$(D.shiftKey||D.altKey)};return window.addEventListener("keydown",T),window.addEventListener("keyup",T),()=>{window.removeEventListener("keydown",T),window.removeEventListener("keyup",T)}},[]);const L=r||j,E=C.useRef(null),M=C.useCallback(T=>{E.current={x:T.clientX,y:T.clientY,id:T.pointerId}},[]),O=C.useCallback(T=>{E.current=null},[]),z=C.useCallback(T=>{var G;if(T.ctrlKey||T.metaKey||T.shiftKey||!r)return;const R=(G=N.current)==null?void 0:G.querySelector(".xterm-viewport");R&&(R.scrollTop+=T.deltaY,T.stopPropagation())},[r]),U=C.useCallback(()=>{const T=new URLSearchParams(window.location.search),D=new URLSearchParams;D.set("paneId",e.paneId),T.forEach((G,P)=>{D.has(P)||D.set(P,G)});const R=`${window.location.pathname}${window.location.search}#/canvas-pane?${D.toString()}`;window.open(R,`canvas-pane-${e.paneId}`,"noopener,noreferrer")},[e.paneId]),Q=b?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh",transform:"none",pointerEvents:"auto",zIndex:9999,borderRadius:0,border:"none",overflow:"hidden",boxShadow:"none"}:{transform:`translate(${x}px, ${f}px) scale(${v})`,transformOrigin:"top left",width:e.width,height:e.height,willChange:"transform",pointerEvents:"auto",zIndex:e.zIndex,borderRadius:8,border:`1px solid ${_}`,overflow:"hidden",boxShadow:r?"0 0 0 1px var(--color-canvas-tile-border-selected)":"0 2px 8px rgba(0,0,0,0.08)"},I=C.useCallback(T=>{var P;if(T.button!==0)return;d(e.id),u(e.id);const D=(P=N.current)==null?void 0:P.querySelector(".xterm-helper-textarea");if(!D)return;const R=()=>{try{D.focus()}catch{}};R();const G=()=>{window.removeEventListener("pointerup",G,!0),R()};window.addEventListener("pointerup",G,!0)},[e.id,d,u]);return i.jsxs("div",{className:b?"canvas-tile":"absolute canvas-tile",style:Q,onPointerDownCapture:I,children:[i.jsxs("div",{className:"canvas-tile-header flex items-center gap-1.5 px-2 select-none",style:{height:32,background:"var(--color-canvas-tile-header)",color:"var(--color-canvas-tile-header-text)",cursor:"grab",borderBottom:g?"none":"1px solid var(--color-canvas-tile-border)"},onDoubleClick:k,children:[i.jsx(qs,{size:13,style:{opacity:.5,flexShrink:0}}),i.jsx("span",{className:"flex-1 text-xs truncate",style:{fontSize:12,fontWeight:500},children:h||n("canvas.defaultTitle")}),i.jsx("button",{onClick:T=>{T.stopPropagation(),w()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:n("canvas.tileMenu.duplicate"),children:i.jsx(Ci,{size:12})}),i.jsx("button",{onClick:T=>{T.stopPropagation(),U()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:n("canvas.tileMenu.openStandalone"),children:i.jsx(Ar,{size:12})}),i.jsx("button",{onClick:T=>{T.stopPropagation(),S()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:n(g?"canvas.tileMenu.restore":"canvas.tileMenu.minimize"),children:g?i.jsx(Vu,{size:12}):i.jsx(Pa,{size:12})}),i.jsx("button",{onClick:T=>{T.stopPropagation(),y()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:n(b?"canvas.tileMenu.restore":"canvas.tileMenu.maximize"),children:b?i.jsx(Wu,{size:12}):i.jsx(Ba,{size:12})}),i.jsx("button",{onClick:T=>{T.stopPropagation(),s(e.id)},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:n("canvas.tileMenu.close"),children:i.jsx(at,{size:12})})]}),!g&&i.jsxs("div",{ref:N,className:"flex-1 relative",style:{height:"calc(100% - 32px)",overflow:"hidden"},children:[i.jsx(Pl,{paneId:e.paneId,initialCwd:e.cwd??null,onPtyCreated:A}),i.jsx("div",{className:"absolute inset-0","data-canvas-tile-focused":r?"true":"false",style:{zIndex:5,pointerEvents:L?"none":"auto",background:"transparent"},onPointerDown:M,onPointerUp:O,onWheel:z})]}),!g&&aL.map(T=>i.jsx("div",{className:`absolute ${T.className}`,style:{cursor:T.cursor,zIndex:10,opacity:0},"data-resize-handle":T.position},T.position))]})}function lL({rect:e}){return i.jsx("div",{className:"absolute pointer-events-none",style:{left:e.x,top:e.y,width:e.width,height:e.height,background:"var(--color-canvas-selection-fill)",border:"1px solid var(--color-canvas-selection-stroke)",borderRadius:2,zIndex:999}})}function cL(){const e=C.useRef(null),t=C.useRef(new Go),r=C.useRef(new iL),n=it(T=>T.tiles),s=it(T=>T.viewport),a=it(T=>T.selectedTileIds),l=it(T=>T.setViewport),o=it(T=>T.updateTile),c=it(T=>T.selectTile),d=it(T=>T.selectTiles),u=it(T=>T.deselectAll),h=it(T=>T.bringToFront),[p,m]=C.useState(null),[v,x]=C.useState(!1),[f,b]=C.useState(!1),[g,_]=C.useState(null);C.useEffect(()=>{t.current.setState(s)},[s]);const y=C.useMemo(()=>Object.values(n).sort((T,D)=>T.zIndex-D.zIndex),[n]),S=C.useMemo(()=>new Set(a),[a]),w=C.useRef(s);w.current=s;const k=C.useRef({setViewport:l,updateTile:o,selectTile:c,deselectAll:u,bringToFront:h,selectTiles:d});k.current={setViewport:l,updateTile:o,selectTile:c,deselectAll:u,bringToFront:h,selectTiles:d};const A=.92,N=.01,j=3.5,$=C.useRef(null),L=C.useRef({vx:0,vy:0,last:0}),E=C.useCallback(()=>{$.current!==null&&(cancelAnimationFrame($.current),$.current=null)},[]),M=C.useCallback((T,D)=>{E();const R=Math.hypot(T,D);if(R>j){const P=j/R;T*=P,D*=P}L.current={vx:T,vy:D,last:performance.now()};const G=()=>{const P=performance.now(),H=L.current,q=Math.min(32,P-H.last);H.last=P;const F=t.current.applyPan(H.vx*q,H.vy*q);k.current.setViewport(F);const Z=Math.pow(A,q/16.67);if(H.vx*=Z,H.vy*=Z,Math.hypot(H.vx,H.vy)<N){$.current=null;return}$.current=requestAnimationFrame(G)};$.current=requestAnimationFrame(G)},[E]);C.useEffect(()=>()=>E(),[E]),C.useEffect(()=>{const T=r.current,D={onViewportPan:(R,G)=>{const H=t.current.applyPan(R,G);k.current.setViewport(H)},onTileMove:(R,G,P)=>{k.current.updateTile(R,{x:G,y:P})},onTileResize:(R,G)=>{k.current.updateTile(R,G)},onTileSelect:R=>{k.current.selectTile(R),k.current.bringToFront(R)},onSelectionBox:R=>{if(R){const G=e.current,P=G==null?void 0:G.getBoundingClientRect();m(P?{x:R.x-P.left,y:R.y-P.top,width:R.width,height:R.height}:R)}else m(null)},onBoxSelectEnd:()=>{},onTileClick:R=>{k.current.selectTile(R),k.current.bringToFront(R)},onCanvasClick:()=>{k.current.deselectAll()},onInteractionStart:()=>{E()},onPanInertiaStart:(R,G)=>{M(R,G)},getViewport:()=>w.current};return T.attach(D),()=>T.detach()},[]),C.useEffect(()=>{const T=e.current;if(!T)return;const D=t.current,R=H=>{const q=H.target,B=!!(q&&q.closest('.xterm, .xterm-screen, .xterm-viewport, input, textarea, [contenteditable="true"], [contenteditable=""]')),F=!!(q&&q.closest('[data-canvas-tile-focused="true"]')),Z=H.ctrlKey||H.metaKey;if((B||F)&&!Z&&!H.shiftKey)return;H.preventDefault();const J=T.getBoundingClientRect(),te=H.clientX-J.left,ne=H.clientY-J.top;if(Z){const ae=D.applyZoom(H.deltaY,te,ne);l(ae);return}let re=-H.deltaX,me=-H.deltaY;H.shiftKey&&re===0&&(re=-H.deltaY,me=0);const he=H.deltaMode===1?16:H.deltaMode===2?100:1,pe=D.applyPan(re*he,me*he);l(pe)},G=H=>{if(!(H.ctrlKey||H.metaKey))return;const q=H.target;if(q){const B=q.tagName;if(B==="INPUT"||B==="TEXTAREA"||B==="SELECT"||q.isContentEditable)return}if(H.key==="+"||H.key==="="||H.key==="-"||H.key==="_"||H.key==="0"){H.preventDefault();const B=T.clientWidth,F=T.clientHeight;if(H.key==="0")l(D.resetView());else if(H.key==="-"||H.key==="_"){const Z=D.applyZoom(120,B/2,F/2);l(Z)}else{const Z=D.applyZoom(-120,B/2,F/2);l(Z)}}},P=H=>{H.preventDefault()};return T.addEventListener("wheel",R,{passive:!1}),window.addEventListener("keydown",G),T.addEventListener("gesturestart",P),T.addEventListener("gesturechange",P),T.addEventListener("gestureend",P),()=>{T.removeEventListener("wheel",R),window.removeEventListener("keydown",G),T.removeEventListener("gesturestart",P),T.removeEventListener("gesturechange",P),T.removeEventListener("gestureend",P)}},[l]);const O=C.useCallback(T=>{const D=e.current;if(!D)return;const R=T.button===1||T.button===2,G=r.current.isSpacePressed,P=D.getBoundingClientRect(),H=T.clientX-P.left,q=T.clientY-P.top,B=r.current;let F=null,Z=null,J=null;if(!R&&!G){const he=[...Object.values(n)].sort((pe,ae)=>ae.zIndex-pe.zIndex);for(const pe of he){const ae=pe.x*s.zoom+s.panX,ye=pe.y*s.zoom+s.panY,be=pe.width*s.zoom,le=pe.height*s.zoom,_e={x:ae,y:ye,width:be,height:le},Te=B.getResizeHandle(_e,H,q,T0);if(Te){F=pe.id,Z=Te,J=pe.id;break}if(B.isInTileHeader(_e,H,q,s.zoom)){F=pe.id,J=pe.id;break}if(H>=ae&&H<=ae+be&&q>=ye&&q<=ye+le){J=pe.id;break}}}const te=T.target;if(!R&&!G&&Z===null&&J&&S.has(J)&&te&&te.closest(".xterm, .xterm-screen, .xterm-viewport, .xterm-rows"))return;const ne=T.target;if(ne&&!(R||G||Z!==null)&&(ne.closest("button")||ne.closest("input, textarea:not(.xterm-helper-textarea), select")||ne.closest('[contenteditable="true"], [contenteditable=""]')))return;if(R&&T.preventDefault(),!J&&!Z){const he=document.activeElement;he&&typeof he.blur=="function"&&he.blur(),u()}const me=T.nativeEvent;B.handlePointerDown(me,F,Z,n),J?(c(J),h(J)):(T.shiftKey||T.ctrlKey||T.metaKey)&&u(),D.setPointerCapture(T.pointerId),x(B.isSpacePressed)},[n,s,c,u,h,S]),z=C.useCallback(T=>{var R;const D=r.current;D.handlePointerMove(T.nativeEvent),x(D.isSpacePressed),b(D.isDragging),_(((R=D.currentDrag)==null?void 0:R.type)??null)},[]),U=C.useCallback(T=>{var G;const D=r.current;if(((G=D.currentDrag)==null?void 0:G.type)==="select"&&D.isDragging&&p){const P=s.zoom||1,H={x:(p.x-s.panX)/P,y:(p.y-s.panY)/P,width:p.width/P,height:p.height/P},q=D.getSelectedTileIds(H,n);d(q)}D.handlePointerUp(T.nativeEvent);const R=e.current;R&&R.releasePointerCapture(T.pointerId),b(!1),_(null),m(null)},[s,n,d,p]),I=f&&g==="pan"?"grabbing":v?"grab":"default";return i.jsxs("div",{ref:e,className:"absolute inset-0",style:{cursor:I,touchAction:"none",overscrollBehavior:"contain"},onPointerDown:O,onPointerMove:z,onPointerUp:U,onContextMenu:T=>T.preventDefault(),children:[i.jsx("div",{className:"absolute inset-0",style:{pointerEvents:"none"},children:y.map(T=>i.jsx(oL,{tile:T,viewport:s,isSelected:S.has(T.id)},T.id))}),p&&i.jsx(lL,{rect:p})]})}function C_(){const e=it(n=>n.tiles),{t}=de(),r=Object.keys(e).length>0;return i.jsxs("div",{className:"relative w-full h-full overflow-hidden bg-bg-primary",children:[i.jsx(cL,{}),i.jsx(nL,{}),!r&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:i.jsx("p",{className:"text-text-tertiary text-sm",children:t("canvas.empty")})})]})}const L0="/assets/dark-claw-cat-D_ew_BKV.png",D0="/assets/light-claw-cat-BgBWmnmi.png",M0="/assets/red-claw-cat--t2EuBIB.png",$0={small:{container:"w-20 h-20",text:"text-[12px]"},medium:{container:"w-32 h-32",text:"text-[14px]"},large:{container:"w-40 h-40",text:"text-[16px]"}};function O0({size:e="medium",className:t=""}){const n=Jt(a=>a.resolved)==="dark"?L0:D0,s=$0[e];return i.jsxs("div",{className:`relative ${s.container} ${t}`,children:[i.jsx("img",{src:n,alt:"",className:"cat-loading-layer cat-loading-layer-base absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"}),i.jsx("img",{src:M0,alt:"",className:"cat-loading-layer cat-loading-layer-color absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"})]})}function bn({size:e="medium",text:t="Loading...",className:r=""}){const n=$0[e];return i.jsxs("div",{className:`flex flex-col items-center justify-center gap-4 ${r}`,children:[i.jsx(O0,{size:e}),t&&i.jsx("div",{className:`text-text-secondary ${n.text} font-medium animate-pulse`,children:t})]})}function dL({size:e="medium",className:t=""}){return i.jsx(O0,{size:e,className:t})}function A_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function uL(e){if(Array.isArray(e))return e}function hL(e,t,r){return(t=_L(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pL(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,a,l,o=[],c=!0,d=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(c=(n=a.call(r)).done)&&(o.push(n.value),o.length!==t);c=!0);}catch(u){d=!0,s=u}finally{try{if(!c&&r.return!=null&&(l=r.return(),Object(l)!==l))return}finally{if(d)throw s}}return o}}function mL(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
836
836
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function E_(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function T_(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?E_(Object(r),!0).forEach(function(n){hL(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):E_(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function fL(e,t){if(e==null)return{};var r,n,s=gL(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n<a.length;n++)r=a[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(s[r]=e[r])}return s}function gL(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function bL(e,t){return uL(e)||pL(e,t)||xL(e,t)||mL()}function yL(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function _L(e){var t=yL(e,"string");return typeof t=="symbol"?t:t+""}function xL(e,t){if(e){if(typeof e=="string")return A_(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?A_(e,t):void 0}}function vL(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function I_(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function N_(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?I_(Object(r),!0).forEach(function(n){vL(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):I_(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function wL(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(n){return t.reduceRight(function(s,a){return a(s)},n)}}function pa(e){return function t(){for(var r=this,n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];return s.length>=e.length?e.apply(this,s):function(){for(var l=arguments.length,o=new Array(l),c=0;c<l;c++)o[c]=arguments[c];return t.apply(r,[].concat(s,o))}}}function pl(e){return{}.toString.call(e).includes("Object")}function SL(e){return!Object.keys(e).length}function Ia(e){return typeof e=="function"}function kL(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function CL(e,t){return pl(t)||us("changeType"),Object.keys(t).some(function(r){return!kL(e,r)})&&us("changeField"),t}function AL(e){Ia(e)||us("selectorType")}function EL(e){Ia(e)||pl(e)||us("handlerType"),pl(e)&&Object.values(e).some(function(t){return!Ia(t)})&&us("handlersType")}function TL(e){e||us("initialIsRequired"),pl(e)||us("initialType"),SL(e)&&us("initialContent")}function IL(e,t){throw new Error(e[t]||e.default)}var NL={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},us=pa(IL)(NL),vo={changes:CL,selector:AL,handler:EL,initial:TL};function RL(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};vo.initial(e),vo.handler(t);var r={current:e},n=pa(ML)(r,t),s=pa(DL)(r),a=pa(vo.changes)(e),l=pa(LL)(r);function o(){var d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(u){return u};return vo.selector(d),d(r.current)}function c(d){wL(n,s,a,l)(d)}return[o,c]}function LL(e,t){return Ia(t)?t(e.current):t}function DL(e,t){return e.current=N_(N_({},e.current),t),t}function ML(e,t,r){return Ia(t)?t(e.current):Object.keys(r).forEach(function(n){var s;return(s=t[n])===null||s===void 0?void 0:s.call(t,e.current[n])}),r}var $L={create:RL},OL={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function jL(e){return function t(){for(var r=this,n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];return s.length>=e.length?e.apply(this,s):function(){for(var l=arguments.length,o=new Array(l),c=0;c<l;c++)o[c]=arguments[c];return t.apply(r,[].concat(s,o))}}}function BL(e){return{}.toString.call(e).includes("Object")}function PL(e){return e||R_("configIsRequired"),BL(e)||R_("configType"),e.urls?(FL(),{paths:{vs:e.urls.monacoBase}}):e}function FL(){console.warn(j0.deprecation)}function zL(e,t){throw new Error(e[t]||e.default)}var j0={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
@@ -1027,7 +1027,7 @@ ${r("tool.moreLinesCount").replace("{count}",String(s.length-t))}`})]})}function
1027
1027
  `,children:n?i.jsx("div",{className:"flex flex-col items-center justify-center h-32",children:i.jsx(bn,{size:"small",text:e("docs.loading")})}):r?i.jsx(BF,{items:r,currentPath:s,onSelect:A}):i.jsx("div",{className:"p-4 text-sm text-text-tertiary",children:e("docs.loadError")})}),i.jsx("div",{className:"flex-1 min-w-0 overflow-hidden flex flex-col",children:j?i.jsx(jF,{query:c,results:d,onSelect:N}):l?i.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:i.jsx(bn,{size:"small",text:e("docs.loading")})}):o?i.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"📄"}),i.jsx("div",{className:"text-text-secondary text-sm mb-2",children:e("docs.notFound")}),i.jsx("div",{className:"text-text-tertiary text-xs",children:o})]})}):a?i.jsx(OF,{content:a,onNavigate:A}):i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-text-tertiary",children:[i.jsx("div",{className:"text-[48px] mb-4 opacity-30",children:"📖"}),i.jsx("div",{className:"text-sm",children:e("docs.title")})]})})]})]})}function Yx(e,t){const r=mt.getState().pendingReveal;if(!r||r.path!==t)return!1;mt.getState().setPendingReveal(null);const{line:n,col:s,query:a}=r,l=e.getModel();if(!l)return!1;const o=s&&s>0?s:1;if(e.revealLineInCenter(n),e.setPosition({lineNumber:n,column:o}),e.focus(),a){const c=l.findMatches(a,!1,!1,!1,null,!0);if(c.length>0){const d=c.find(p=>p.range.startLineNumber>=n)||c[0];e.setSelection(d.range),e.revealRangeInCenter(d.range);const u=c.map(p=>({range:p.range,options:{className:"search-find-match",overviewRuler:{color:"#d7ba7d",position:1}}})),h=e.deltaDecorations([],u);setTimeout(()=>{try{e.deltaDecorations(h,[])}catch{}},5e3)}}return!0}function u1({path:e,content:t,language:r,onContentChange:n,onSave:s,minimap:a=!0,onCursorChange:l}){const{t:o}=de(),{resolved:c}=Jt(),d=C.useRef(null),u=C.useRef(l);u.current=l;const h=c==="dark"?"cbc-dark":"cbc-light",p=C.useCallback((x,f)=>{d.current=x,f.editor.defineTheme("cbc-dark",{base:"vs-dark",inherit:!0,rules:[],colors:{"editor.background":"#121314"}}),f.editor.defineTheme("cbc-light",{base:"vs",inherit:!0,rules:[],colors:{"editor.background":"#ffffff"}}),f.editor.setTheme(h),x.addCommand(f.KeyMod.CtrlCmd|f.KeyCode.KeyS,()=>{s()});const b=()=>{const g=u.current;if(!g)return;const _=x.getPosition(),y=x.getSelection();if(!_)return;let S=0,w=0;if(y&&!y.isEmpty()){const k=x.getModel();k&&(S=k.getValueInRange(y).length,w=Math.abs(y.endLineNumber-y.startLineNumber)+1)}g(_.lineNumber,_.column,S,w)};x.onDidChangeCursorPosition(b),x.onDidChangeCursorSelection(b),b()},[s]),m=C.useCallback(x=>{x!==void 0&&n(x)},[n]);C.useEffect(()=>{const x=d.current;if(!x)return;const f=x.getModel();f&&t.length>0&&f.getValue()!==t&&f.setValue(t)},[t]);const v=mt(x=>x.pendingReveal);return C.useEffect(()=>{if(!v||v.path!==e)return;if(d.current){Yx(d.current,e);return}let x=0;const f=setInterval(()=>{x++,d.current?(Yx(d.current,e),clearInterval(f)):x>=50&&clearInterval(f)},50);return()=>clearInterval(f)},[e,v]),i.jsx(xD,{height:"100%",language:r,theme:h,defaultValue:t,onChange:m,onMount:p,loading:i.jsxs("div",{className:"flex items-center justify-center h-full gap-2",style:{color:"var(--color-text-tertiary)"},children:[i.jsx(He,{size:16,className:"animate-spin"}),i.jsx("span",{style:{fontSize:13},children:o("editor.loading")})]}),options:{fontSize:13,fontFamily:"'Menlo', 'Monaco', 'Consolas', 'Courier New', monospace",lineHeight:20,minimap:{enabled:a,maxColumn:80},scrollBeyondLastLine:!1,automaticLayout:!0,wordWrap:"off",tabSize:4,insertSpaces:!0,renderWhitespace:"selection",bracketPairColorization:{enabled:!0},padding:{top:8},smoothScrolling:!0,cursorBlinking:"smooth",cursorSmoothCaretAnimation:"on",fixedOverflowWidgets:!0}},e)}async function Fr(e,t){var l;const r=jl(),n={...t,...r?{cwd:r}:{}},s=await Ve(`/api/v1/git/${e}`,{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){const o=await s.json().catch(()=>({error:{message:s.statusText}}));throw new Error(((l=o.error)==null?void 0:l.message)||`Git API error: ${s.status}`)}const a=await s.json();return a.data??a}async function PF(){return Fr("status")}async function Zx(e){await Fr("stage",{paths:e})}async function Xx(e){await Fr("unstage",{paths:e})}async function FF(e){return Fr("commit",{message:e})}async function h1(e,t){return Fr("diff",{path:e,staged:t})}async function yd(e,t){await Fr("discard",{paths:e,useTrash:t})}async function zF(){return(await Fr("branches")).branches}async function UF(e){return Fr("branch/switch",{name:e})}async function HF(e,t=!0){return Fr("branch/create",{name:e,checkout:t})}async function GF(){return Fr("push")}async function WF(){return Fr("pull")}async function qF(e){return(await Fr("log",{limit:e})).entries}const QF=1e3,VF=2e3;let ca=null,da=null,Gr=null,_d=!1;async function KF(){try{const{authHeaders:e}=await cs(async()=>{const{authHeaders:n}=await Promise.resolve().then(()=>hC);return{authHeaders:n}},void 0),{fetchWithRetry:t}=await cs(async()=>{const{fetchWithRetry:n}=await Promise.resolve().then(()=>Lv);return{fetchWithRetry:n}},void 0),r=await t("/api/v1/info",{headers:e()});if(r.ok){const n=await r.json();return(n.data??n).cwd||void 0}}catch{}}const Bn=Ke((e,t)=>({isGitRepo:!1,loading:!1,error:null,files:[],currentBranch:null,ahead:0,behind:0,remote:null,branches:[],branchesLoading:!1,selectedFile:null,selectedFileStaged:!1,diffResult:null,diffLoading:!1,commitMessage:"",committing:!1,pushing:!1,pulling:!1,lastOperationMessage:null,refresh:async()=>{t().files.length===0&&!t().isGitRepo&&e({loading:!0,error:null});try{const n=await PF();e({isGitRepo:n.isGitRepo,files:n.files,currentBranch:n.branch,ahead:n.ahead,behind:n.behind,remote:n.remote,loading:!1})}catch(n){e({loading:!1,error:n.message})}},loadBranches:async()=>{e({branchesLoading:!0});try{const r=await zF();e({branches:r,branchesLoading:!1})}catch{e({branchesLoading:!1})}},stageFile:async r=>{await Zx([r]),await t().refresh()},unstageFile:async r=>{await Xx([r]),await t().refresh()},stageAll:async()=>{const r=t().files.filter(n=>!n.staged).map(n=>n.path);r.length>0&&(await Zx(r),await t().refresh())},unstageAll:async()=>{const r=t().files.filter(n=>n.staged).map(n=>n.path);r.length>0&&(await Xx(r),await t().refresh())},discardFile:async r=>{await yd([r],!0),await t().refresh()},discardAll:async()=>{const r=t().files.filter(a=>!a.staged),n=r.filter(a=>a.status!=="untracked"),s=r.filter(a=>a.status==="untracked");n.length>0?await yd(n.map(a=>a.path)):s.length>0&&await yd(s.map(a=>a.path),!0),await t().refresh()},commit:async()=>{const r=t().commitMessage.trim();if(r){e({committing:!0});try{const n=await FF(r);e({committing:!1,commitMessage:"",lastOperationMessage:n.success?"Committed successfully":n.message}),await t().refresh()}catch(n){e({committing:!1,lastOperationMessage:n.message})}}},push:async()=>{e({pushing:!0});try{const r=await GF();e({pushing:!1,lastOperationMessage:r.success?"Pushed successfully":r.message}),await t().refresh()}catch(r){e({pushing:!1,lastOperationMessage:r.message})}},pull:async()=>{e({pulling:!0});try{const r=await WF();e({pulling:!1,lastOperationMessage:r.success?"Pulled successfully":r.message}),await t().refresh()}catch(r){e({pulling:!1,lastOperationMessage:r.message})}},switchBranch:async r=>{try{const n=await UF(r);e({lastOperationMessage:n.success?`Switched to ${r}`:n.message}),await t().refresh()}catch(n){e({lastOperationMessage:n.message})}},createBranch:async r=>{try{const n=await HF(r);e({lastOperationMessage:n.success?`Created branch ${r}`:n.message}),await t().refresh(),await t().loadBranches()}catch(n){e({lastOperationMessage:n.message})}},selectFile:async(r,n)=>{if(t().selectedFile===r&&t().selectedFileStaged===n){e({selectedFile:null,diffResult:null,selectedFileStaged:!1});return}e({selectedFile:r,selectedFileStaged:n,diffLoading:!0,diffResult:null});try{const s=await h1(r,n);e({diffResult:s,diffLoading:!1})}catch{e({diffLoading:!1})}},clearSelection:()=>e({selectedFile:null,diffResult:null,selectedFileStaged:!1}),setCommitMessage:r=>e({commitMessage:r}),clearOperationMessage:()=>e({lastOperationMessage:null}),startWatching:async()=>{if(_d)return;let r=jl();if(r||(r=await KF()),!r)return;_d=!0;const n=()=>{t().loading||(Gr&&clearTimeout(Gr),Gr=setTimeout(()=>{Gr=null,t().refresh()},QF))},s=new Set(["index","HEAD","FETCH_HEAD","ORIG_HEAD","refs"]);ca=p_(`${r}/.git`,!1,a=>{var o;const l=(o=a.entry)==null?void 0:o.name;l&&s.has(l)&&n()},()=>{ca=null}),da=p_(r,!0,()=>{t().loading||(Gr&&clearTimeout(Gr),Gr=setTimeout(()=>{Gr=null,t().refresh()},VF))},()=>{da=null})},stopWatching:async()=>{_d=!1,ca&&(ca.close(),ca=null),da&&(da.close(),da=null),Gr&&(clearTimeout(Gr),Gr=null)}}));WR(async()=>{const e=Bn.getState();await e.stopWatching(),e.refresh(),await e.startWatching()});function p1({currentBranch:e,branches:t,branchesLoading:r,onSwitch:n,onCreate:s,onLoadBranches:a,actions:l,defaultOpen:o,onClose:c}){const{t:d}=de(),[u,h]=C.useState(o??!1),[p,m]=C.useState(""),[v,x]=C.useState(""),[f,b]=C.useState(0),[g,_]=C.useState(!1),y=C.useRef(null),S=C.useCallback(E=>{h(E),E||c==null||c()},[c]);C.useEffect(()=>{const E=setTimeout(()=>x(p),100);return()=>clearTimeout(E)},[p]),C.useEffect(()=>{u&&a()},[u,a]),C.useEffect(()=>{u?setTimeout(()=>{var E;return(E=y.current)==null?void 0:E.focus()},0):(m(""),x(""),b(0),_(!1))},[u]);const{localBranches:w,remoteBranches:k,flatList:A}=C.useMemo(()=>{let E;if(v){const U=[];for(const Q of t){const I=ka(v,Q.name);I.match&&U.push({...Q,_score:I.score})}U.sort((Q,I)=>I._score-Q._score),E=U}else E=t;const M=E.filter(U=>!U.isRemote),O=E.filter(U=>U.isRemote),z=[...M,...O];return{localBranches:M,remoteBranches:O,flatList:z}},[t,v]);C.useEffect(()=>{b(0)},[p]);const N=C.useCallback(E=>{E.key==="Escape"?S(!1):E.key==="ArrowDown"?(E.preventDefault(),b(M=>Math.min(M+1,A.length-1))):E.key==="ArrowUp"?(E.preventDefault(),b(M=>Math.max(M-1,0))):E.key==="Enter"&&(E.preventDefault(),g?p.trim()&&(s(p.trim()),S(!1)):A[f]?(n(A[f].name),S(!1)):p.trim()&&A.length===0&&(s(p.trim()),S(!1)))},[A,f,g,p,n,s]),j=C.useCallback(E=>{n(E),S(!1)},[n]),$=C.useCallback(()=>{_(!0),setTimeout(()=>{var E;return(E=y.current)==null?void 0:E.focus()},0)},[]),L=C.useCallback(()=>{p.trim()&&(s(p.trim()),S(!1))},[p,s]);return i.jsxs("div",{className:"branch-picker",children:[!o&&i.jsxs("div",{className:"branch-picker-header",children:[i.jsxs("button",{className:"branch-picker-trigger",onClick:()=>S(!u),title:e||"",children:[i.jsx(gs,{size:14,className:"branch-picker-icon"}),i.jsx("span",{className:"branch-picker-name",children:e||"No branch"})]}),l]}),u&&Ek.createPortal(i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"branch-picker-backdrop",onClick:()=>S(!1)}),i.jsxs("div",{className:"branch-picker-dropdown",onKeyDown:N,onMouseDown:E=>E.stopPropagation(),onClick:E=>E.stopPropagation(),children:[i.jsx("div",{className:"branch-picker-search",children:i.jsx("input",{ref:y,className:"branch-picker-input",type:"text",value:p,onChange:E=>m(E.target.value),placeholder:g?d("ide.scm.newBranchPlaceholder")||"New branch name...":d("ide.scm.branchSearchPlaceholder")||"Select a branch or tag to checkout"})}),!g&&i.jsx("div",{className:"branch-picker-actions",children:i.jsxs("button",{className:"branch-picker-action",onClick:$,children:[i.jsx(Ot,{size:14}),i.jsx("span",{children:d("ide.scm.createBranch")||"Create new branch..."})]})}),g&&i.jsx("div",{className:"branch-picker-actions",children:i.jsxs("button",{className:"branch-picker-action branch-picker-action-confirm",onClick:L,disabled:!p.trim(),children:[i.jsx(Ot,{size:14}),i.jsx("span",{children:p.trim()?`Create branch "${p.trim()}"`:d("ide.scm.newBranchPlaceholder")||"Type branch name..."})]})}),A.length>0&&i.jsx(YF,{flatList:A,localCount:w.length,remoteCount:k.length,currentBranch:e,highlightIdx:f,onSelect:j,onHover:b}),r&&A.length===0&&i.jsx("div",{className:"branch-picker-empty",children:"Loading..."}),!r&&A.length===0&&!g&&i.jsx("div",{className:"branch-picker-empty",children:v?d("ide.scm.noBranchMatch")||"No matching branches":d("ide.scm.noBranchMatch")||"No branches found"})]})]}),document.body)]})}const Cs=40,Mo=24;function YF({flatList:e,localCount:t,remoteCount:r,currentBranch:n,highlightIdx:s,onSelect:a,onHover:l}){const o=C.useRef(null),[c,d]=C.useState(0),[u,h]=C.useState(300);C.useEffect(()=>{const b=o.current;if(!b)return;const g=new ResizeObserver(_=>{for(const y of _)h(y.contentRect.height)});return g.observe(b),()=>g.disconnect()},[]),C.useEffect(()=>{const b=o.current;if(!b)return;const g=s*Cs;g<b.scrollTop?b.scrollTop=g:g+Cs>b.scrollTop+u&&(b.scrollTop=g+Cs-u)},[s,u]);const p=C.useCallback(b=>{d(b.target.scrollTop)},[]),m=e.length*Cs+(t>0&&r>0?Mo:0)+(r>0?Mo:0),v=Math.max(0,Math.floor(c/Cs)-2),x=Math.min(e.length,Math.ceil((c+u)/Cs)+2),f=[];t>0&&r>0&&v===0&&f.push(i.jsx("div",{className:"branch-picker-group-label",style:{height:Mo},children:"branches"},"label-local"));for(let b=v;b<x;b++){const g=e[b];g&&(b===t&&r>0&&f.push(i.jsx("div",{className:"branch-picker-group-label",style:{height:Mo},children:"remotes"},"label-remote")),f.push(i.jsx(ZF,{branch:g,isCurrent:g.name===n,isHighlighted:b===s,dataIdx:b,onSelect:a,onHover:()=>l(b)},g.name)))}return i.jsx("div",{ref:o,className:"branch-picker-list",onScroll:p,children:i.jsx("div",{style:{height:m,position:"relative"},children:i.jsx("div",{style:{position:"absolute",top:v*Cs,left:0,right:0},children:f})})})}function ZF({branch:e,isCurrent:t,isHighlighted:r,dataIdx:n,onSelect:s,onHover:a}){return i.jsxs("div",{className:`branch-picker-item ${r?"highlighted":""} ${t?"current":""}`,"data-idx":n,onClick:()=>s(e.name),onMouseEnter:a,title:e.lastCommitMessage?`${e.name}
1028
1028
  ${e.lastCommitAuthor} • ${e.lastCommitHash} • ${e.lastCommitMessage}`:e.name,children:[i.jsxs("div",{className:"branch-picker-item-main",children:[i.jsx(gs,{size:14,className:"branch-picker-item-icon"}),i.jsx("span",{className:"branch-picker-item-name",children:e.name}),e.lastCommitDate&&i.jsx("span",{className:"branch-picker-item-date",children:e.lastCommitDate}),t&&i.jsx(Fn,{size:14,className:"branch-picker-item-check"}),e.ahead||e.behind?i.jsxs("span",{className:"branch-picker-item-sync",children:[e.ahead?`↑${e.ahead}`:"",e.behind?`↓${e.behind}`:""]}):null]}),e.lastCommitMessage&&i.jsxs("div",{className:"branch-picker-item-detail",children:[i.jsx("span",{className:"branch-picker-item-author",children:e.lastCommitAuthor}),i.jsx("span",{className:"branch-picker-item-separator",children:"•"}),i.jsx("span",{className:"branch-picker-item-hash",children:e.lastCommitHash}),i.jsx("span",{className:"branch-picker-item-separator",children:"•"}),i.jsx("span",{className:"branch-picker-item-message",children:e.lastCommitMessage})]})]})}const Jx={image:"Image",svg:"SVG",markdown:"Markdown Preview",pdf:"PDF",binary:"Binary"};function m1({language:e,cursorLine:t,cursorColumn:r,selectedCount:n,selectedLines:s,viewMode:a="editor",imageInfo:l,zoom:o,extraRight:c}){const{t:d}=de();if(a==="image"||a==="svg")return i.jsxs("div",{className:"editor-statusbar",children:[i.jsxs("div",{className:"editor-statusbar-left",children:[i.jsx(xd,{}),l&&i.jsxs("span",{className:"editor-statusbar-item",children:[l.width," × ",l.height]})]}),i.jsxs("div",{className:"editor-statusbar-right",children:[o!=null&&i.jsxs("span",{className:"editor-statusbar-item",children:[Math.round(o*100),"%"]}),i.jsx("span",{className:"editor-statusbar-item",children:Jx[a]}),c]})]});if(a!=="editor")return i.jsxs("div",{className:"editor-statusbar",children:[i.jsx("div",{className:"editor-statusbar-left",children:i.jsx(xd,{})}),i.jsxs("div",{className:"editor-statusbar-right",children:[i.jsx("span",{className:"editor-statusbar-item",children:Jx[a]||a}),c]})]});const u=`Ln ${t}, Col ${r}`,h=n&&n>0?s&&s>1?` (${n} ${d("editor.selected")}, ${s} ${d("editor.lines")})`:` (${n} ${d("editor.selected")})`:"";return i.jsxs("div",{className:"editor-statusbar",children:[i.jsxs("div",{className:"editor-statusbar-left",children:[i.jsx(xd,{}),i.jsxs("span",{className:"editor-statusbar-item",children:[u,h]})]}),i.jsxs("div",{className:"editor-statusbar-right",children:[i.jsx("span",{className:"editor-statusbar-item",children:e}),i.jsx("span",{className:"editor-statusbar-item",children:"UTF-8"}),i.jsx("span",{className:"editor-statusbar-item",children:"LF"}),i.jsx("span",{className:"editor-statusbar-item",children:"Spaces: 4"}),c]})]})}function xd(){const{currentBranch:e,branches:t,branchesLoading:r,isGitRepo:n,switchBranch:s,createBranch:a,loadBranches:l,refresh:o}=Bn(),[c,d]=C.useState(!1);C.useEffect(()=>{o()},[o]);const u=C.useCallback(p=>{s(p),d(!1)},[s]),h=C.useCallback(p=>{a(p),d(!1)},[a]);return n?i.jsxs("span",{className:"editor-statusbar-branch",onClick:p=>{p.stopPropagation(),d(m=>!m)},onPointerDown:p=>p.stopPropagation(),onMouseDown:p=>p.stopPropagation(),children:[i.jsx(gs,{size:12}),i.jsx("span",{children:e||"No branch"}),c&&i.jsx(p1,{currentBranch:e,branches:t,branchesLoading:r,onSwitch:u,onCreate:h,onLoadBranches:l,defaultOpen:!0,onClose:()=>d(!1)})]}):null}function f1({actions:e}={}){const{t}=de(),{tabs:r,activeTabId:n,rootPath:s,setActiveTab:a,closeTab:l,closeOtherTabs:o,closeAllTabs:c,closeTabsToRight:d,closeSavedTabs:u,reorderTabs:h,pinTab:p,unpinTab:m}=mt(),[v,x]=C.useState(null),f=C.useRef(null),[b,g]=C.useState(null),_=C.useRef(-1),y=C.useRef(null),[S,w]=C.useState(!1),[k,A]=C.useState(!1),N=C.useMemo(()=>GR(r),[r]),j=C.useCallback(()=>{const P=y.current;P&&(w(P.scrollLeft>0),A(P.scrollLeft+P.clientWidth<P.scrollWidth-1))},[]);C.useEffect(()=>{const P=y.current;if(!P)return;j(),P.addEventListener("scroll",j,{passive:!0});const H=new ResizeObserver(j);return H.observe(P),()=>{P.removeEventListener("scroll",j),H.disconnect()}},[j,r.length]),C.useEffect(()=>{if(!n||!y.current)return;const H=y.current.querySelector(".editor-tab.active");H&&H.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})},[n]);const $=C.useCallback(()=>{var P;(P=y.current)==null||P.scrollBy({left:-150,behavior:"smooth"})},[]),L=C.useCallback(()=>{var P;(P=y.current)==null||P.scrollBy({left:150,behavior:"smooth"})},[]),E=C.useCallback((P,H)=>{P.preventDefault(),x({x:P.clientX,y:P.clientY,tabId:H})},[]),M=C.useCallback(()=>{x(null)},[]),O=C.useCallback((P,H)=>{P.button===1&&(P.preventDefault(),l(H))},[l]),z=C.useCallback((P,H)=>{_.current=H,P.dataTransfer.effectAllowed="move",P.currentTarget instanceof HTMLElement&&P.dataTransfer.setDragImage(P.currentTarget,0,0)},[]),U=C.useCallback((P,H)=>{P.preventDefault(),P.dataTransfer.dropEffect="move",g(H)},[]),Q=C.useCallback((P,H)=>{P.preventDefault();const q=_.current;q>=0&&q!==H&&h(q,H),_.current=-1,g(null)},[h]),I=C.useCallback(()=>{_.current=-1,g(null)},[]),T=C.useCallback(P=>{const H=r.find(q=>q.id===P);H&&navigator.clipboard.writeText(H.path),M()},[r,M]),D=C.useCallback(P=>{const H=r.find(q=>q.id===P);if(H&&s){const q=H.path.startsWith(s+"/")?H.path.slice(s.length+1):H.path;navigator.clipboard.writeText(q)}else H&&navigator.clipboard.writeText(H.path);M()},[r,s,M]),R=C.useCallback(P=>{const H=r.find(q=>q.id===P);if(H){const{selectPath:q,toggleExpand:B,expandedPaths:F}=mt.getState(),Z=H.path.split("/");for(let J=1;J<Z.length;J++){const te=Z.slice(0,J).join("/");te&&!F.has(te)&&B(te)}q(H.path)}M()},[r,M]);if(r.length===0)return null;const G=v?r.find(P=>P.id===v.tabId):null;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"editor-tabs-wrapper",children:[S&&i.jsx("button",{className:"editor-tabs-scroll-btn",onClick:$,children:i.jsx(zC,{size:14})}),i.jsx("div",{className:"editor-tabs",ref:y,children:r.map((P,H)=>i.jsxs("div",{className:`editor-tab${P.id===n?" active":""}${b===H?" drag-indicator":""}`,onClick:()=>a(P.id),onMouseDown:q=>O(q,P.id),onContextMenu:q=>E(q,P.id),title:P.path,draggable:!0,onDragStart:q=>z(q,H),onDragOver:q=>U(q,H),onDrop:q=>Q(q,H),onDragEnd:I,children:[i.jsx(yn,{name:P.name,type:"file",size:14}),i.jsx("span",{className:"editor-tab-name",children:P.name}),N.get(P.id)&&i.jsx("span",{className:"editor-tab-description",children:N.get(P.id)}),P.isPinned?P.isDirty?i.jsx("span",{className:"dirty-dot"}):i.jsx("span",{className:"pin-icon",children:i.jsx($E,{size:14})}):P.isDirty?i.jsx("span",{className:"dirty-dot"}):i.jsx("button",{className:"close-btn",onClick:q=>{q.stopPropagation(),l(P.id)},children:i.jsx(at,{size:12})})]},P.id))}),k&&i.jsx("button",{className:"editor-tabs-scroll-btn",onClick:L,children:i.jsx(We,{size:14})}),e&&i.jsx("div",{className:"editor-tabs-actions",children:e})]}),v&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"editor-context-overlay",onClick:M}),i.jsxs("div",{ref:f,className:"editor-context-menu",style:{left:v.x,top:v.y},children:[G!=null&&G.isPinned?i.jsx("button",{onClick:()=>{m(v.tabId),M()},children:t("editor.unpin")}):i.jsx("button",{onClick:()=>{p(v.tabId),M()},children:t("editor.pin")}),i.jsx("div",{className:"editor-context-separator"}),i.jsx("button",{onClick:()=>T(v.tabId),children:t("editor.copyPath")}),i.jsx("button",{onClick:()=>D(v.tabId),children:t("editor.copyRelativePath")}),i.jsx("button",{onClick:()=>R(v.tabId),children:t("editor.revealInExplorer")}),i.jsx("div",{className:"editor-context-separator"}),i.jsx("button",{onClick:()=>{l(v.tabId),M()},children:t("editor.close")}),i.jsx("button",{onClick:()=>{o(v.tabId),M()},children:t("editor.closeOthers")}),i.jsx("button",{onClick:()=>{d(v.tabId),M()},children:t("editor.closeToRight")}),i.jsx("button",{onClick:()=>{u(),M()},children:t("editor.closeSaved")}),i.jsx("button",{onClick:()=>{c(),M()},children:t("editor.closeAll")})]})]})]})}const XF=qi;function Yb(e){return`/api/v1/files/download?path=${encodeURIComponent(e)}`}function ev({path:e,onImageInfo:t,onZoomChange:r}){const{t:n}=de(),s=C.useRef(null),a=C.useRef(null),[l,o]=C.useState("fit"),c=zl(Yb(e)),[d,u]=C.useState(null),[h,p]=C.useState(!1),[m,v]=C.useState({x:0,y:0}),x=C.useRef({x:0,y:0,tx:0,ty:0}),f=C.useCallback(()=>{if(!s.current||!d)return 1;const L=s.current.clientWidth-40,E=s.current.clientHeight-80;return L<=0||E<=0?1:Math.min(L/d.w,E/d.h,1)},[d]),b=l==="fit"?f():l,g=C.useCallback(()=>{const L=a.current;if(!L)return;const E=L.naturalWidth,M=L.naturalHeight;u({w:E,h:M}),t==null||t({width:E,height:M})},[t]);C.useEffect(()=>{r==null||r(b)},[b,r]);const _=C.useCallback(L=>{!L.ctrlKey&&!L.metaKey||(L.preventDefault(),o(E=>{const M=E==="fit"?f():E,O=L.deltaY<0?.1:-.1;return Math.min(5,Math.max(.1,M+O))}))},[f]),y=C.useCallback(L=>{l!=="fit"&&(L.preventDefault(),p(!0),x.current={x:L.clientX,y:L.clientY,tx:m.x,ty:m.y})},[l,m]),S=C.useCallback(L=>{if(!h)return;const E=L.clientX-x.current.x,M=L.clientY-x.current.y;v({x:x.current.tx+E,y:x.current.ty+M})},[h]),w=C.useCallback(()=>{p(!1)},[]),k=()=>o(L=>Math.min(5,(L==="fit"?f():L)+.1)),A=()=>o(L=>Math.max(.1,(L==="fit"?f():L)-.1)),N=()=>{o("fit"),v({x:0,y:0})},j=()=>{o(1),v({x:0,y:0})},$=b>=3;return i.jsxs("div",{ref:s,className:"file-preview-image-container checkerboard",onWheel:_,onMouseDown:y,onMouseMove:S,onMouseUp:w,onMouseLeave:w,style:{cursor:l!=="fit"?h?"grabbing":"grab":"default"},children:[c&&i.jsx("img",{ref:a,src:c,alt:e,onLoad:g,className:$?"pixelated":"",style:{transform:`translate(${m.x}px, ${m.y}px) scale(${b})`,transformOrigin:"center center",maxWidth:"none",maxHeight:"none",userSelect:"none",pointerEvents:"none"},draggable:!1}),i.jsxs("div",{className:"image-zoom-toolbar",children:[i.jsx("button",{onClick:A,title:n("filePreview.zoomOut"),children:i.jsx(Pa,{size:16})}),i.jsxs("span",{className:"image-zoom-label",children:[Math.round(b*100),"%"]}),i.jsx("button",{onClick:k,title:n("filePreview.zoomIn"),children:i.jsx(Ot,{size:16})}),i.jsx("button",{onClick:N,title:n("filePreview.fitToWindow"),children:i.jsx(Ba,{size:16})}),i.jsx("button",{onClick:j,title:n("filePreview.actualSize"),children:i.jsx(e2,{size:16})})]})]})}function JF({className:e,children:t}){const r=Jt(a=>a.resolved),n=(e||"").match(/language-(\w+)/),s=String(t).replace(/\n$/,"");return n?i.jsx("div",{className:"relative group my-3",children:i.jsx(XF,{style:r==="dark"?Ka:Ya,language:n[1],PreTag:"div",customStyle:{margin:0,borderRadius:"8px",fontSize:"13px",lineHeight:"1.6"},codeTagProps:{style:{background:"transparent",textShadow:"none"}},children:s})}):i.jsx("code",{className:"bg-[var(--color-bg-tertiary)] px-1.5 py-0.5 rounded text-[13px]",children:t})}function e8({content:e}){return i.jsx("div",{className:"file-preview-markdown",children:i.jsx("div",{className:"file-preview-markdown-content",children:i.jsx(Us,{remarkPlugins:[Hs],components:{code:JF},children:e})})})}function t8({path:e}){const{t}=de(),r=zl(Yb(e));return r?i.jsx("iframe",{src:r,className:"file-preview-pdf",title:t("filePreview.pdfPreview")}):null}function r8({path:e,name:t}){const{t:r}=de(),n=C.useCallback(()=>{fetch(Yb(e),{headers:ve()}).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.blob()}).then(s=>{const a=URL.createObjectURL(s),l=document.createElement("a");l.href=a,l.download=t,l.click(),URL.revokeObjectURL(a)}).catch(s=>{console.warn("[FilePreview] download failed:",String(s))})},[e,t]);return i.jsxs("div",{className:"file-preview-binary",children:[i.jsx(Fv,{size:48,className:"text-[var(--color-text-tertiary)]"}),i.jsx("div",{className:"mt-4 text-lg font-medium text-[var(--color-text-primary)]",children:t}),i.jsx("div",{className:"mt-2 text-sm text-[var(--color-text-secondary)]",children:r("filePreview.binaryNotSupported")}),i.jsxs("button",{onClick:n,className:"mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--color-bg-tertiary)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-quaternary)] transition-colors text-sm",children:[i.jsx(Bv,{size:16}),r("filePreview.download")]})]})}function g1({path:e,name:t,content:r,viewMode:n,onImageInfo:s,onZoomChange:a}){switch(n){case"image":return i.jsx(ev,{path:e,onImageInfo:s,onZoomChange:a});case"svg":return i.jsx(ev,{path:e,onImageInfo:s,onZoomChange:a});case"markdown":return i.jsx(e8,{content:r});case"pdf":return i.jsx(t8,{path:e});case"binary":return i.jsx(r8,{path:e,name:t});default:return null}}function b1({node:e,depth:t,isExpanded:r,isSelected:n,isMultiSelected:s,isRenaming:a,expandedPaths:l,selectedPath:o,selectedPaths:c,renamingPath:d,onToggleExpand:u,onSelect:h,onOpenFile:p,onConfirmRename:m,onCancelRename:v,onContextMenu:x,onDragStart:f,onDrop:b}){var D;const g=e.type==="directory",_=12+t*12,[y,S]=C.useState(e.name),w=C.useRef(null),[k,A]=C.useState(!1);C.useEffect(()=>{if(a&&w.current){S(e.name),w.current.focus();const R=e.name.lastIndexOf(".");!g&&R>0?w.current.setSelectionRange(0,R):w.current.select()}},[a,e.name,g]);const N=C.useCallback(R=>{a||(h(e.path,{ctrl:R.ctrlKey||R.metaKey,shift:R.shiftKey}),g?u(e.path):!R.ctrlKey&&!R.metaKey&&!R.shiftKey&&p(e.path,e.name))},[a,e.path,g,e.name,h,u,p]),j=C.useCallback(()=>{a||g||p(e.path,e.name)},[a,g,e.path,e.name,p]),$=C.useCallback(R=>{R.stopPropagation(),R.key==="Enter"?(R.preventDefault(),m(e.path,y)):R.key==="Escape"&&(R.preventDefault(),v())},[e.path,y,m,v]),L=C.useCallback(()=>{m(e.path,y)},[e.path,y,m]),E=C.useCallback(R=>{R.preventDefault(),x(R,e.path)},[x,e.path]),M=C.useCallback(R=>{const G=s?[...c]:[e.path];R.dataTransfer.effectAllowed="copyMove",R.dataTransfer.setData("text/plain",JSON.stringify(G)),R.dataTransfer.setData("application/x-file-paths",JSON.stringify(G)),f(G)},[s,c,e.path,f]),O=C.useCallback(R=>{g&&(R.preventDefault(),R.dataTransfer.dropEffect="move",A(!0))},[g]),z=C.useCallback(()=>{A(!1)},[]),U=C.useCallback(R=>{R.preventDefault(),A(!1),g&&b(e.path)},[g,e.path,b]),Q=n||s,I=12,T=12;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`file-tree-item ${Q?"selected":""} ${k?"drag-over":""}`,onClick:N,onDoubleClick:j,onContextMenu:E,draggable:!a,onDragStart:M,onDragOver:O,onDragLeave:z,onDrop:U,"data-path":e.path,title:e.path,children:[Array.from({length:t},(R,G)=>i.jsx("span",{className:"file-tree-indent-guide",style:{left:T+G*I+6}},G)),i.jsx("span",{style:{width:_,flexShrink:0}}),g?e.isLoading?i.jsx(He,{size:16,className:"file-tree-chevron animate-spin"}):i.jsx(We,{size:16,className:`file-tree-chevron ${r?"expanded":""}`}):i.jsx(yn,{name:e.name,type:e.type,isExpanded:r,size:16}),a?i.jsx("input",{ref:w,className:"file-tree-rename-input",value:y,onChange:R=>S(R.target.value),onKeyDown:$,onBlur:L,onClick:R=>R.stopPropagation()}):i.jsx("span",{className:"file-tree-item-name",children:e.name})]}),g&&r&&((D=e.children)==null?void 0:D.map(R=>i.jsx(b1,{node:R,depth:t+1,isExpanded:l.has(R.path),isSelected:o===R.path,isMultiSelected:c.has(R.path),isRenaming:d===R.path,expandedPaths:l,selectedPath:o,selectedPaths:c,renamingPath:d,onToggleExpand:u,onSelect:h,onOpenFile:p,onConfirmRename:m,onCancelRename:v,onContextMenu:x,onDragStart:f,onDrop:b},R.path)))]})}function n8({initialPath:e,onSelect:t,onClose:r}){const{t:n}=de(),[s,a]=C.useState(e||"/"),[l,o]=C.useState([]),[c,d]=C.useState(!0),[u,h]=C.useState(null),[p,m]=C.useState(!1),v=C.useRef(null),x=C.useCallback(async y=>{d(!0),h(null);try{const w=(await ds(y,1)).filter(k=>k.type==="directory").sort((k,A)=>k.name.localeCompare(A.name,void 0,{numeric:!0,sensitivity:"base"}));o(w),a(y)}catch{const S=y.replace(/\/[^/]+\/?$/,"")||"/";if(S!==y&&S.length>0)try{const k=(await ds(S,1)).filter(A=>A.type==="directory").sort((A,N)=>A.name.localeCompare(N.name,void 0,{numeric:!0,sensitivity:"base"}));o(k),a(S),d(!1);return}catch{}h(n("editor.loadError"))}finally{d(!1)}},[n]);C.useEffect(()=>{x(s)},[]);const f=C.useCallback(()=>{const y=s.replace(/\/[^/]+\/?$/,"")||"/";x(y)},[s,x]),b=C.useCallback(y=>{x(y)},[x]),g=C.useCallback(()=>{t(s)},[s,t]),_=C.useCallback(y=>{const S=y.trim();S&&x(S),m(!1)},[x]);return C.useEffect(()=>{p&&v.current&&(v.current.focus(),v.current.select())},[p]),C.useEffect(()=>{const y=S=>{S.key==="Escape"&&r()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[r]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-50 bg-black/40",onClick:r}),i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",onClick:y=>y.target===y.currentTarget&&r(),children:i.jsxs("div",{className:"bg-bg-primary border border-border-default rounded-xl shadow-xl flex flex-col",style:{width:"480px",maxWidth:"90vw",maxHeight:"70vh"},children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border-muted/30",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:n("editor.openFolder")}),i.jsx("button",{className:"text-text-tertiary hover:text-text-primary",onClick:r,children:i.jsx(at,{size:16})})]}),i.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-border-muted/30",children:[i.jsx("button",{className:"p-1 rounded hover:bg-bg-hover text-text-tertiary hover:text-text-primary flex-shrink-0",onClick:f,title:n("editor.parentFolder"),children:i.jsx(Jo,{size:14})}),p?i.jsx("input",{ref:v,type:"text",defaultValue:s,className:"flex-1 px-1.5 py-0.5 text-xs font-mono bg-bg-secondary border border-accent-brand rounded outline-none",onKeyDown:y=>{y.key==="Enter"&&_(y.target.value),y.key==="Escape"&&m(!1)},onBlur:y=>_(y.target.value)}):i.jsx("button",{className:"flex-1 text-left text-xs font-mono text-text-secondary truncate px-1.5 py-0.5 rounded hover:bg-bg-hover",onClick:()=>m(!0),title:s,children:s})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto min-h-[200px]",children:[c&&i.jsx("div",{className:"flex items-center justify-center py-8 text-text-tertiary",children:i.jsx(He,{size:16,className:"animate-spin"})}),u&&i.jsx("div",{className:"px-4 py-3 text-xs text-accent-red",children:u}),!c&&!u&&l.length===0&&i.jsx("div",{className:"px-4 py-8 text-center text-xs text-text-tertiary",children:n("editor.emptyFolder")}),!c&&!u&&l.map(y=>i.jsxs("button",{className:"flex items-center gap-2 w-full px-4 py-1.5 text-left text-sm text-text-primary hover:bg-bg-hover/50 cursor-pointer",onClick:()=>b(y.path),children:[i.jsx(Hu,{size:14,className:"text-text-tertiary flex-shrink-0"}),i.jsx("span",{className:"truncate",children:y.name}),i.jsx(We,{size:12,className:"text-text-tertiary flex-shrink-0 ml-auto"})]},y.path))]}),i.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-3 border-t border-border-muted/30",children:[i.jsx("button",{className:"px-3 py-1.5 text-xs rounded-md text-text-secondary hover:bg-bg-hover border border-border-muted",onClick:r,children:n("editor.close")}),i.jsx("button",{className:"px-3 py-1.5 text-xs rounded-md bg-accent-brand text-accent-brand-foreground hover:opacity-90",onClick:g,children:n("editor.openFolder")})]})]})})]})}function y1(e){var ae,ye,be;const{t}=de(),r=Or(le=>le.info),{rootPath:n,tree:s,treeLoading:a,treeError:l,expandedPaths:o,selectedPath:c,selectedPaths:d,renamingPath:u,setRootPath:h,toggleExpand:p,selectPath:m,openFile:v,refreshTree:x,collapseAll:f,createNewFile:b,createNewFolder:g,startRename:_,startCreateFile:y,startCreateFolder:S,confirmRename:w,cancelRename:k,deleteSelected:A,moveToDirectory:N}=mt(),[j,$]=C.useState(!1),[L,E]=C.useState(!1),[M,O]=C.useState(!1),z=C.useRef(null),[U,Q]=C.useState(null),I=C.useRef([]);C.useEffect(()=>{const le=hl().has("path");r!=null&&r.cwd&&!n&&!le?h(r.cwd):n&&!s&&!a&&!l&&h(n)},[r==null?void 0:r.cwd,n,s,a,l,h]);const T=C.useCallback(le=>{O(!1),h(le)},[h]),D=C.useCallback((le,_e)=>{v(le,_e)},[v]),R=C.useCallback((le,_e)=>{w(le,_e)},[w]),G=C.useCallback((le,_e)=>{le.preventDefault(),d.has(_e)||m(_e),Q({x:le.clientX,y:le.clientY,path:_e})},[d,m]),P=C.useCallback(()=>Q(null),[]),H=C.useCallback(()=>{U&&(_(U.path),Q(null))},[U,_]),q=C.useCallback(()=>{Q(null),A()},[A]),B=C.useCallback((le,_e)=>{if(!le)return null;if(le.path===_e)return le;if(le.children)for(const Te of le.children){const $e=B(Te,_e);if($e)return $e}return null},[]),F=U?((ae=B(s,U.path))==null?void 0:ae.type)==="directory":!1,Z=C.useCallback(()=>{if(U){const le=B(s,U.path),_e=(le==null?void 0:le.type)==="directory"?U.path:U.path.substring(0,U.path.lastIndexOf("/"));if(_e){o.has(_e)||p(_e);const Te=_e+"/__new_file__";y(Te)}Q(null)}},[U,s,o,p,y,B]),J=C.useCallback(()=>{if(U){const le=B(s,U.path),_e=(le==null?void 0:le.type)==="directory"?U.path:U.path.substring(0,U.path.lastIndexOf("/"));if(_e){o.has(_e)||p(_e);const Te=_e+"/__new_folder__";S(Te)}Q(null)}},[U,s,o,p,S,B]),te=C.useCallback(()=>{U&&(navigator.clipboard.writeText(U.path).catch(()=>{}),Q(null))},[U]),ne=C.useCallback(()=>{if(U&&n){const le=U.path.startsWith(n+"/")?U.path.slice(n.length+1):U.path;navigator.clipboard.writeText(le).catch(()=>{}),Q(null)}},[U,n]),re=C.useCallback(le=>{I.current=le},[]),me=C.useCallback(le=>{I.current.length>0&&(N(I.current,le),I.current=[])},[N]),he=C.useCallback(le=>{var $e,Ze,ce,Ce;if(u||!s)return;const _e=sh(s,o);if(_e.length===0)return;const Te=c?_e.indexOf(c):-1;switch(le.key){case"ArrowDown":{le.preventDefault();const Le=Te<_e.length-1?Te+1:0;m(_e[Le],{shift:le.shiftKey}),(Ze=($e=z.current)==null?void 0:$e.querySelector(`[data-path="${CSS.escape(_e[Le])}"]`))==null||Ze.scrollIntoView({block:"nearest"});break}case"ArrowUp":{le.preventDefault();const Le=Te>0?Te-1:_e.length-1;m(_e[Le],{shift:le.shiftKey}),(Ce=(ce=z.current)==null?void 0:ce.querySelector(`[data-path="${CSS.escape(_e[Le])}"]`))==null||Ce.scrollIntoView({block:"nearest"});break}case"ArrowRight":{le.preventDefault(),c&&!o.has(c)&&p(c);break}case"ArrowLeft":{le.preventDefault(),c&&o.has(c)&&p(c);break}case"Enter":{le.preventDefault(),c&&_(c);break}case"Delete":case"Backspace":{le.preventDefault(),d.size>0&&A();break}case" ":{if(le.preventDefault(),c){const Le=jt=>{if(!jt)return null;if(jt.path===c)return jt;if(jt.children)for(const Qt of jt.children){const xe=Le(Qt);if(xe)return xe}return null},lt=Le(s);(lt==null?void 0:lt.type)==="directory"?p(c):lt&&v(lt.path,lt.name)}break}}},[s,o,c,d,u,m,p,_,v,A]),pe=(s==null?void 0:s.name)||(n==null?void 0:n.split("/").pop())||"WORKSPACE";return i.jsxs("div",{className:"file-tree",ref:z,tabIndex:0,onKeyDown:he,onClick:()=>{var le;return(le=z.current)==null?void 0:le.focus()},children:[i.jsx("div",{className:"file-tree-title-bar",children:i.jsx("span",{className:"file-tree-title-text",children:t("editor.explorer")})}),i.jsxs("div",{className:"file-tree-section-header",onClick:()=>$(!j),onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),children:[j?i.jsx(We,{size:12,style:{flexShrink:0}}):i.jsx(rt,{size:12,style:{flexShrink:0}}),i.jsx("span",{className:"file-tree-section-name",children:pe.toUpperCase()}),L&&!j&&i.jsxs("div",{className:"file-tree-section-actions",onClick:le=>le.stopPropagation(),children:[i.jsx("button",{className:"file-tree-section-action",onClick:b,title:t("editor.newFile"),children:i.jsx(AA,{size:14})}),i.jsx("button",{className:"file-tree-section-action",onClick:g,title:t("editor.newFolder"),children:i.jsx(OA,{size:14})}),i.jsx("button",{className:"file-tree-section-action",onClick:()=>O(!0),title:t("editor.openFolder"),children:i.jsx(Uu,{size:14})}),i.jsx("button",{className:"file-tree-section-action",onClick:x,title:t("editor.refresh"),children:i.jsx(St,{size:14})}),i.jsx("button",{className:"file-tree-section-action",onClick:f,title:t("editor.collapseAll"),children:i.jsx(gA,{size:14})})]})]}),M&&i.jsx(n8,{initialPath:n||(r==null?void 0:r.cwd)||"/",onSelect:T,onClose:()=>O(!1)}),!j&&i.jsxs("div",{className:"file-tree-content",children:[a&&!s&&i.jsx("div",{className:"file-tree-loading",children:i.jsx(He,{size:16,className:"animate-spin"})}),!a&&!s&&l&&n&&i.jsxs("div",{className:"file-tree-empty",children:[i.jsx("span",{children:t("editor.loadError")}),i.jsxs("button",{className:"file-tree-retry-btn",onClick:()=>h(n),children:[i.jsx(St,{size:12}),t("editor.refresh")]}),(r==null?void 0:r.cwd)&&n!==r.cwd&&i.jsxs("button",{className:"file-tree-retry-btn",onClick:()=>h(r.cwd),children:[i.jsx(qA,{size:12}),t("editor.backToWorkDir")]})]}),(ye=s==null?void 0:s.children)==null?void 0:ye.map(le=>i.jsx(b1,{node:le,depth:0,isExpanded:o.has(le.path),isSelected:c===le.path,isMultiSelected:d.has(le.path),isRenaming:u===le.path,expandedPaths:o,selectedPath:c,selectedPaths:d,renamingPath:u,onToggleExpand:p,onSelect:m,onOpenFile:D,onConfirmRename:R,onCancelRename:k,onContextMenu:G,onDragStart:re,onDrop:me},le.path)),((be=s==null?void 0:s.children)==null?void 0:be.length)===0&&i.jsx("div",{className:"file-tree-empty",children:t("editor.emptyFolder")})]}),U&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"editor-context-overlay",onClick:P}),i.jsxs("div",{className:"editor-context-menu",style:{left:U.x,top:U.y},children:[F&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:Z,children:t("editor.newFile")}),i.jsx("button",{onClick:J,children:t("editor.newFolder")}),i.jsx("div",{className:"editor-context-separator"})]}),i.jsx("button",{onClick:te,children:t("editor.copyPath")}),i.jsx("button",{onClick:ne,children:t("editor.copyRelativePath")}),i.jsx("div",{className:"editor-context-separator"}),d.size<=1&&i.jsx("button",{onClick:H,children:t("editor.rename")}),i.jsx("button",{className:"danger",onClick:q,children:d.size>1?`${t("editor.delete")} (${d.size})`:t("editor.delete")})]})]})]})}function s8(e,t){fetch(`/api/v1/pty/${e}/input/send`,{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({data:t})}).catch(()=>{})}function i8(e){return/^[a-zA-Z0-9_./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function _1(){const{t:e}=de(),{bottomTerminals:t,activeBottomTerminalId:r,bottomPanelMaximized:n,createBottomTerminal:s,closeBottomTerminal:a,closeOtherBottomTerminals:l,closeBottomTerminalsToRight:o,closeAllBottomTerminals:c,setActiveBottomTerminal:d,setBottomPanelCollapsed:u,toggleBottomPanelMaximize:h}=yt(),p=Ei(E=>E.cwd),[m,v]=C.useState(null),x=C.useCallback((E,M)=>{E.preventDefault(),v({x:E.clientX,y:E.clientY,tabId:M})},[]),f=C.useCallback(()=>{v(null)},[]),b=De(E=>E.panes),g=C.useRef(null);C.useEffect(()=>{const E=setTimeout(()=>{window.dispatchEvent(new Event("resize"))},60);return()=>clearTimeout(E)},[]),C.useEffect(()=>{if(!r||!g.current)return;const M=g.current.querySelector(".ide-bottom-tab.active");M&&M.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})},[r]);const _=C.useCallback(()=>{s()},[s]),y=C.useCallback((E,M)=>{E.stopPropagation(),a(M)},[a]),S=C.useCallback(()=>{u(!0)},[u]),[w,k]=C.useState(!1),A={current:0},N=C.useCallback(E=>{E.preventDefault(),E.stopPropagation(),A.current++,(E.dataTransfer.types.includes("text/plain")||E.dataTransfer.types.includes("application/x-file-paths"))&&k(!0)},[]),j=C.useCallback(E=>{E.preventDefault(),E.stopPropagation(),E.dataTransfer.dropEffect="copy"},[]),$=C.useCallback(E=>{E.preventDefault(),E.stopPropagation(),A.current--,A.current<=0&&(A.current=0,k(!1))},[]),L=C.useCallback(E=>{E.preventDefault(),E.stopPropagation(),k(!1),A.current=0;let M=[];const O=E.dataTransfer.getData("application/x-file-paths")||E.dataTransfer.getData("text/plain");if(O)try{const I=JSON.parse(O);Array.isArray(I)&&(M=I)}catch{M=[O]}if(M.length===0&&E.dataTransfer.files.length>0)for(let I=0;I<E.dataTransfer.files.length;I++){const T=E.dataTransfer.files[I],D=T.path||T.webkitRelativePath||T.name;D&&M.push(D)}if(M.length===0)return;const z=r;if(!z)return;const U=b[z];if(!(U!=null&&U.ptySessionId))return;const Q=M.map(i8).join(" ");s8(U.ptySessionId,Q),setTimeout(()=>{const I=document.querySelector('.ide-bottom-terminal-wrap[style*="flex"] .xterm-helper-textarea');I==null||I.focus()},50)},[r,b]);return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`ide-bottom-panel ${w?"drop-highlight":""}`,onDragEnter:N,onDragOver:j,onDragLeave:$,onDrop:L,children:[i.jsxs("div",{className:"ide-bottom-tabs",children:[i.jsx("div",{className:"ide-bottom-tabs-list",ref:g,onDoubleClick:E=>{E.target===E.currentTarget&&_()},children:t.map((E,M)=>{const O=b[E],z=(O==null?void 0:O.title)||`Terminal ${M+1}`,U=E===r;return i.jsxs("button",{className:`ide-bottom-tab ${U?"active":""}`,onClick:()=>d(E),onDoubleClick:()=>h(),onContextMenu:Q=>x(Q,E),children:[i.jsx("span",{className:"ide-bottom-tab-title",title:z,children:z}),i.jsx("span",{className:"ide-bottom-tab-close",onClick:Q=>y(Q,E),children:i.jsx(at,{size:14})})]},E)})}),i.jsxs("div",{className:"ide-bottom-tabs-actions",children:[i.jsx("button",{className:"ide-bottom-action-btn",onClick:_,title:e("ide.newTerminal"),children:i.jsx(Ot,{size:16})}),i.jsx("button",{className:"ide-bottom-action-btn",onClick:h,title:n?e("ide.restorePanel")||"Restore Panel Size":e("ide.maximizePanel")||"Maximize Panel",children:n?i.jsx(Wu,{size:16}):i.jsx(Ba,{size:16})}),i.jsx("button",{className:"ide-bottom-action-btn",onClick:S,title:e("ide.hidePanel"),children:i.jsx(rt,{size:16})})]})]}),i.jsxs("div",{className:"ide-bottom-content",children:[t.map(E=>i.jsx("div",{className:"ide-bottom-terminal-wrap",style:{display:E===r?"flex":"none"},children:i.jsx(Pl,{paneId:E,initialCwd:p})},E)),t.length===0&&i.jsx("div",{className:"ide-bottom-empty",children:i.jsxs("button",{className:"ide-bottom-empty-btn",onClick:_,children:[i.jsx(Ot,{size:16}),i.jsx("span",{children:e("ide.newTerminal")||"New Terminal"})]})})]})]}),m&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"editor-context-overlay",onClick:f}),i.jsxs("div",{className:"editor-context-menu",style:{left:m.x,top:m.y},children:[i.jsx("button",{onClick:()=>{a(m.tabId),f()},children:e("terminal.close")}),i.jsx("button",{onClick:()=>{l(m.tabId),f()},children:e("terminal.closeOthers")}),i.jsx("button",{onClick:()=>{o(m.tabId),f()},children:e("terminal.closeToRight")}),i.jsx("div",{className:"editor-context-separator"}),i.jsx("button",{onClick:()=>{c(),f()},children:e("terminal.closeAll")})]})]})]})}const x1="data:image/svg+xml,%3csvg%20width='873'%20height='612'%20viewBox='0%200%20873%20612'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M611.24%200C631.42%200.472994%20652.67%200.151247%20672.917%200.149414L783.53%200.125977L783.58%20114.446C783.58%20131.188%20782.828%20155.62%20783.732%20171.959C793.764%20172.165%20866.262%20170.817%20869.239%20173.294C869.728%20173.699%20870.138%20174.379%20870.486%20174.905L872.008%20175.384C873.402%20179.664%20872.344%20228.902%20872.338%20236.71C872.313%20263.731%20873.157%20518.745%20871.959%20521.349C871.837%20521.605%20871.58%20521.905%20871.415%20522.119L869.141%20522.375C841.374%20521.684%20811.566%20522.247%20783.646%20522.271C784.001%20538.325%20783.695%20555.229%20783.72%20571.344C783.738%20583.932%20784.056%20598.74%20783.451%20611.182C613.783%20610.846%20273.598%20611.469%2087.6807%20611.041C87.3452%20610.736%2087.0093%20610.436%2086.6738%20610.137L86.2393%20607.375C86.831%20602.028%2086.4052%20585.668%2086.3984%20579.416L86.2812%20521.838C82.9453%20522.522%2063.9127%20522.272%2059.0283%20522.266L0.391602%20522.259L0.398438%20278.798L0.427734%20209.334C0.430803%20201.523%200.934097%20181.445%200%20174.62C0.578928%20172.779%200.0735528%20173.48%201.33105%20172.293C17.2444%20171.377%2036.4875%20172.458%2052.7188%20172.065C59.0087%20171.913%2081.4327%20171.805%2086.0195%20172.717L85.9805%2056.9336L85.9072%2021.3467C85.895%2015.7024%2085.6474%205.58945%2086.2832%200.297852L89.3057%200.0224609C145.847%201.00635%20204.767%200.149918%20261.493%200.137695L261.571%2058.8008C261.576%2063.634%20261.865%2082.5764%20261.06%2086.293C288.984%2085.6006%20319.108%2086.1736%20347.17%2086.1797L509.068%2086.1846L576.67%2086.1357C582.985%2086.1314%20604.124%2085.7374%20608.728%2086.8135C607.982%2081.7879%20608.33%2064.0733%20608.33%2058.0186L608.428%201.34473C609.424%20-0.0534957%20608.978%200.391111%20611.24%200ZM697.12%20173.048C694.553%20171.797%20619.805%20172.389%20610.134%20172.389L279.41%20172.397L201.266%20172.392C193.899%20172.39%20184.497%20172.27%20176.995%20172.399C175.636%20172.423%20175.324%20173.65%20174.702%20174.81L172.704%20175.383C172.033%20177.999%20172.341%20204.836%20172.348%20208.9L172.398%20294.312L172.37%20445.969L172.349%20494.032C172.347%20501.781%20172.011%20513.954%20172.658%20521.324C174.533%20523.401%20174.111%20521.52%20174.854%20522.534C175.611%20523.561%20175.655%20525.034%20177.928%20525.016C181.545%20524.988%20185.335%20524.97%20189.044%20524.966H347.752L604.785%20524.96L669.054%20525.009C673.406%20525.009%20693.575%20525.296%20696.857%20524.643C697.499%20523.408%20697.493%20523.505%20697.542%20522.118C696.815%20500.607%20697.389%20475.931%20697.389%20454.243V327.045L697.383%20228.248C697.383%20211.843%20696.729%20190.781%20697.64%20174.935L697.12%20173.048Z'%20fill='%2300BC90'/%3e%3cpath%20d='M347.56%20260.864L349.808%20261.441C351.42%20265.483%20350.329%20418.222%20350.229%20435.792C344.53%20436.85%20263.503%20436.929%20260.894%20435.722L261.464%20433.765C261.114%20420.392%20261.416%20405.532%20261.413%20392.005L261.412%20313.381C261.422%20299.699%20262.22%20276.275%20261.106%20263.652C261.428%20261.859%20261.059%20262.619%20262.19%20261.257C268.232%20260.664%20277.082%20261.319%20283.456%20261.111C303.554%20260.454%20327.973%20262.241%20347.56%20260.864Z'%20fill='%2300BC90'/%3e%3cpath%20d='M608.752%20260.881L610.641%20261.353C612.854%20266.169%20610.268%20347.019%20611.302%20358.962C611.693%20363.539%20611.436%20434.199%20610.892%20435.767C610.293%20435.847%20609.248%20436.027%20608.685%20436.028C584.88%20436.436%20548.549%20435.89%20523.533%20435.943C522.702%20435.945%20522.567%20435.098%20522.127%20434.149C522.787%20429.284%20522.445%20415.565%20522.445%20410.114L522.415%20362.246L522.457%20298.316C522.463%20288.598%20522.94%20272.837%20522.097%20263.668L522.586%20261.78C525.887%20259.891%20595.756%20261.699%20608.752%20260.881Z'%20fill='%2300BC90'/%3e%3c/svg%3e";function tv(e){const{direction:t,initialSize:r,minSize:n=120,maxSize:s,collapsible:a=!0,collapseThreshold:l,defaultCollapsed:o=!1,onResize:c,onCollapse:d,onMaximize:u,maximizeThreshold:h=.92,reverse:p=!1}=e,[m,v]=C.useState(r),[x,f]=C.useState(o),[b,g]=C.useState(!1),_=C.useRef(null),y=C.useRef(r);C.useEffect(()=>{x||v(r)},[r,x]),C.useEffect(()=>{f(o)},[o]);const S=l??n*.6,w=C.useCallback(()=>{if(s)return s;const L=_.current;if(!(L!=null&&L.parentElement))return 1/0;const E=L.parentElement.getBoundingClientRect();return(t==="horizontal"?E.width:E.height)*.8},[t,s]),k=C.useCallback(L=>{const E=Math.max(n,Math.min(w(),L));v(E),y.current=E,c==null||c(E)},[n,w,c]),A=C.useCallback(()=>{f(L=>{const E=!L;if(E)y.current=m;else{const M=Math.max(n,y.current);v(M),c==null||c(M)}return d==null||d(E),E})},[m,n,c,d]),N=C.useCallback((L,E)=>{g(!0);const M=_.current;if(!M)return;const O=x?0:m,z=w(),Q=(t==="horizontal"?M.clientWidth:M.clientHeight)*h;let I=!1;const T=()=>{g(!1),document.removeEventListener("pointermove",R),document.removeEventListener("pointerup",G),document.removeEventListener("pointercancel",G),document.body.style.cursor="",document.body.style.userSelect="",document.body.classList.remove("ide-sash-dragging")},D=(P,H)=>{if(I)return;let q;t==="horizontal"?q=P-L:q=H-E,p&&(q=-q);const B=O+q;if(a&&B<S){x||(y.current=m>n?m:r,f(!0),d==null||d(!0));return}if(u&&B>=Q){I=!0,u(),T();return}x&&B>=n&&(f(!1),d==null||d(!1));const F=Math.max(n,Math.min(z,B));v(F),c==null||c(F)},R=P=>D(P.clientX,P.clientY),G=()=>T();document.addEventListener("pointermove",R),document.addEventListener("pointerup",G),document.addEventListener("pointercancel",G),document.body.style.cursor=t==="horizontal"?"col-resize":"row-resize",document.body.style.userSelect="none",document.body.classList.add("ide-sash-dragging")},[x,m,t,p,a,S,n,r,w,c,d,u,h]),j=C.useCallback(L=>{L.preventDefault(),L.stopPropagation(),N(L.clientX,L.clientY)},[N]),$=["ide-sash",t==="horizontal"?"ide-sash-vertical":"ide-sash-horizontal",b?"dragging":""].filter(Boolean).join(" ");return{size:x?0:m,collapsed:x,sashProps:{onPointerDown:j,onDoubleClick:A,className:$},containerRef:_,setSize:k,toggleCollapse:A,dragging:b}}function a8(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function o8({filePath:e,rootPath:t,onSegmentClick:r,onOpenFile:n}){const a=(e.startsWith(t)?e.slice(t.length).replace(/^\//,""):e).split("/").filter(Boolean),[l,o]=C.useState(null),[c,d]=C.useState([]),[u,h]=C.useState(!1),[p,m]=C.useState(-1),v=C.useRef(null),x=C.useRef(null),f=C.useCallback(async(S,w)=>{const k=w.getBoundingClientRect();o({dirPath:S,anchorRect:k}),h(!0),d([]),m(-1);try{const A=await ds(S);d(a8(A.map(N=>({name:N.name,path:N.path,type:N.type}))))}catch{d([])}h(!1)},[]),b=C.useCallback(()=>{o(null),d([]),m(-1)},[]),g=C.useCallback(S=>{S.type==="directory"?(r(S.path),b()):(n(S.path),b())},[r,n,b]);C.useEffect(()=>{if(!l)return;const S=w=>{if(w.key==="Escape"){w.preventDefault(),b();return}w.key==="ArrowDown"?(w.preventDefault(),m(k=>k<c.length-1?k+1:0)):w.key==="ArrowUp"?(w.preventDefault(),m(k=>k>0?k-1:c.length-1)):w.key==="Enter"&&p>=0&&p<c.length&&(w.preventDefault(),g(c[p]))};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[l,c,p,b,g]),C.useEffect(()=>{var S;p>=0&&x.current&&((S=x.current.querySelectorAll(".breadcrumb-dropdown-item")[p])==null||S.scrollIntoView({block:"nearest"}))},[p]);const _=C.useCallback((S,w)=>{S.stopPropagation();const k=S.currentTarget;l&&l.dirPath===w?b():f(w,k)},[l,f,b]),y=C.useCallback((S,w)=>{S.stopPropagation();const k=S.currentTarget;l&&l.dirPath===w?b():f(w,k)},[l,f,b]);return i.jsxs("div",{className:"editor-breadcrumbs",children:[i.jsx("span",{style:{display:"inline-flex",alignItems:"center"},children:i.jsx("span",{className:`editor-breadcrumb-segment ${a.length===0?"active":""}`,onClick:S=>_(S,t),children:i.jsx("span",{children:t.split("/").pop()||t})})}),a.map((S,w)=>{const k=w===a.length-1,A=t+"/"+a.slice(0,w+1).join("/"),N=w===0?t:t+"/"+a.slice(0,w).join("/");return i.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[i.jsx("span",{className:"editor-breadcrumb-separator",children:i.jsx(We,{size:10})}),i.jsxs("span",{className:`editor-breadcrumb-segment ${k?"active":""} ${(l==null?void 0:l.dirPath)===(k?N:A)?"dropdown-open":""}`,onClick:j=>k?y(j,N):_(j,A),children:[k&&i.jsx(yn,{name:S,type:"file",size:14}),i.jsx("span",{style:k?{fontWeight:500}:void 0,children:S})]})]},A)}),l&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"breadcrumb-dropdown-overlay",onClick:b}),i.jsx("div",{ref:v,className:"breadcrumb-dropdown",style:{left:Math.min(l.anchorRect.left,window.innerWidth-260),top:l.anchorRect.bottom+2},children:u?i.jsx("div",{className:"breadcrumb-dropdown-loading",children:i.jsx(He,{size:14,className:"animate-spin"})}):c.length===0?i.jsx("div",{className:"breadcrumb-dropdown-empty",children:"Empty"}):i.jsx("div",{className:"breadcrumb-dropdown-list",ref:x,children:c.map((S,w)=>{const k=S.path===e,A=w===p;return i.jsxs("div",{className:`breadcrumb-dropdown-item ${k?"current":""} ${A?"highlighted":""}`,onClick:()=>g(S),children:[S.type==="directory"?i.jsx(We,{size:12,style:{flexShrink:0,opacity:.5}}):i.jsx(yn,{name:S.name,type:S.type,size:16}),i.jsx("span",{className:"breadcrumb-dropdown-item-name",children:S.name})]},S.path)})})})]})]})}function l8(e,t){const r=e.toLowerCase(),n=t.toLowerCase();let s=0,a=0,l=-1;for(let o=0;o<n.length&&s<r.length;o++)n[o]===r[s]&&(a+=o===l+1?2:1,(o===0||n[o-1]==="/"||n[o-1]===".")&&(a+=3),l=o,s++);return{match:s===r.length,score:a}}const rv=20,c8=3;function v1({isOpen:e,onClose:t,onSelect:r,rootPath:n}){const{t:s}=de(),[a,l]=C.useState(""),[o,c]=C.useState(0),[d,u]=C.useState([]),[h,p]=C.useState(!1),m=C.useRef(null),v=C.useRef(null),x=C.useRef(""),f=C.useRef([]),b=C.useCallback(async(y,S,w)=>{if(S>c8)return[];try{const k=await ds(y),A=[];for(const N of k){const j=w?`${w}/${N.name}`:N.name;if(N.type==="file"&&!E0(N.path))A.push({name:N.name,path:N.path,relativePath:j});else if(N.type==="directory"&&!N.name.startsWith(".")&&N.name!=="node_modules"){const $=await b(N.path,S+1,j);A.push(...$)}}return A}catch{return[]}},[]);C.useEffect(()=>{if(e){if(l(""),c(0),setTimeout(()=>{var y;return(y=m.current)==null?void 0:y.focus()},0),x.current===n&&f.current.length>0){u(f.current);return}p(!0),b(n,0,"").then(y=>{x.current=n,f.current=y,u(y),p(!1)})}},[e,n,b]);const g=C.useMemo(()=>{if(!a.trim())return d.slice(0,rv);const y=[];for(const S of d){const w=l8(a,S.relativePath);w.match&&y.push({entry:S,score:w.score})}return y.sort((S,w)=>w.score-S.score),y.slice(0,rv).map(S=>S.entry)},[d,a]);C.useEffect(()=>{c(0)},[g.length,a]);const _=C.useCallback(y=>{switch(y.key){case"ArrowDown":y.preventDefault(),c(S=>(S+1)%Math.max(g.length,1));break;case"ArrowUp":y.preventDefault(),c(S=>(S-1+g.length)%Math.max(g.length,1));break;case"Enter":y.preventDefault(),g[o]&&r(g[o].path);break;case"Escape":y.preventDefault(),t();break}},[g,o,r,t]);return C.useEffect(()=>{var S;const y=(S=v.current)==null?void 0:S.children[o];y==null||y.scrollIntoView({block:"nearest"})},[o]),e?i.jsx("div",{className:"quick-open-overlay",onClick:t,children:i.jsxs("div",{className:"quick-open-dialog",onClick:y=>y.stopPropagation(),onKeyDown:_,children:[i.jsx("input",{ref:m,className:"quick-open-input",type:"text",value:a,onChange:y=>l(y.target.value),placeholder:s("editor.quickOpenPlaceholder")}),i.jsx("div",{className:"quick-open-list",ref:v,children:h?i.jsx("div",{className:"quick-open-empty",children:s("editor.quickOpenLoading")}):g.length===0?i.jsx("div",{className:"quick-open-empty",children:(a.trim(),s("editor.quickOpenEmpty"))}):g.map((y,S)=>i.jsxs("div",{className:`quick-open-item${S===o?" active":""}`,onClick:()=>r(y.path),onMouseEnter:()=>c(S),children:[i.jsx(yn,{name:y.name,type:"file",size:14}),i.jsx("span",{className:"quick-open-item-name",children:y.name}),i.jsx("span",{className:"quick-open-item-path",children:y.relativePath})]},y.path))})]})}):null}const Ca=Ke()(Gs((e,t)=>({isOpen:!0,setOpen:r=>e({isOpen:r}),toggle:()=>e({isOpen:!t().isOpen})}),{namespace:"sidebar",fields:["isOpen"],scope:"global",debounceMs:300}));function d8({gitFileCount:e=0}){const{t}=de(),r=yt(u=>u.activePanel),n=yt(u=>u.sidePanelCollapsed),s=yt(u=>u.toggleActivePanel),a=yt(u=>u.bottomPanelCollapsed),l=yt(u=>u.toggleBottomPanel),o=Ca(u=>u.isOpen),c=Ca(u=>u.toggle),d=C.useCallback(u=>r===u&&!n,[r,n]);return i.jsxs("div",{className:"ide-activity-bar",children:[i.jsxs("div",{className:"ide-activity-bar-top",children:[i.jsx("button",{className:`ide-activity-btn ${d("explorer")?"active":""}`,onClick:()=>s("explorer"),title:t("ide.explorer")||"Explorer",children:i.jsx(zv,{size:22,strokeWidth:1.5})}),i.jsx("button",{className:`ide-activity-btn ${d("search")?"active":""}`,onClick:()=>s("search"),title:t("ide.search")||"Search",children:i.jsx(br,{size:22,strokeWidth:1.5})}),i.jsxs("button",{className:`ide-activity-btn ${d("source-control")?"active":""}`,onClick:()=>s("source-control"),title:t("ide.sourceControl")||"Source Control",children:[i.jsx(gs,{size:22,strokeWidth:1.5}),e>0&&i.jsx("span",{className:"ide-activity-badge",children:e>99?"99+":e})]})]}),i.jsxs("div",{className:"ide-activity-bar-bottom",children:[i.jsx("button",{className:`ide-activity-btn ${a?"":"active"}`,onClick:l,title:t("ide.terminal")||"Terminal",children:i.jsx(IE,{size:22,strokeWidth:1.5})}),i.jsx("button",{className:`ide-activity-btn ${o?"active":""}`,onClick:c,title:t("sidebar.toggle")||"Toggle Sidebar",children:i.jsx(qu,{size:22,strokeWidth:1.5})})]})]})}function u8(){try{const e=localStorage.getItem("cbc_search_prefs");if(e)return{...nv,...JSON.parse(e)}}catch{}return nv}const nv={viewMode:"tree",caseSensitive:!1,isRegex:!1,wholeWord:!1,query:"",includePattern:"",excludePattern:"",useDefaultExcludes:!0};function Tn(e){try{localStorage.setItem("cbc_search_prefs",JSON.stringify(e))}catch{}}function In(e){return{viewMode:e.viewMode,caseSensitive:e.caseSensitive,isRegex:e.isRegex,wholeWord:e.wholeWord,query:e.query,includePattern:e.includePattern,excludePattern:e.excludePattern,useDefaultExcludes:e.useDefaultExcludes}}const Kn=u8(),h8=Ke((e,t)=>({query:Kn.query,isRegex:Kn.isRegex,caseSensitive:Kn.caseSensitive,wholeWord:Kn.wholeWord,includePattern:Kn.includePattern,excludePattern:Kn.excludePattern,useDefaultExcludes:Kn.useDefaultExcludes,viewMode:Kn.viewMode,results:[],searching:!1,totalMatches:0,fileCount:0,error:null,setQuery:r=>{e({query:r}),Tn(In({...t(),query:r}))},search:async()=>{var h;const{query:r,isRegex:n,caseSensitive:s,wholeWord:a,includePattern:l,excludePattern:o,useDefaultExcludes:c}=t();if(!r.trim())return;const d=jl();let u=o||void 0;if(c){const p="node_modules,**/.git,**/dist,**/build,**/.next,**/coverage";u=u?`${u},${p}`:p}e({searching:!0,error:null,results:[],totalMatches:0,fileCount:0});try{const p=await fetch("/api/v1/fs/search-content",{method:"POST",headers:{...ve(),"Content-Type":"application/json"},body:JSON.stringify({query:r.trim(),cwd:d||void 0,isRegex:n,caseSensitive:s,wholeWord:a,includeGlob:l||void 0,excludeGlob:u,maxResults:200})});if(p.ok){const m=await p.json(),x=(m.data??m).results||[],f=new Map;for(const g of x)f.has(g.path)||f.set(g.path,[]),f.get(g.path).push(g);const b=[];for(const[g,_]of f)b.push({path:g,matches:_});e({results:b,totalMatches:x.length,fileCount:b.length,searching:!1})}else{const m=await p.json().catch(()=>null),v=((h=m==null?void 0:m.error)==null?void 0:h.message)||`HTTP ${p.status}`;e({searching:!1,error:v})}}catch(p){e({searching:!1,error:p.message||"Search failed"})}},toggleRegex:()=>{e(r=>({isRegex:!r.isRegex})),Tn(In(t()))},toggleCaseSensitive:()=>{e(r=>({caseSensitive:!r.caseSensitive})),Tn(In(t()))},toggleWholeWord:()=>{e(r=>({wholeWord:!r.wholeWord})),Tn(In(t()))},setIncludePattern:r=>{e({includePattern:r}),Tn(In({...t(),includePattern:r}))},setExcludePattern:r=>{e({excludePattern:r}),Tn(In({...t(),excludePattern:r}))},toggleUseDefaultExcludes:()=>{e(r=>({useDefaultExcludes:!r.useDefaultExcludes})),Tn(In(t()))},setViewMode:r=>{e({viewMode:r}),Tn(In(t()))},clear:()=>{e({query:"",includePattern:"",excludePattern:"",results:[],totalMatches:0,fileCount:0,searching:!1,error:null}),Tn(In(t()))}}));function p8(e){const t={children:[]};for(const n of e){const s=n.path.split("/");let a=t;for(let l=0;l<s.length;l++){const o=s[l];if(l===s.length-1)a.children.push({name:o,fullPath:n.path,isDir:!1,children:[],matches:n.matches,matchCount:n.matches.length});else{let d=a.children.find(u=>u.isDir&&u.name===o);d||(d={name:o,fullPath:s.slice(0,l+1).join("/"),isDir:!0,children:[],matchCount:0},a.children.push(d)),a=d}}}function r(n){if(n.isDir&&n.children.length===1&&n.children[0].isDir){const l=n.children[0];return r({...l,name:`${n.name}/${l.name}`})}const s=n.children.map(r),a=s.reduce((l,o)=>l+o.matchCount,0);return{...n,children:s,matchCount:n.isDir?a:n.matchCount}}return t.children.map(r)}function w1(){const{t:e}=de(),{query:t,isRegex:r,caseSensitive:n,wholeWord:s,includePattern:a,excludePattern:l,useDefaultExcludes:o,viewMode:c,results:d,searching:u,totalMatches:h,fileCount:p,error:m,setQuery:v,search:x,toggleRegex:f,toggleCaseSensitive:b,toggleWholeWord:g,setIncludePattern:_,setExcludePattern:y,toggleUseDefaultExcludes:S,setViewMode:w}=h8(),{openFile:k}=mt(),A=C.useRef(null),[N,j]=C.useState(new Set),[$,L]=C.useState(!0);C.useEffect(()=>{var I;(I=A.current)==null||I.focus()},[]),C.useEffect(()=>{const I=new Set;for(const T of d){I.add(T.path);const D=T.path.split("/");for(let R=1;R<D.length;R++)I.add(D.slice(0,R).join("/"))}j(I),L(!0)},[d]);const E=C.useMemo(()=>p8(d),[d]),M=C.useCallback(I=>{I.key==="Enter"&&(I.preventDefault(),x())},[x]),O=C.useCallback(I=>{j(T=>{const D=new Set(T);return D.has(I)?D.delete(I):D.add(I),D})},[]),z=C.useCallback(()=>{j(new Set),L(!1)},[]),U=C.useCallback(()=>{const I=new Set;for(const T of d){I.add(T.path);const D=T.path.split("/");for(let R=1;R<D.length;R++)I.add(D.slice(0,R).join("/"))}j(I),L(!0)},[d]),Q=C.useCallback((I,T)=>{const D=T?{line:T,query:t.trim()}:void 0;k(I,void 0,D)},[k,t]);return i.jsxs("div",{className:"search-panel",children:[i.jsx("div",{className:"scm-header",children:i.jsx("span",{className:"scm-header-title",children:e("ide.search.title")})}),i.jsxs("div",{className:"search-input-section",children:[i.jsxs("div",{className:"search-field",children:[i.jsx("input",{ref:A,className:"search-field-input",value:t,onChange:I=>v(I.target.value),onKeyDown:M,placeholder:e("ide.search.placeholder")}),i.jsxs("div",{className:"search-field-actions",children:[i.jsx("button",{className:`search-field-btn ${n?"active":""}`,onClick:b,title:e("ide.search.matchCase"),children:i.jsx(OC,{size:14})}),i.jsx("button",{className:`search-field-btn ${s?"active":""}`,onClick:g,title:e("ide.search.wholeWord"),children:i.jsx(L2,{size:14})}),i.jsx("button",{className:`search-field-btn ${r?"active":""}`,onClick:f,title:e("ide.search.regex"),children:i.jsx(QE,{size:14})})]})]}),i.jsxs("div",{className:"search-filter-section",children:[i.jsx("span",{className:"search-filter-label",children:e("ide.search.filesToInclude")}),i.jsx("div",{className:"search-field",children:i.jsx("input",{className:"search-field-input",value:a,onChange:I=>_(I.target.value),onKeyDown:M,placeholder:e("ide.search.includePlaceholder")||"e.g. *.ts, src/**/include"})})]}),i.jsxs("div",{className:"search-filter-section",children:[i.jsx("span",{className:"search-filter-label",children:e("ide.search.filesToExclude")}),i.jsxs("div",{className:"search-field",children:[i.jsx("input",{className:"search-field-input",value:l,onChange:I=>y(I.target.value),onKeyDown:M,placeholder:e("ide.search.excludePlaceholder")||"e.g. node_modules, *.min.js"}),i.jsx("div",{className:"search-field-actions",children:i.jsx("button",{className:`search-field-btn ${o?"active":""}`,onClick:S,title:e("ide.search.useExcludeSettings")||"Use Exclude Settings and Ignore Files",children:i.jsx(Dl,{size:14})})})]})]})]}),(u||h>0||m)&&i.jsxs("div",{className:"search-status-bar",children:[u&&i.jsxs("div",{className:"search-status",children:[i.jsx(He,{size:14,className:"animate-spin"}),i.jsx("span",{children:e("ide.search.searching")})]}),!u&&h>0&&i.jsx("div",{className:"search-status",children:i.jsxs("span",{children:[h," results in ",p," files"]})}),m&&i.jsx("div",{className:"search-status search-error",children:m.includes("timed out")?e("ide.search.timedOut"):e("ide.search.failed")}),h>0&&i.jsxs("div",{className:"search-status-actions",children:[i.jsx("button",{className:`scm-icon-btn ${c==="list"?"active":""}`,onClick:()=>w("list"),title:e("ide.listView"),children:i.jsx(Yv,{size:14})}),i.jsx("button",{className:`scm-icon-btn ${c==="tree"?"active":""}`,onClick:()=>w("tree"),title:e("ide.treeView"),children:i.jsx(sw,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:$?z:U,title:$?"Collapse All":"Expand All",children:$?i.jsx(RA,{size:14}):i.jsx(I2,{size:14})})]})]}),i.jsxs("div",{className:"search-results",children:[c==="tree"&&E.map(I=>i.jsx(S1,{node:I,depth:0,expandedPaths:N,onToggle:O,onFileClick:Q,query:t},I.fullPath)),c==="list"&&d.map(I=>i.jsxs("div",{className:"search-tree-group",children:[i.jsxs("div",{className:"search-tree-file",style:{paddingLeft:"4px"},onClick:()=>O(I.path),children:[N.has(I.path)?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx(yn,{name:I.path.split("/").pop()||"",type:"file",size:14}),i.jsx("span",{className:"search-tree-name",children:I.path.split("/").pop()}),i.jsx("span",{className:"search-list-filepath",children:I.path}),i.jsx("span",{className:"search-tree-badge",children:I.matches.length})]}),N.has(I.path)&&i.jsx("div",{className:"search-tree-matches",children:I.matches.map((T,D)=>i.jsx("div",{className:"search-tree-match",style:{paddingLeft:"24px"},onClick:()=>Q(I.path,T.line),children:i.jsx(k1,{text:T.text,query:t})},D))})]},I.path)),!u&&t&&h===0&&!m&&i.jsxs("div",{className:"scm-empty",children:[i.jsx(br,{size:20,strokeWidth:1.5,style:{opacity:.3}}),i.jsx("span",{children:e("ide.search.noResults")})]})]})]})}function S1({node:e,depth:t,expandedPaths:r,onToggle:n,onFileClick:s,query:a}){const l=r.has(e.fullPath),o=t*14;if(e.isDir)return i.jsxs("div",{className:"search-tree-group",children:[i.jsxs("div",{className:"search-tree-dir",style:{paddingLeft:`${o+4}px`},onClick:()=>n(e.fullPath),children:[l?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx(Hu,{size:14,className:"scm-tree-folder-icon"}),i.jsx("span",{className:"search-tree-name",children:e.name}),i.jsx("span",{className:"search-tree-badge",children:e.matchCount})]}),l&&e.children.map(d=>i.jsx(S1,{node:d,depth:t+1,expandedPaths:r,onToggle:n,onFileClick:s,query:a},d.fullPath))]});const c=e.name;return i.jsxs("div",{className:"search-tree-group",children:[i.jsxs("div",{className:"search-tree-file",style:{paddingLeft:`${o+4}px`},onClick:()=>n(e.fullPath),children:[l?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx(yn,{name:c,type:"file",size:14}),i.jsx("span",{className:"search-tree-name",children:c}),i.jsx("span",{className:"search-tree-badge",children:e.matchCount})]}),l&&e.matches&&i.jsx("div",{className:"search-tree-matches",children:e.matches.map((d,u)=>i.jsx("div",{className:"search-tree-match",style:{paddingLeft:`${o+24}px`},onClick:()=>s(e.fullPath,d.line),children:i.jsx(k1,{text:d.text,query:a})},u))})]})}function k1({text:e,query:t}){if(!t)return i.jsx("span",{className:"search-match-text",children:e});const r=[],n=e.toLowerCase(),s=t.toLowerCase();let a=0,l=n.indexOf(s),o=0;for(;l!==-1&&o<10;)l>a&&r.push(i.jsx("span",{children:e.slice(a,l)},o++)),r.push(i.jsx("span",{className:"search-highlight",children:e.slice(l,l+t.length)},o++)),a=l+t.length,l=n.indexOf(s,a);return a<e.length&&r.push(i.jsx("span",{children:e.slice(a)},o++)),i.jsx("span",{className:"search-match-text",children:r})}const C1={modified:{label:"M",color:"var(--color-accent-yellow)"},added:{label:"A",color:"var(--color-accent-green)"},deleted:{label:"D",color:"var(--color-accent-red)"},renamed:{label:"R",color:"var(--color-accent-blue)"},copied:{label:"C",color:"var(--color-accent-blue)"},untracked:{label:"U",color:"var(--color-accent-green)"},conflicted:{label:"!",color:"var(--color-accent-red)"}};function A1({file:e,onStage:t,onUnstage:r,onDiscard:n,onOpenFile:s}){const{t:a}=de(),l=C.useCallback(o=>{o.stopPropagation(),navigator.clipboard.writeText(e.path).catch(()=>{})},[e.path]);return i.jsxs("div",{className:"scm-file-actions",children:[i.jsx("button",{className:"scm-file-action-btn",onClick:l,title:a("ide.scm.copyPath"),children:i.jsx(Ci,{size:13})}),s&&e.status!=="deleted"&&i.jsx("button",{className:"scm-file-action-btn",onClick:o=>{o.stopPropagation(),s(e.path)},title:a("ide.scm.openFile"),children:i.jsx(Ar,{size:13})}),n&&i.jsx("button",{className:"scm-file-action-btn",onClick:o=>{o.stopPropagation(),n(e.path)},title:a("ide.scm.discard"),children:i.jsx(zs,{size:13})}),t&&i.jsx("button",{className:"scm-file-action-btn",onClick:o=>{o.stopPropagation(),t(e.path)},title:a("ide.scm.stage"),children:i.jsx(Ot,{size:13})}),r&&i.jsx("button",{className:"scm-file-action-btn",onClick:o=>{o.stopPropagation(),r(e.path)},title:a("ide.scm.unstage"),children:i.jsx(Pa,{size:13})})]})}function m8({files:e,sectionTitle:t,sectionCount:r,sectionActions:n,onStage:s,onUnstage:a,onDiscard:l,onSelect:o,onOpenFile:c}){const[d,u]=C.useState(!0);return i.jsxs("div",{className:"scm-file-list",children:[t&&i.jsxs("div",{className:"scm-tree-section-root",onClick:()=>u(h=>!h),children:[d?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{className:"scm-tree-section-title",children:t}),r!==void 0&&i.jsx("span",{className:"scm-section-count",children:r}),n&&i.jsx("div",{className:"scm-file-actions",children:n})]}),(!t||d)&&e.map(h=>{const p=C1[h.status]||{label:"?",color:"var(--color-text-tertiary)"},m=h.path.split("/").pop()||h.path,v=h.path.includes("/")?h.path.substring(0,h.path.lastIndexOf("/")):"";return i.jsxs("div",{className:"scm-file-item",onClick:()=>o==null?void 0:o(h.path),children:[i.jsx(yn,{name:m,type:"file",size:16}),i.jsx("span",{className:"scm-file-name-text",children:m}),v&&i.jsx("span",{className:"scm-file-path-desc",children:v}),i.jsx(A1,{file:h,onStage:s,onUnstage:a,onDiscard:l,onOpenFile:c}),i.jsx("span",{className:"scm-file-status",style:{color:p.color},children:p.label})]},`${h.path}-${h.staged}`)})]})}function f8(e){const t={children:[]};for(const n of e){const s=n.path.split("/");let a=t;for(let l=0;l<s.length;l++){const o=s[l],c=l===s.length-1,d=s.slice(0,l+1).join("/");if(c)a.children.push({name:o,fullPath:d,isDir:!1,children:[],file:n});else{let u=a.children.find(h=>h.isDir&&h.name===o);u||(u={name:o,fullPath:d,isDir:!0,children:[]},a.children.push(u)),a=u}}}function r(n){if(n.isDir&&n.children.length===1&&n.children[0].isDir){const s=n.children[0];return r({...s,name:`${n.name}/${s.name}`})}return{...n,children:n.children.map(r)}}return t.children.map(r)}function Iu({node:e,depth:t,onStage:r,onUnstage:n,onDiscard:s,onSelect:a,onOpenFile:l}){const{t:o}=de(),[c,d]=C.useState(!0);function u(b){if(!b.isDir)return null;const g=Ru(b);return g.length===0?null:g.some(_=>_.status==="modified")?"var(--color-accent-yellow)":g.some(_=>_.status==="untracked"||_.status==="added")?"var(--color-accent-green)":"var(--color-text-tertiary)"}const h=u(e),p=Ru(e),m=C.useCallback(b=>{b.stopPropagation(),r&&p.forEach(g=>r(g.path))},[r,p]),v=C.useCallback(b=>{b.stopPropagation(),s&&p.forEach(g=>s(g.path))},[s,p]),x=C.useCallback(b=>{b.stopPropagation(),n&&p.forEach(g=>n(g.path))},[n,p]),f=t*16+4;return i.jsxs("div",{className:"scm-tree-group",children:[i.jsxs("div",{className:"scm-tree-dir",style:{paddingLeft:`${f}px`},onClick:()=>d(b=>!b),children:[Array.from({length:t},(b,g)=>i.jsx("span",{className:"scm-tree-indent-guide",style:{left:`${g*16+12}px`}},g)),c?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx(Hu,{size:14,className:"scm-tree-folder-icon"}),i.jsx("span",{className:"scm-tree-dir-name",children:e.name}),i.jsxs("div",{className:"scm-file-actions",children:[s&&i.jsx("button",{className:"scm-file-action-btn",onClick:v,title:o("ide.scm.discardAll"),children:i.jsx(zs,{size:13})}),r&&i.jsx("button",{className:"scm-file-action-btn",onClick:m,title:o("ide.scm.stageAll"),children:i.jsx(Ot,{size:13})}),n&&i.jsx("button",{className:"scm-file-action-btn",onClick:x,title:o("ide.scm.unstageAll"),children:i.jsx(Pa,{size:13})})]}),h&&i.jsx("span",{className:"scm-tree-dir-dot",style:{background:h}})]}),c&&e.children.map(b=>b.isDir?i.jsx(Iu,{node:b,depth:t+1,onStage:r,onUnstage:n,onDiscard:s,onSelect:a,onOpenFile:l},b.fullPath):i.jsx(Nu,{node:b,depth:t+1,onStage:r,onUnstage:n,onDiscard:s,onSelect:a,onOpenFile:l},b.fullPath))]})}function Nu({node:e,depth:t,onStage:r,onUnstage:n,onDiscard:s,onSelect:a,onOpenFile:l}){const o=e.file,c=C1[o.status]||{label:"?",color:"var(--color-text-tertiary)"};return i.jsxs("div",{className:"scm-file-item",style:{paddingLeft:`${t*16+20}px`},onClick:()=>a==null?void 0:a(o.path),children:[Array.from({length:t},(d,u)=>i.jsx("span",{className:"scm-tree-indent-guide",style:{left:`${u*16+12}px`}},u)),i.jsx(yn,{name:e.name,type:"file",size:16}),i.jsx("span",{className:"scm-file-name-text",children:e.name}),i.jsx(A1,{file:o,onStage:r,onUnstage:n,onDiscard:s,onOpenFile:l}),i.jsx("span",{className:"scm-file-status",style:{color:c.color},children:c.label})]})}function Ru(e){return e.isDir?e.children.flatMap(Ru):e.file?[e.file]:[]}function g8({files:e,sectionTitle:t,sectionCount:r,sectionActions:n,onStage:s,onUnstage:a,onDiscard:l,onSelect:o,onOpenFile:c}){const[d,u]=C.useState(!0),h=f8(e);return t?i.jsxs("div",{className:"scm-file-list scm-tree-view",children:[i.jsxs("div",{className:"scm-tree-section-root",onClick:()=>u(p=>!p),children:[d?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{className:"scm-tree-section-title",children:t}),r!==void 0&&i.jsx("span",{className:"scm-section-count",children:r}),n&&i.jsx("div",{className:"scm-file-actions",children:n})]}),d&&h.map(p=>p.isDir?i.jsx(Iu,{node:p,depth:1,onStage:s,onUnstage:a,onDiscard:l,onSelect:o,onOpenFile:c},p.fullPath):i.jsx(Nu,{node:p,depth:1,onStage:s,onUnstage:a,onDiscard:l,onSelect:o,onOpenFile:c},p.fullPath))]}):i.jsx("div",{className:"scm-file-list scm-tree-view",children:h.map(p=>p.isDir?i.jsx(Iu,{node:p,depth:0,onStage:s,onUnstage:a,onDiscard:l,onSelect:o,onOpenFile:c},p.fullPath):i.jsx(Nu,{node:p,depth:0,onStage:s,onUnstage:a,onDiscard:l,onSelect:o,onOpenFile:c},p.fullPath))})}function sv(e){return e.viewMode==="tree"?i.jsx(g8,{...e}):i.jsx(m8,{...e})}const iv=["var(--color-accent-green)","var(--color-accent-blue)","var(--color-accent-yellow)","var(--color-accent-purple)","var(--color-accent-red)"];function b8(){const{t:e}=de(),[t,r]=C.useState(!1),[n,s]=C.useState([]),[a,l]=C.useState(!1),o=C.useCallback(async()=>{l(!0);try{const d=await qF(30);s(d)}catch{}l(!1)},[]);C.useEffect(()=>{t&&n.length===0&&!a&&o()},[t,n.length,a,o]);const c=d=>{try{const u=new Date(d),p=new Date().getTime()-u.getTime(),m=Math.floor(p/6e4);if(m<60)return`${m}m ago`;const v=Math.floor(m/60);if(v<24)return`${v}h ago`;const x=Math.floor(v/24);return x<7?`${x}d ago`:u.toLocaleDateString()}catch{return d}};return i.jsxs("div",{className:"scm-graph",children:[i.jsxs("button",{className:"scm-section-header",onClick:()=>r(d=>!d),children:[t?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{children:e("ide.scm.graph")}),t&&i.jsx("button",{className:"scm-icon-btn",onClick:d=>{d.stopPropagation(),o()},title:e("ide.refresh"),children:i.jsx(St,{size:12,className:a?"animate-spin":""})})]}),t&&i.jsxs("div",{className:"scm-graph-list",children:[a&&n.length===0&&i.jsx("div",{className:"scm-graph-loading",children:i.jsx(He,{size:14,className:"animate-spin"})}),n.map((d,u)=>i.jsxs("div",{className:"scm-graph-entry",title:`${d.hash}
1029
1029
  ${d.author}
1030
- ${d.date}`,children:[i.jsx("span",{className:"scm-graph-dot",style:{background:iv[u%iv.length]}}),i.jsx("span",{className:"scm-graph-msg",children:d.message}),i.jsx("span",{className:"scm-graph-time",children:c(d.date)})]},d.hash))]})]})}function E1(){const{t:e}=de(),{isGitRepo:t,loading:r,files:n,currentBranch:s,ahead:a,behind:l,pushing:o,pulling:c,branches:d,branchesLoading:u,lastOperationMessage:h,refresh:p,loadBranches:m,stageFile:v,unstageFile:x,stageAll:f,unstageAll:b,discardFile:g,discardAll:_,push:y,pull:S,switchBranch:w,createBranch:k,clearOperationMessage:A}=Bn(),N=mt(D=>D.openFile),j=yt(D=>D.scmViewMode),$=yt(D=>D.setScmViewMode),[L,E]=C.useState(!0),[M,O]=C.useState(!0);C.useEffect(()=>{p(),Bn.getState().startWatching()},[p]),C.useEffect(()=>{if(h){const D=setTimeout(A,3e3);return()=>clearTimeout(D)}},[h,A]);const z=C.useCallback(D=>{w(D)},[w]),U=C.useCallback(async(D,R)=>{yt.getState().bottomPanelMaximized&&yt.setState({bottomPanelMaximized:!1});try{const G=await h1(D,R);mt.getState().openDiffTab(D,{oldText:G.oldText,newText:G.newText,staged:R})}catch{}},[]),Q=C.useCallback(D=>{N(D)},[N]),I=n.filter(D=>D.staged),T=n.filter(D=>!D.staged);return t?i.jsxs("div",{className:"scm-panel",children:[i.jsxs("div",{className:"scm-header",children:[i.jsx("span",{className:"scm-header-title",children:e("ide.scm.title")}),i.jsxs("div",{className:"scm-header-actions",children:[i.jsx("button",{className:`scm-icon-btn ${j==="list"?"active":""}`,onClick:()=>$("list"),title:e("ide.listView"),children:i.jsx(Yv,{size:14})}),i.jsx("button",{className:`scm-icon-btn ${j==="tree"?"active":""}`,onClick:()=>$("tree"),title:e("ide.treeView"),children:i.jsx(sw,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:p,disabled:r,title:e("ide.refresh"),children:i.jsx(St,{size:14,className:r?"animate-spin":""})})]})]}),i.jsxs("div",{className:"scm-scroll",children:[i.jsxs("div",{className:"scm-section",children:[i.jsxs("button",{className:"scm-section-header",onClick:()=>E(D=>!D),children:[L?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{children:e("ide.scm.repositories")})]}),L&&i.jsx(p1,{currentBranch:s,branches:d,branchesLoading:u,onSwitch:z,onCreate:k,onLoadBranches:m,actions:i.jsxs(i.Fragment,{children:[(a>0||l>0)&&i.jsxs("span",{className:"scm-branch-sync",children:[a>0&&i.jsxs("span",{children:["↑",a]}),l>0&&i.jsxs("span",{children:["↓",l]})]}),i.jsxs("div",{className:"scm-branch-actions",children:[i.jsx("button",{className:"scm-icon-btn",onClick:S,disabled:c,title:e("ide.scm.pull"),children:c?i.jsx(He,{size:14,className:"animate-spin"}):i.jsx(jv,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:y,disabled:o,title:e("ide.scm.push"),children:o?i.jsx(He,{size:14,className:"animate-spin"}):i.jsx(Jo,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:p,disabled:r,title:e("ide.refresh"),children:i.jsx(St,{size:12,className:r?"animate-spin":""})})]})]})})]}),i.jsxs("div",{className:"scm-section",children:[i.jsxs("button",{className:"scm-section-header",onClick:()=>O(D=>!D),children:[M?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{children:e("ide.scm.changes")}),i.jsx("span",{className:"scm-section-count",children:n.length})]}),h&&i.jsx("div",{className:"scm-operation-msg",children:h}),M&&i.jsxs(i.Fragment,{children:[I.length>0&&i.jsx(sv,{files:I,viewMode:j,sectionTitle:e("ide.scm.stagedChanges"),sectionCount:I.length,sectionActions:i.jsx("button",{className:"scm-file-action-btn",onClick:()=>b(),title:e("ide.scm.unstageAll"),children:i.jsx(Pa,{size:13})}),onUnstage:x,onSelect:D=>U(D,!0),onOpenFile:Q}),T.length>0&&i.jsx(sv,{files:T,viewMode:j,sectionTitle:e("ide.scm.changes"),sectionCount:T.length,sectionActions:i.jsxs(i.Fragment,{children:[i.jsx("button",{className:"scm-file-action-btn",onClick:()=>_(),title:e("ide.scm.discardAll"),children:i.jsx(zs,{size:13})}),i.jsx("button",{className:"scm-file-action-btn",onClick:()=>f(),title:e("ide.scm.stageAll"),children:i.jsx(Ot,{size:13})})]}),onStage:v,onDiscard:g,onSelect:D=>U(D,!1),onOpenFile:Q}),n.length===0&&!r&&i.jsxs("div",{className:"scm-empty",children:[i.jsx(Fn,{size:20,strokeWidth:1.5,style:{opacity:.3}}),i.jsx("span",{children:e("ide.scm.noChanges")})]})]})]}),i.jsx(b8,{})]})]}):i.jsxs("div",{className:"scm-panel",children:[i.jsx("div",{className:"scm-header",children:i.jsx("span",{className:"scm-header-title",children:e("ide.scm.title")})}),i.jsxs("div",{className:"ide-panel-placeholder",children:[i.jsx(gs,{size:32,strokeWidth:1,style:{opacity:.2}}),i.jsx("div",{className:"ide-panel-placeholder-text",children:e("ide.scm.notGitRepo")})]})]})}function y8({activePanel:e,onMenuClick:t}){return i.jsxs("div",{className:"ide-side-panel-content",children:[e==="explorer"&&i.jsx(y1,{onMenuClick:t}),e==="search"&&i.jsx(w1,{}),e==="source-control"&&i.jsx(E1,{})]})}function _8({onMenuClick:e,activeTab:t,mdToggleBtn:r,cursorInfo:n,imageInfo:s,previewZoom:a,isMarkdownSource:l,quickOpenVisible:o,setQuickOpenVisible:c,onContentChange:d,onSave:u,onCursorChange:h,onImageInfo:p,onZoomChange:m}){const{t:v}=de(),{rootPath:x,openFile:f,revealInTree:b}=mt(),{activePanel:g,sidePanelWidth:_,sidePanelCollapsed:y,setSidePanelWidth:S,setSidePanelCollapsed:w,bottomPanelHeight:k,bottomPanelCollapsed:A,bottomPanelMaximized:N,setBottomPanelHeight:j,setBottomPanelCollapsed:$,toggleBottomPanelMaximize:L}=yt(),E=tv({direction:"horizontal",initialSize:_,minSize:160,maxSize:600,collapsible:!0,defaultCollapsed:y,onResize:S,onCollapse:w}),M=tv({direction:"vertical",initialSize:k,minSize:140,maxSize:typeof window<"u"?Math.max(300,window.innerHeight-80):500,collapsible:!0,defaultCollapsed:A,reverse:!0,onResize:j,onCollapse:$,onMaximize:L,maximizeThreshold:.85}),O=Bn(D=>D.files.length);C.useEffect(()=>(Bn.getState().refresh(),Bn.getState().startWatching(),()=>{Bn.getState().stopWatching()}),[]);const z=typeof navigator<"u"&&navigator.platform.includes("Mac"),U=()=>t?t.viewMode==="diff"&&t.diffData?i.jsx("div",{className:"editor-container",children:i.jsx(Ps,{path:t.path,oldText:t.diffData.oldText,newText:t.diffData.newText})}):t.viewMode==="editor"||l?i.jsx("div",{className:"editor-container",children:i.jsx(u1,{path:t.path,content:t.content,language:t.language,onContentChange:d,onSave:u,minimap:!0,onCursorChange:h})}):i.jsx(g1,{path:t.path,name:t.name,content:t.content,viewMode:t.viewMode,onImageInfo:p,onZoomChange:m}):i.jsx(x8,{isMac:z,t:v}),Q=o&&x&&i.jsx(v1,{isOpen:o,onClose:()=>c(!1),onSelect:D=>{f(D),c(!1)},rootPath:x}),I=g&&!E.collapsed,T=!M.collapsed;return i.jsxs("div",{className:"ide-layout",children:[Q,i.jsxs("div",{className:"ide-layout-row",ref:E.containerRef,children:[i.jsx(d8,{gitFileCount:O}),I&&i.jsxs("div",{className:"ide-side-panel",style:{width:E.size},children:[i.jsx(y8,{activePanel:g,onMenuClick:e}),i.jsx("div",{...E.sashProps})]}),i.jsxs("div",{className:"ide-main-area",ref:M.containerRef,children:[!N&&i.jsxs("div",{className:"ide-editor-area",style:{flex:T?void 0:1,height:T?`calc(100% - ${M.size}px)`:"100%"},children:[i.jsx(f1,{actions:r}),t&&x&&i.jsx(o8,{filePath:t.path,rootPath:x,onSegmentClick:b,onOpenFile:f}),i.jsx("div",{className:"ide-editor-content",onDragOver:D=>{D.preventDefault(),D.dataTransfer.dropEffect="copy"},onDrop:D=>{D.preventDefault();const R=D.dataTransfer.getData("application/x-file-paths")||D.dataTransfer.getData("text/plain");if(R){try{const G=JSON.parse(R),P=Array.isArray(G)?G:[R];P.length>0&&f(P[0])}catch{R&&f(R)}setTimeout(()=>{const G=document.querySelector(".ide-editor-content .monaco-editor textarea");G==null||G.focus()},100)}},children:U()})]}),T&&i.jsxs(i.Fragment,{children:[!N&&i.jsx("div",{...M.sashProps}),i.jsx("div",{className:"ide-bottom-panel-wrap",style:{height:N?"100%":M.size},children:i.jsx(_1,{})})]})]})]}),i.jsx("div",{className:"ide-statusbar-drag-zone",onPointerDown:M.sashProps.onPointerDown,onDoubleClick:M.sashProps.onDoubleClick,children:i.jsx(m1,{language:(t==null?void 0:t.language)||"",cursorLine:n.line,cursorColumn:n.col,selectedCount:n.selectedChars,selectedLines:n.selectedLines,viewMode:t?l?"editor":t.viewMode:"editor",imageInfo:s,zoom:a})})]})}function x8({isMac:e,t}){const r=C.useRef(null),[n,s]=C.useState(!1);return C.useEffect(()=>{const a=r.current;if(!a)return;const l=new ResizeObserver(o=>{for(const c of o)s(c.contentRect.height<300)});return l.observe(a),()=>l.disconnect()},[]),i.jsxs("div",{className:"editor-empty",ref:r,children:[i.jsx("div",{className:"ide-empty-icon",children:i.jsx("img",{src:x1,alt:"CodeBuddy",width:"64",height:"64",style:{opacity:.15,filter:"grayscale(1)"}})}),!n&&i.jsxs("div",{className:"editor-empty-shortcuts",children:[i.jsxs("div",{className:"editor-empty-hint",children:[i.jsxs("kbd",{children:[e?"⌘":"Ctrl","+P"]}),i.jsx("span",{children:t("editor.quickOpen")})]}),i.jsxs("div",{className:"editor-empty-hint",children:[i.jsxs("kbd",{children:[e?"⌘":"Ctrl","+B"]}),i.jsx("span",{children:t("ide.toggleSidebar")||"Toggle Sidebar"})]}),i.jsxs("div",{className:"editor-empty-hint",children:[i.jsxs("kbd",{children:[e?"⌃":"Ctrl","+`"]}),i.jsx("span",{children:t("ide.toggleTerminal")||"Toggle Terminal"})]})]})]})}function v8(){const{t:e}=de(),t=yt(a=>a.activeMobilePanel),r=yt(a=>a.setActiveMobilePanel),n=Bn(a=>a.files.length),s=[{id:"explorer",icon:i.jsx(zv,{size:20,strokeWidth:1.5}),label:e("ide.explorer")||"Explorer"},{id:"search",icon:i.jsx(br,{size:20,strokeWidth:1.5}),label:e("ide.search")||"Search"},{id:"source-control",icon:i.jsx(gs,{size:20,strokeWidth:1.5}),label:e("ide.sourceControl")||"Source Control",badge:n},{id:"terminal",icon:i.jsx(qs,{size:20,strokeWidth:1.5}),label:e("ide.terminal")||"Terminal"}];return i.jsx("div",{className:"mobile-tab-bar",children:s.map(a=>i.jsxs("button",{className:`mobile-tab-bar-btn ${t===a.id?"active":""}`,onClick:()=>r(a.id),children:[i.jsxs("span",{className:"mobile-tab-bar-icon",children:[a.icon,a.badge!=null&&a.badge>0&&i.jsx("span",{className:"mobile-tab-bar-badge",children:a.badge>99?"99+":a.badge})]}),i.jsx("span",{className:"mobile-tab-bar-label",children:a.label})]},a.id))})}const w8=1e3;function av({onMenuClick:e}){const{t}=de(),{tabs:r,activeTabId:n,updateTabContent:s,saveTab:a,closeTab:l}=mt(),{setRootPath:o,openFile:c,rootPath:d}=mt(),[u,h]=C.useState(!1),p=yt(P=>P.toggleBottomPanel),[m,v]=C.useState(()=>window.innerWidth<768),[x,f]=C.useState(!1),b=C.useRef("");C.useEffect(()=>{const P=async()=>{if(ah()!=="editor")return;const q=hl(),B=q.get("path");if(!B)return;const F=q.get("line"),Z=q.get("col"),J=`${B}:${F}:${Z}`;if(J===b.current)return;if(b.current=J,await $R(B)==="directory")await o(B);else{const ne=B.substring(0,B.lastIndexOf("/"));ne&&await o(ne);const re=F?parseInt(F,10):void 0,me=re?{line:re,col:Z?parseInt(Z,10):1,query:""}:void 0;c(B,void 0,me)}};P();const H=()=>P();return window.addEventListener("hashchange",H),()=>window.removeEventListener("hashchange",H)},[]),C.useEffect(()=>{const P=window.matchMedia("(min-width: 768px)"),H=q=>{v(!q.matches),q.matches&&f(!1)};return P.addEventListener("change",H),()=>P.removeEventListener("change",H)},[]),C.useEffect(()=>{m&&n&&f(!0)},[m,n,r.length]);const g=mt(P=>P.pendingReveal);C.useEffect(()=>{m&&g&&n&&f(!0)},[m,g,n]);const _=r.find(P=>P.id===n)||null,y=C.useRef(),S=C.useCallback(P=>{if(!n)return;s(n,P),clearTimeout(y.current);const H=n;y.current=setTimeout(()=>{const q=mt.getState().tabs.find(B=>B.id===H);!q||!q.isDirty||a(H)},w8)},[n,s,a]);C.useEffect(()=>()=>clearTimeout(y.current),[]),C.useEffect(()=>{const P=H=>{const q=H.metaKey||H.ctrlKey;if(q&&H.key==="p"&&!H.shiftKey&&(H.preventDefault(),h(!0)),q&&H.key==="w"&&!H.shiftKey&&(H.preventDefault(),n&&l(n)),q&&H.key==="b"&&!H.shiftKey){H.preventDefault();const B=yt.getState();B.setSidePanelCollapsed(!B.sidePanelCollapsed)}q&&H.key==="`"&&(H.preventDefault(),p())};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[n,l,p]);const w=C.useCallback(()=>{clearTimeout(y.current),n&&a(n)},[n,a]),[k,A]=C.useState({line:1,col:1,selectedChars:0,selectedLines:0}),N=C.useCallback((P,H,q,B)=>{A({line:P,col:H,selectedChars:q,selectedLines:B})},[]),[j,$]=C.useState(null),[L,E]=C.useState(1),[M,O]=C.useState(new Set),z=(_==null?void 0:_.viewMode)==="markdown"&&!M.has(_.id),U=C.useCallback(()=>{n&&O(P=>{const H=new Set(P);return H.has(n)?H.delete(n):H.add(n),H})},[n]),Q=(_==null?void 0:_.viewMode)==="markdown"?z?i.jsx("button",{className:"editor-action-btn",onClick:U,title:t("editor.preview"),children:i.jsx(Pu,{size:16})}):i.jsx("button",{className:"editor-action-btn",onClick:U,title:t("editor.source"),children:i.jsx(Rl,{size:16})}):null,I=C.useCallback(()=>{const P=new URLSearchParams(window.location.search);P.set("standalone","1"),window.open(`#/editor?${P.toString()}`,"_blank","noopener,noreferrer")},[]),T=i.jsxs(i.Fragment,{children:[Q,i.jsx("button",{className:"editor-action-btn",onClick:I,title:t("editor.openInNewWindow"),children:i.jsx(Ar,{size:16})})]}),D=yt(P=>P.activeMobilePanel),R=yt(P=>P.createBottomTerminal),G=yt(P=>P.bottomTerminals);if(C.useEffect(()=>{m&&D==="terminal"&&G.length===0&&R()},[m,D,G.length,R]),m){const P=u&&d&&i.jsx(v1,{isOpen:u,onClose:()=>h(!1),onSelect:q=>{c(q),h(!1)},rootPath:d}),H=_?_.viewMode==="editor"||z?i.jsx("div",{className:"editor-container",children:i.jsx(u1,{path:_.path,content:_.content,language:_.language,onContentChange:S,onSave:w,minimap:!1,onCursorChange:N})}):i.jsx(g1,{path:_.path,name:_.name,content:_.content,viewMode:_.viewMode,onImageInfo:$,onZoomChange:E}):null;return i.jsxs("div",{className:"editor-view editor-view-mobile",children:[P,i.jsxs("div",{className:"mobile-panel-content",children:[D==="explorer"&&i.jsx("div",{className:"editor-sidebar editor-sidebar-mobile",children:i.jsx(y1,{onMenuClick:e})}),D==="search"&&i.jsx(w1,{}),D==="source-control"&&i.jsx(E1,{}),D==="terminal"&&i.jsx("div",{className:"mobile-terminal-panel",children:i.jsx(_1,{})})]}),i.jsx("div",{className:`editor-mobile-panel ${x?"open":""}`,children:i.jsxs("div",{className:"editor-main",children:[i.jsxs("div",{className:"editor-mobile-header",children:[i.jsx("button",{className:"editor-mobile-back",onClick:()=>f(!1),children:i.jsx(Mi,{size:18})}),i.jsx("div",{className:"editor-mobile-tabs-wrap",children:i.jsx(f1,{actions:T})})]}),H,_&&i.jsx(m1,{language:_.language,cursorLine:k.line,cursorColumn:k.col,selectedCount:k.selectedChars,selectedLines:k.selectedLines,viewMode:z?"editor":_.viewMode,imageInfo:j,zoom:L})]})}),i.jsx(v8,{})]})}return i.jsx("div",{className:"editor-view",children:i.jsx(_8,{onMenuClick:e,activeTab:_,editorContent:null,mdToggleBtn:T,cursorInfo:k,imageInfo:j,previewZoom:L,isMarkdownSource:z,quickOpenVisible:u,setQuickOpenVisible:h,onContentChange:S,onSave:w,onCursorChange:N,onImageInfo:$,onZoomChange:E})})}class Kt extends C.Component{constructor(r){super(r);fe(this,"handleRetry",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,n){console.error(`[ErrorBoundary${this.props.viewName?` - ${this.props.viewName}`:""}]`,r,n)}render(){var r;return this.state.hasError?i.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:i.jsxs("div",{className:"text-center max-w-md",children:[i.jsx("div",{className:"text-[48px] mb-4 text-text-tertiary",children:"!"}),i.jsx("h2",{className:"text-text-primary text-[16px] font-semibold mb-2",children:this.props.errorTitle||"Something went wrong"}),i.jsx("p",{className:"text-text-tertiary text-[13px] mb-4 break-words",children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),i.jsx("button",{onClick:this.handleRetry,className:"px-6 py-2 bg-accent-brand text-bg-primary rounded-lg text-[13px] font-medium hover:opacity-90 active:scale-95 transition-all",children:this.props.retryLabel||"Retry"})]})}):this.props.children}}function S8(e){return!Number.isFinite(e)||e<0?"0":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function k8(e,t,r,n){const s=Math.max(1,Math.round(e/1e3)),a=n(t===1?"goal.recap.stats.turn":"goal.recap.stats.turns"),l=n(r===1?"goal.recap.stats.token":"goal.recap.stats.tokens");return`${s}s · ${t} ${a} · ${S8(r)} ${l}`}function C8(){const e=$t(a=>a.goalRecap),t=$t(a=>a.dismissGoalRecap),{t:r}=de();C.useEffect(()=>{if(!e)return;const a=l=>{l.key==="Escape"&&(l.preventDefault(),t())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,t]);const n=C.useCallback(()=>t(),[t]),s=C.useMemo(()=>A8(e,r),[e,r]);return e?i.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:n}),i.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"goal-recap-title",className:"relative bg-bg-card border border-border-default rounded-xl shadow-2xl w-full max-w-[480px] mx-4 overflow-hidden",children:[i.jsx("div",{className:"px-5 pt-5 pb-4 flex flex-col gap-3",children:s}),i.jsxs("div",{className:"px-5 pb-4 pt-2 border-t border-border-default text-text-tertiary text-[12px]",children:[i.jsx("span",{className:"text-text-secondary",children:r("goal.recap.footer.setAnother")}),i.jsx("span",{children:r("goal.recap.footer.toSetAnother")}),i.jsx("span",{className:"text-text-secondary",children:"Esc"}),i.jsxs("span",{children:[" ",r("goal.recap.footer.escDismiss")]})]})]})]}):null}function A8(e,t){if(!e)return null;if(e.active)return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Nd,{size:18,className:"text-accent-brand"}),i.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.active")})]}),i.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed",children:[t("goal.progress.condition"),": ",e.active.condition]})]});if(e.latest){const{ok:r,reason:n,condition:s,durationMs:a,turnCount:l,tokenDelta:o}=e.latest,c=r?Nl:ki,d=r?"text-accent-green":"text-accent-red",u=t(r?"goal.recap.achieved":"goal.recap.impossible"),h=k8(a,l,o,t);return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(c,{size:18,className:d}),i.jsx("h3",{id:"goal-recap-title",className:`text-[15px] font-semibold ${d}`,children:u})]}),i.jsx("div",{className:"text-text-secondary text-[12px]",children:h}),i.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed mt-2",children:[t("goal.progress.condition"),": ",s]}),n?i.jsxs("div",{className:"text-text-tertiary text-[12px] break-words leading-relaxed",children:[t("goal.progress.reason"),": ",n]}):null]})}return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Nd,{size:18,className:"text-text-tertiary"}),i.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.empty.title")})]}),i.jsx("div",{className:"text-text-secondary text-[13px] leading-relaxed",children:t("goal.recap.empty.hint")}),i.jsx("div",{className:"text-text-tertiary text-[12px] leading-relaxed",children:t("goal.recap.empty.example")})]})}function E8(e,t){const n=Date.now()-e,s=Math.floor(n/6e4),a=Math.floor(n/36e5),l=Math.floor(n/864e5);return t==="zh"?s<1?"刚刚":s<60?`${s} 分钟前`:a<24?`${a} 小时前`:l<30?`${l} 天前`:new Date(e).toLocaleDateString("zh-CN"):s<1?"Just now":s<60?`${s}m ago`:a<24?`${a}h ago`:l<30?`${l}d ago`:new Date(e).toLocaleDateString("en-US")}function T8({isOpen:e,onClose:t,onSwitchSession:r}){const{t:n,resolved:s}=de(),[a,l]=C.useState([]),[o,c]=C.useState(!0),[d,u]=C.useState(null),[h,p]=C.useState(null),[m,v]=C.useState(null),[x,f]=C.useState(""),b=C.useRef(null),[g,_]=C.useState(null),y=C.useCallback(async()=>{c(!0),u(null);try{const $=await fetch("/api/v1/sessions",{headers:ve()});if(!$.ok)throw new Error(`HTTP ${$.status}`);const L=await $.json(),E=L.data??L;l(E.sessions||[])}catch($){u($.message||"Unknown error")}finally{c(!1)}},[]);C.useEffect(()=>{e&&y()},[e,y]);const S=C.useCallback(async $=>{var L;try{const E=await fetch(`/api/v1/sessions/${encodeURIComponent($.id)}`,{method:"DELETE",headers:ve()});if(!E.ok){const M=await E.json().catch(()=>({}));throw new Error(((L=M.error)==null?void 0:L.message)||M.error||`HTTP ${E.status}`)}l(M=>M.filter(O=>O.id!==$.id))}catch(E){console.error("[history] Delete failed:",E)}finally{_(null)}},[]),w=C.useCallback(async($,L)=>{var M;const E=L.trim();if(E)try{const O=await fetch(`/api/v1/sessions/${encodeURIComponent($.id)}/rename`,{method:"POST",headers:ve({"Content-Type":"application/json"}),body:JSON.stringify({name:E})});if(!O.ok){const z=await O.json().catch(()=>({}));throw new Error(((M=z.error)==null?void 0:M.message)||z.error||`HTTP ${O.status}`)}l(z=>z.map(U=>U.id===$.id?{...U,name:E}:U))}catch(O){console.error("[history] Rename failed:",O)}finally{v(null),f("")}},[]),k=C.useCallback(($,L)=>{L.stopPropagation(),v($),f($.name),setTimeout(()=>{var E;return(E=b.current)==null?void 0:E.focus()},50)},[]),A=C.useCallback(($,L)=>{L.stopPropagation(),!$.isCurrent&&_($)},[]),N=C.useCallback(async $=>{if(!($.isCurrent||h)){p($.id);try{await(r==null?void 0:r($.id)),t()}finally{p(null)}}},[h,r,t]),j=()=>o?i.jsx("div",{className:"history-loading",children:i.jsx(bn,{size:"small",text:n("history.loading")})}):d?i.jsxs("div",{className:"history-error",children:[i.jsx("p",{className:"history-error-text",children:n("history.loadError")}),i.jsx("button",{className:"history-retry-btn",onClick:y,children:n("history.retry")})]}):a.length===0?i.jsxs("div",{className:"history-empty",children:[i.jsx($i,{size:48,className:"text-text-tertiary"}),i.jsx("p",{className:"history-empty-title",children:n("history.noData")}),i.jsx("p",{className:"history-empty-hint",children:n("history.noDataHint")})]}):i.jsx("div",{className:"history-list",children:a.map(($,L)=>{const E=fl($.updatedAt),M=L>0?fl(a[L-1].updatedAt):null,O=E!==M;return i.jsxs("div",{children:[O&&i.jsx(es,{label:cS($.updatedAt,s)}),i.jsxs("div",{className:`history-session-item${$.isCurrent?" current":""}${!$.isCurrent&&!h?" clickable":""}`,onClick:()=>!$.isCurrent&&!h&&N($),children:[i.jsxs("div",{className:"history-session-info",children:[i.jsx("p",{className:"history-session-name",children:$.name}),i.jsxs("div",{className:"history-session-meta",children:[$.isCurrent&&i.jsx("span",{className:"history-session-badge",children:n("history.current")}),i.jsx("span",{children:n("history.messages").replace("{count}",String($.messageCount))}),i.jsx("span",{children:E8($.updatedAt,s)})]})]}),i.jsxs("div",{className:"history-session-actions",children:[h===$.id&&i.jsx("div",{className:"history-session-switching",children:i.jsx("div",{className:"history-session-spinner"})}),h!==$.id&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:"history-action-btn",title:n("history.rename"),onClick:z=>k($,z),children:i.jsx(LE,{size:14})}),!$.isCurrent&&i.jsx("button",{className:"history-action-btn danger",title:n("history.delete"),onClick:z=>A($,z),children:i.jsx(Oi,{size:14})})]})]})]})]},$.id)})});return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`history-drawer-overlay ${e?"open":""}`,onClick:t}),i.jsxs("div",{className:`history-drawer ${e?"open":""}`,children:[i.jsxs("div",{className:"history-drawer-header",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"history-drawer-title",children:n("history.title")}),i.jsx("p",{className:"history-drawer-subtitle",children:n("history.description")})]}),i.jsx("button",{onClick:t,className:"history-drawer-close",children:i.jsx(at,{size:16})})]}),i.jsx("div",{className:"history-content",children:j()})]}),m&&i.jsx("div",{className:"history-rename-overlay",onClick:()=>v(null),children:i.jsxs("div",{className:"history-rename-dialog",onClick:$=>$.stopPropagation(),children:[i.jsx("h3",{children:n("history.renameTitle")}),i.jsx("input",{ref:b,className:"history-rename-input",value:x,onChange:$=>f($.target.value),placeholder:n("history.renamePlaceholder"),onKeyDown:$=>{$.key==="Enter"&&x.trim()&&w(m,x),$.key==="Escape"&&v(null)}}),i.jsxs("div",{className:"history-rename-actions",children:[i.jsx("button",{className:"history-rename-cancel",onClick:()=>v(null),children:n("history.renameCancel")}),i.jsx("button",{className:"history-rename-ok",disabled:!x.trim(),onClick:()=>w(m,x),children:n("history.renameOk")})]})]})}),g&&i.jsx("div",{className:"history-delete-overlay",onClick:()=>_(null),children:i.jsxs("div",{className:"history-delete-dialog",onClick:$=>$.stopPropagation(),children:[i.jsx("p",{children:n("history.deleteConfirm")}),i.jsxs("div",{className:"history-delete-actions",children:[i.jsx("button",{className:"history-delete-cancel",onClick:()=>_(null),children:n("history.deleteCancel")}),i.jsx("button",{className:"history-delete-ok",onClick:()=>S(g),children:n("history.deleteOk")})]})]})})]})}function $o(e,t){return`${e}@${t}`}async function As(e,t){return Ve(e,{method:"POST",headers:{"Content-Type":"application/json",...ve()},body:t?JSON.stringify(t):void 0})}async function I8(e){return Ve(e,{method:"DELETE",headers:ve()})}async function ov(e){return Ve(e,{method:"GET",headers:ve()})}const N8=Ke((e,t)=>({plugins:[],loading:!1,error:null,marketplaces:[],marketplaceLoading:!1,availablePlugins:[],browsingMarketplace:null,browsingLoading:!1,browsingError:null,operatingPlugins:new Set,fetchPlugins:async()=>{e({loading:!0,error:null});try{const r=await ov("/api/v1/plugins");if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=(await r.json()).data,a=Array.isArray(s)?s.map(l=>({...l,canRemove:l.canRemove,canSwitchoff:l.canSwitchoff,canEdit:l.canEdit})):[];e({plugins:a,loading:!1})}catch(r){console.warn("[plugin-store] fetchPlugins failed:",r),e({error:r.message,loading:!1})}},fetchMarketplaces:async()=>{e({marketplaceLoading:!0});try{const r=await ov("/api/v1/plugins/marketplaces");if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=(await r.json()).data;e({marketplaces:Array.isArray(s)?s:[],marketplaceLoading:!1})}catch(r){console.warn("[plugin-store] fetchMarketplaces failed:",r),e({marketplaceLoading:!1})}},browseMarketplace:async r=>{var n;e({browsingMarketplace:r,browsingLoading:!0,browsingError:null});try{const s=await As("/api/v1/plugins/marketplaces/browse",{marketplace:r});if(!s.ok){const c=await s.json().catch(()=>null);throw new Error(((n=c==null?void 0:c.error)==null?void 0:n.message)||`HTTP ${s.status}`)}const a=await s.json(),o=(Array.isArray(a.data)?a.data:[]).map(c=>({name:c.name,version:c.version,description:c.description,marketplace:c.marketplaceName||r,installed:!!c.status,author:c.author,license:c.license,homepage:c.homepage,repository:c.repository,keywords:c.keywords,category:c.category,features:c.features,source:c.source}));e({availablePlugins:o,browsingLoading:!1})}catch(s){console.warn("[plugin-store] browseMarketplace failed:",s),e({browsingError:s.message,browsingLoading:!1})}},browseAllMarketplaces:async()=>{const{marketplaces:r}=t();if(r.length!==0){e({browsingMarketplace:"__all__",browsingLoading:!0,browsingError:null});try{const n=await Promise.allSettled(r.map(async c=>{var p;const d=await As("/api/v1/plugins/marketplaces/browse",{marketplace:c.name});if(!d.ok){const m=await d.json().catch(()=>null);throw new Error(((p=m==null?void 0:m.error)==null?void 0:p.message)||`HTTP ${d.status}`)}const u=await d.json();return(Array.isArray(u.data)?u.data:[]).map(m=>({name:m.name,version:m.version,description:m.description,marketplace:m.marketplaceName||c.name,installed:!!m.status,author:m.author,license:m.license,homepage:m.homepage,repository:m.repository,keywords:m.keywords,category:m.category,features:m.features,source:m.source}))})),s=[];let a=!1;for(const c of n)c.status==="fulfilled"?s.push(...c.value):a=!0;const l=new Set,o=s.filter(c=>{const d=`${c.name}@${c.marketplace}`;return l.has(d)?!1:(l.add(d),!0)});e({availablePlugins:o,browsingLoading:!1,browsingError:a&&o.length===0?"Some marketplaces failed to load":null})}catch(n){console.warn("[plugin-store] browseAllMarketplaces failed:",n),e({browsingError:n.message,browsingLoading:!1})}}},enablePlugin:async(r,n)=>{var a;const s=$o(r,n);e(l=>({operatingPlugins:new Set(l.operatingPlugins).add(s)}));try{const l=await As("/api/v1/plugins/enable",{plugin:s});if(!l.ok){const o=await l.json().catch(()=>null);throw new Error(((a=o==null?void 0:o.error)==null?void 0:a.message)||`HTTP ${l.status}`)}await t().fetchPlugins()}finally{e(l=>{const o=new Set(l.operatingPlugins);return o.delete(s),{operatingPlugins:o}})}},disablePlugin:async(r,n)=>{var a;const s=$o(r,n);e(l=>({operatingPlugins:new Set(l.operatingPlugins).add(s)}));try{const l=await As("/api/v1/plugins/disable",{plugin:s});if(!l.ok){const o=await l.json().catch(()=>null);throw new Error(((a=o==null?void 0:o.error)==null?void 0:a.message)||`HTTP ${l.status}`)}await t().fetchPlugins()}finally{e(l=>{const o=new Set(l.operatingPlugins);return o.delete(s),{operatingPlugins:o}})}},uninstallPlugin:async(r,n)=>{var a;const s=$o(r,n);e(l=>({operatingPlugins:new Set(l.operatingPlugins).add(s)}));try{const l=await As("/api/v1/plugins/uninstall",{plugin:s});if(!l.ok){const o=await l.json().catch(()=>null);throw new Error(((a=o==null?void 0:o.error)==null?void 0:a.message)||`HTTP ${l.status}`)}await t().fetchPlugins()}finally{e(l=>{const o=new Set(l.operatingPlugins);return o.delete(s),{operatingPlugins:o}})}},installPlugin:async(r,n,s)=>{var l;const a=$o(r,n);e(o=>({operatingPlugins:new Set(o.operatingPlugins).add(a)}));try{const o=await As("/api/v1/plugins",{plugin:a,options:s?{scope:s}:void 0});if(!o.ok){const d=await o.json().catch(()=>null);throw new Error(((l=d==null?void 0:d.error)==null?void 0:l.message)||`HTTP ${o.status}`)}await t().fetchPlugins();const c=t();c.browsingMarketplace&&(c.browsingMarketplace==="__all__"?await t().browseAllMarketplaces():await t().browseMarketplace(c.browsingMarketplace))}finally{e(o=>{const c=new Set(o.operatingPlugins);return c.delete(a),{operatingPlugins:c}})}},addMarketplace:async(r,n)=>{var a;const s=await As("/api/v1/plugins/marketplaces",{source:r,name:n});if(!s.ok){const l=await s.json().catch(()=>null);throw new Error(((a=l==null?void 0:l.error)==null?void 0:a.message)||`HTTP ${s.status}`)}await t().fetchMarketplaces()},removeMarketplace:async r=>{var s;const n=await I8(`/api/v1/plugins/marketplaces/${encodeURIComponent(r)}`);if(!n.ok){const a=await n.json().catch(()=>null);throw new Error(((s=a==null?void 0:a.error)==null?void 0:s.message)||`HTTP ${n.status}`)}await t().fetchMarketplaces()}}));function T1(){const{t:e}=de(),{plugins:t,marketplaces:r,loading:n,marketplaceLoading:s,error:a,operatingPlugins:l,availablePlugins:o,browsingLoading:c,browsingError:d,fetchPlugins:u,fetchMarketplaces:h,browseMarketplace:p,browseAllMarketplaces:m,enablePlugin:v,disablePlugin:x,uninstallPlugin:f,installPlugin:b,addMarketplace:g,removeMarketplace:_}=N8(),[y,S]=C.useState("installed"),[w,k]=C.useState(""),[A,N]=C.useState("all"),[j,$]=C.useState(null),[L,E]=C.useState(!1),[M,O]=C.useState(""),[z,U]=C.useState(""),[Q,I]=C.useState(!1),[T,D]=C.useState(null),[R,G]=C.useState(null),[P,H]=C.useState(null),[q,B]=C.useState(""),[F,Z]=C.useState(""),[J,te]=C.useState(null),ne=C.useCallback(ce=>{te(Ce=>Ce===ce?null:ce)},[]);C.useEffect(()=>{u(),h()},[u,h]),C.useEffect(()=>{y==="browse"&&!q&&r.length>0&&(B("__all__"),m())},[y,r,q,m]);const re=C.useCallback(async ce=>{$(null);try{ce.status==="enabled"?await x(ce.name,ce.marketplace):await v(ce.name,ce.marketplace)}catch(Ce){$(Ce.message)}},[v,x]),me=C.useCallback(async ce=>{$(null),G(null);try{await f(ce.name,ce.marketplace)}catch(Ce){$(Ce.message)}},[f]),he=C.useCallback(async(ce,Ce)=>{$(null);try{await b(ce.name,ce.marketplace,Ce)}catch(Le){$(Le.message)}},[b]),pe=C.useCallback(async()=>{const ce=M.trim();if(ce){I(!0),D(null);try{await g(ce,z.trim()||void 0),O(""),U(""),E(!1)}catch(Ce){D(Ce.message)}finally{I(!1)}}},[M,z,g]),ae=C.useCallback(async ce=>{$(null),H(null);try{if(await _(ce),q===ce&&r.length>1){const Ce=r.find(Le=>Le.name!==ce);Ce&&(B(Ce.name),p(Ce.name))}}catch(Ce){$(Ce.message)}},[_,q,r,p]),ye=C.useCallback(()=>{u(),h(),y==="browse"&&q&&(q==="__all__"?m():p(q))},[u,h,y,q,p,m]),be=C.useCallback(ce=>{B(ce),Z(""),ce==="__all__"?m():p(ce)},[p,m]),le=ce=>`${ce.name}@${ce.marketplace}`,_e=C.useMemo(()=>{const ce=new Set(t.map(Ce=>Ce.marketplace));return Array.from(ce).sort()},[t]),Te=C.useMemo(()=>{let ce=t;A!=="all"&&(ce=ce.filter(Le=>Le.marketplace===A));const Ce=w.trim().toLowerCase();return Ce&&(ce=ce.filter(Le=>Le.name.toLowerCase().includes(Ce)||Le.description&&Le.description.toLowerCase().includes(Ce)||Le.marketplace.toLowerCase().includes(Ce))),ce},[t,A,w]),$e=C.useMemo(()=>{let ce=o;const Ce=F.trim().toLowerCase();return Ce&&(ce=ce.filter(Le=>Le.name.toLowerCase().includes(Ce)||Le.description&&Le.description.toLowerCase().includes(Ce))),ce},[o,F]),Ze=t.filter(ce=>ce.status==="enabled").length;return i.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[i.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:i.jsxs("div",{className:"max-w-3xl mx-auto",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("plugins.title")}),y==="installed"&&t.length>0&&i.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[t.length," ",e("plugins.totalCount")," · ",Ze," ",e("plugins.enabled")]}),y==="browse"&&q&&!c&&o.length>0&&i.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[o.length," ",e("plugins.totalCount")]}),y==="marketplaces"&&r.length>0&&i.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[r.length," ",e("plugins.totalCount")]})]}),i.jsx("button",{onClick:ye,disabled:n||c,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${n||c?"opacity-50 cursor-not-allowed border-border-muted text-text-secondary":"border-border-muted text-text-secondary hover:text-text-primary hover:border-text-primary/20 hover:bg-bg-secondary"}`,title:e("plugins.refresh"),children:i.jsx(St,{size:14,className:n||c?"animate-spin":""})})]}),i.jsxs("div",{className:"flex gap-1 border-b border-border-muted",children:[i.jsx("button",{onClick:()=>{S("installed"),$(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${y==="installed"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.installedPlugins")}),i.jsx("button",{onClick:()=>{S("browse"),$(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${y==="browse"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.browseMarketplace")}),i.jsx("button",{onClick:()=>{S("marketplaces"),$(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${y==="marketplaces"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.marketplaces")})]}),y==="installed"&&t.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx(br,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),i.jsx("input",{type:"text",value:w,onChange:ce=>k(ce.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),w&&i.jsx("button",{onClick:()=>k(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:i.jsx(at,{size:12})})]}),_e.length>1&&i.jsxs("select",{value:A,onChange:ce=>N(ce.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[i.jsx("option",{value:"all",children:e("plugins.allMarketplaces")}),_e.map(ce=>i.jsx("option",{value:ce,children:ce},ce))]})]}),y==="browse"&&r.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx(br,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),i.jsx("input",{type:"text",value:F,onChange:ce=>Z(ce.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),F&&i.jsx("button",{onClick:()=>Z(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:i.jsx(at,{size:12})})]}),i.jsxs("select",{value:q,onChange:ce=>be(ce.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[i.jsx("option",{value:"__all__",children:e("plugins.allMarketplaces")}),r.map(ce=>i.jsx("option",{value:ce.name,children:ce.name},ce.name))]})]})]})}),i.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:i.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[j&&i.jsxs("div",{className:"bg-accent-red/10 border border-accent-red/30 rounded-xl p-3.5 text-accent-red text-[13px] flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(rn,{size:14,className:"shrink-0"}),i.jsxs("span",{className:"truncate",children:[e("plugins.operationFailed"),": ",j]})]}),i.jsx("button",{onClick:()=>$(null),className:"w-5 h-5 flex items-center justify-center rounded-full hover:bg-accent-red/20 transition-colors shrink-0 ml-3",children:i.jsx(at,{size:12})})]}),y==="installed"&&i.jsxs(i.Fragment,{children:[n&&t.length===0&&i.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:i.jsx(bn,{size:"small",text:e("plugins.loading")})}),a&&!n&&t.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[i.jsx(rn,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),i.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),i.jsx("button",{onClick:u,className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),!n&&!a&&t.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(Fs,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noPlugins")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noPluginsHint")})]}),t.length>0&&Te.length===0&&!n&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[i.jsx(br,{size:36,className:"mb-3 opacity-30"}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),Te.length>0&&i.jsx("div",{className:"space-y-3",children:Te.map(ce=>{const Ce=le(ce);return i.jsx(R8,{plugin:ce,isEnabled:ce.status==="enabled",isOperating:l.has(Ce),isExpanded:J===Ce,confirmUninstall:R===Ce,onToggle:()=>re(ce),onUninstall:()=>me(ce),onConfirmUninstall:()=>G(Ce),onCancelUninstall:()=>G(null),onExpand:()=>ne(Ce),t:e},Ce)})})]}),y==="browse"&&i.jsxs(i.Fragment,{children:[!s&&r.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(xa,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),c&&o.length===0&&q&&i.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:i.jsx(bn,{size:"small",text:e("plugins.browsingMarketplace")})}),d&&o.length===0&&q&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[i.jsx(rn,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),i.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),i.jsx("button",{onClick:()=>q&&p(q),className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),q&&o.length===0&&!c&&!d&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(Fs,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noAvailablePlugins")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noAvailablePluginsHint")})]}),o.length>0&&$e.length===0&&!c&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[i.jsx(br,{size:36,className:"mb-3 opacity-30"}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),$e.length>0&&i.jsx("div",{className:"space-y-3",children:$e.map(ce=>{const Ce=`${ce.name}@${ce.marketplace}`;return i.jsx(L8,{plugin:ce,isInstalled:ce.installed,isOperating:l.has(Ce),isExpanded:J===Ce,onInstall:Le=>he(ce,Le),onExpand:()=>ne(Ce),t:e},Ce)})})]}),y==="marketplaces"&&i.jsxs("div",{className:"space-y-3",children:[!L&&i.jsxs("button",{onClick:()=>E(!0),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary hover:border-text-primary/30 transition-colors",children:[i.jsx(Ot,{size:12}),e("plugins.addMarketplace")]}),L&&i.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[13px] font-medium",children:e("plugins.addMarketplace")}),i.jsx("button",{onClick:()=>{E(!1),D(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:i.jsx(at,{size:12})})]}),i.jsx("input",{type:"text",value:M,onChange:ce=>O(ce.target.value),placeholder:e("plugins.sourcePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),i.jsx("input",{type:"text",value:z,onChange:ce=>U(ce.target.value),placeholder:e("plugins.namePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),T&&i.jsx("div",{className:"text-accent-red text-[12px]",children:T}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{onClick:()=>{E(!1),D(null)},className:"px-3 py-1.5 rounded-lg text-[12px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")}),i.jsxs("button",{onClick:pe,disabled:!M.trim()||Q,className:"px-3 py-1.5 rounded-lg text-[12px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5",children:[Q&&i.jsx(He,{size:12,className:"animate-spin"}),e("plugins.add")]})]})]}),s&&r.length===0&&i.jsx("div",{className:"flex items-center justify-center py-6",children:i.jsx(He,{size:18,className:"animate-spin text-text-tertiary"})}),!s&&r.length===0&&!L&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(xa,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),r.length>0&&i.jsx("div",{className:"bg-bg-secondary rounded-xl border border-border-muted overflow-hidden",children:r.map((ce,Ce)=>i.jsxs("div",{className:`flex items-center justify-between px-4 py-3 ${Ce>0?"border-t border-border-muted":""}`,children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(xa,{size:14,className:"text-text-tertiary shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"text-[13px] font-medium truncate",children:ce.name}),ce.type&&i.jsx("div",{className:"text-[11px] text-text-tertiary",children:ce.type})]})]}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:P===ce.name?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>ae(ce.name),className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:e("plugins.removeMarketplace")}),i.jsx("button",{onClick:()=>H(null),className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")})]}):i.jsx("button",{onClick:()=>H(ce.name),className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors",title:e("plugins.removeMarketplace"),children:i.jsx(Oi,{size:13})})})]},ce.name))})]})]})})]})}function R8({plugin:e,isEnabled:t,isOperating:r,isExpanded:n,confirmUninstall:s,onToggle:a,onUninstall:l,onConfirmUninstall:o,onCancelUninstall:c,onExpand:d,t:u}){return i.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[i.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:d,children:[i.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:i.jsx(Fs,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[i.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&i.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),i.jsx("span",{className:`text-[10px] px-1.5 py-px rounded font-medium shrink-0 ${t?"bg-accent-green/15 text-accent-green":"bg-bg-tertiary text-text-tertiary"}`,children:u(t?"plugins.enabled":"plugins.disabled")})]}),e.description&&i.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${n?"":"line-clamp-2"}`,children:e.description}),i.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-text-tertiary",children:[i.jsx(xa,{size:10,className:"shrink-0"}),i.jsx("span",{children:e.marketplace}),e.installScope&&i.jsx("span",{className:"px-1.5 py-px rounded bg-bg-tertiary text-[10px] font-medium",children:u(`plugins.scope.${e.installScope}`)})]})]}),i.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:h=>h.stopPropagation(),children:r?i.jsx("div",{className:"w-[72px] flex justify-center",children:i.jsx(He,{size:16,className:"animate-spin text-text-tertiary"})}):s?i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("button",{onClick:l,className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:u("plugins.uninstall")}),i.jsx("button",{onClick:c,className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:u("plugins.cancel")})]}):i.jsxs(i.Fragment,{children:[i.jsxs("button",{onClick:e.canSwitchoff===!1?void 0:a,disabled:e.canSwitchoff===!1,className:`px-2.5 py-1.5 rounded-md text-[11px] font-medium transition-colors flex items-center gap-1 ${e.canSwitchoff===!1?"text-text-tertiary border border-border-muted cursor-not-allowed opacity-50":t?"text-text-secondary border border-border-muted hover:bg-bg-tertiary":"text-text-primary border border-border-muted hover:bg-bg-tertiary"}`,title:e.canSwitchoff===!1?u("plugins.policyCannotSwitchoff"):u(t?"plugins.disable":"plugins.enable"),children:[t?i.jsx(UE,{size:11}):i.jsx(tw,{size:11}),u(t?"plugins.disable":"plugins.enable")]}),i.jsx("button",{onClick:e.canRemove===!1?void 0:o,disabled:e.canRemove===!1,className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${e.canRemove===!1?"text-text-tertiary cursor-not-allowed opacity-30":"text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 opacity-0 group-hover:opacity-100"}`,title:e.canRemove===!1?u("plugins.policyCannotRemove"):u("plugins.uninstall"),children:i.jsx(Oi,{size:13})})]})})]}),n&&i.jsx(I1,{plugin:e,t:u})]})}function L8({plugin:e,isInstalled:t,isOperating:r,isExpanded:n,onInstall:s,onExpand:a,t:l}){return i.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[i.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:a,children:[i.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:i.jsx(Fs,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[i.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&i.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),t&&i.jsx("span",{className:"text-[10px] px-1.5 py-px rounded font-medium shrink-0 bg-accent-green/15 text-accent-green",children:l("plugins.installedLabel")})]}),e.description&&i.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${n?"":"line-clamp-2"}`,children:e.description}),i.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[i.jsx(xa,{size:10,className:"shrink-0"}),i.jsx("span",{children:e.marketplace})]})]}),i.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:o=>o.stopPropagation(),children:t?i.jsx("div",{className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-tertiary bg-bg-tertiary",children:l("plugins.installed")}):r?i.jsx("div",{className:"w-[72px] flex justify-center",children:i.jsx(He,{size:16,className:"animate-spin text-text-tertiary"})}):i.jsx(D8,{onInstall:s,t:l})})]}),n&&i.jsx(I1,{plugin:e,t:l})]})}function I1({plugin:e,t}){const r=e.source,n=typeof r=="object"&&r!==null?r.url:void 0,s=typeof r=="object"&&r!==null?r.source:typeof r=="string"?r:void 0,a="installScope"in e?e.installScope:void 0;return i.jsxs("div",{className:"border-t border-border-muted mx-5 px-0 py-3.5 space-y-2.5",children:[a&&i.jsx(Nn,{label:t("plugins.scope"),children:i.jsx("span",{className:"text-[12px] text-text-secondary",children:t(`plugins.scope.${a}`)})}),e.category&&i.jsx(Nn,{label:t("plugins.category"),children:i.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded bg-[#f5a623]/8 text-[#b8860b] font-medium",children:e.category})}),e.author&&i.jsxs(Nn,{label:t("plugins.author"),children:[i.jsx("span",{className:"text-[12px] text-text-primary font-medium",children:e.author.name}),e.author.email&&i.jsx("a",{href:`mailto:${e.author.email}`,className:"text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:l=>l.stopPropagation(),children:e.author.email}),e.author.url&&i.jsxs("a",{href:e.author.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:l=>l.stopPropagation(),children:[e.author.url,i.jsx(Ar,{size:9})]})]}),e.license&&i.jsx(Nn,{label:t("plugins.license"),children:i.jsx("span",{className:"text-[12px] text-text-secondary",children:e.license})}),e.homepage&&i.jsx(Nn,{label:t("plugins.homepage"),children:i.jsxs("a",{href:e.homepage,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:l=>l.stopPropagation(),children:[e.homepage,i.jsx(Ar,{size:10,className:"shrink-0 text-text-tertiary"})]})}),e.repository&&i.jsx(Nn,{label:t("plugins.repository"),children:i.jsxs("a",{href:e.repository,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:l=>l.stopPropagation(),children:[e.repository,i.jsx(Ar,{size:10,className:"shrink-0 text-text-tertiary"})]})}),s&&i.jsx(Nn,{label:t("plugins.source"),children:n?i.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:l=>l.stopPropagation(),children:[s,i.jsx(Ar,{size:10,className:"shrink-0 text-text-tertiary"})]}):i.jsx("span",{className:"text-[12px] text-text-secondary font-mono",children:s})}),e.keywords&&e.keywords.length>0&&i.jsx(Nn,{label:t("plugins.keywords"),children:i.jsx("div",{className:"flex flex-wrap gap-1",children:e.keywords.map(l=>i.jsx("span",{className:"text-[10px] px-1.5 py-px rounded bg-bg-tertiary text-text-tertiary",children:l},l))})}),e.features&&e.features.length>0&&i.jsx(Nn,{label:t("plugins.features"),children:i.jsx("ul",{className:"space-y-0.5",children:e.features.map((l,o)=>i.jsxs("li",{className:"text-[12px] text-text-secondary flex items-start gap-1.5",children:[i.jsx("span",{className:"text-text-tertiary shrink-0",children:"·"}),l]},o))})})]})}function Nn({label:e,children:t}){return i.jsxs("div",{className:"flex items-baseline gap-3",children:[i.jsx("span",{className:"text-[11px] text-text-tertiary w-12 shrink-0 text-right",children:e}),i.jsx("div",{className:"flex-1 min-w-0 flex items-baseline flex-wrap gap-1",children:t})]})}function D8({onInstall:e,t}){const[r,n]=C.useState(!1);return i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>n(!r),className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary transition-colors flex items-center gap-1",title:t("plugins.install"),children:[i.jsx(Bv,{size:11}),t("plugins.install")]}),r&&i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 bg-bg-primary border border-border-muted rounded-lg shadow-lg py-1 min-w-[220px]",children:[i.jsx("button",{onClick:()=>{e("user"),n(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.user")}),i.jsx("button",{onClick:()=>{e("project"),n(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.project")}),i.jsx("button",{onClick:()=>{e("project-local"),n(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.local")})]})]})}const M8=[{value:"minimal",labelKey:"settings.effort.minimal"},{value:"low",labelKey:"settings.effort.low"},{value:"medium",labelKey:"settings.effort.medium"},{value:"high",labelKey:"settings.effort.high"},{value:"xhigh",labelKey:"settings.effort.xhigh"},{value:"max",labelKey:"settings.effort.max"}],$8=[{titleKey:"settings.group.modelAndReasoning",items:[{key:"model",labelKey:"settings.item.model",descKey:"settings.item.model.desc",type:"text"},{key:"reasoningEffort",labelKey:"settings.item.reasoningEffort",descKey:"settings.item.reasoningEffort.desc",type:"select",options:M8},{key:"alwaysThinkingEnabled",labelKey:"settings.item.alwaysThinkingEnabled",type:"toggle"}]},{titleKey:"settings.group.behavior",items:[{key:"autoCompactEnabled",labelKey:"settings.item.autoCompactEnabled",type:"toggle"},{key:"includeCoAuthoredBy",labelKey:"settings.item.includeCoAuthoredBy",type:"toggle"},{key:"fileCheckpointingEnabled",labelKey:"settings.item.fileCheckpointingEnabled",descKey:"settings.item.fileCheckpointingEnabled.desc",type:"toggle"},{key:"promptSuggestionEnabled",labelKey:"settings.item.promptSuggestionEnabled",type:"toggle"},{key:"ignoreGitIgnore",labelKey:"settings.item.ignoreGitIgnore",descKey:"settings.item.ignoreGitIgnore.desc",type:"toggle"},{key:"deferToolLoading",labelKey:"settings.item.deferToolLoading",type:"toggle"},{key:"hookOutputCollapsed",labelKey:"settings.item.hookOutputCollapsed",type:"toggle"}]},{titleKey:"settings.group.memory",items:[{key:"memory.enabled",labelKey:"settings.item.memory.enabled",type:"toggle"},{key:"memory.autoMemoryEnabled",labelKey:"settings.item.memory.autoMemoryEnabled",descKey:"settings.item.memory.autoMemoryEnabled.desc",type:"toggle"}]},{titleKey:"settings.group.language",items:[{key:"language",labelKey:"settings.item.language",descKey:"settings.item.language.desc",type:"text"}]},{titleKey:"settings.group.advanced",items:[{key:"cleanupPeriodDays",labelKey:"settings.item.cleanupPeriodDays",type:"number"},{key:"imageHistoryRetainRounds",labelKey:"settings.item.imageHistoryRetainRounds",descKey:"settings.item.imageHistoryRetainRounds.desc",type:"number"},{key:"env",labelKey:"settings.item.env",descKey:"settings.item.env.desc",type:"json"}]},{titleKey:"settings.group.sandbox",items:[{key:"sandbox.enabled",labelKey:"settings.item.sandbox.enabled",descKey:"settings.item.sandbox.enabled.desc",type:"toggle"},{key:"sandbox.autoAllowBashIfSandboxed",labelKey:"settings.item.sandbox.autoAllowBashIfSandboxed",descKey:"settings.item.sandbox.autoAllowBashIfSandboxed.desc",type:"toggle"}]}];function O8(e,t){const r=t.split(".");let n=e;for(const s of r){if(n==null||typeof n!="object")return;n=n[s]}return n}function N1(){const{status:e,sessionId:t,currentModel:r,models:n,modes:s,currentMode:a}=er(),{info:l,fetch:o}=Or(),{mode:c,toggle:d}=Jt(),{t:u,tryT:h,locale:p,toggleLocale:m}=de(),[v,x]=C.useState(null),[f,b]=C.useState({}),g=C.useRef({}),[_,y]=C.useState(!1),[S,w]=C.useState({}),k=C.useRef({});C.useEffect(()=>{let I=!1;return y(!0),Promise.all([fetch("/api/v1/settings",{headers:ve()}).then(T=>{if(!T.ok)throw new Error(`Settings API: ${T.status}`);return T.json()}).then(T=>(T==null?void 0:T.data)??T??{}),fetch("/api/v1/settings?scope=user",{headers:ve()}).then(T=>{if(!T.ok)throw new Error(`User settings API: ${T.status}`);return T.json()}).then(T=>(T==null?void 0:T.data)??T??{})]).then(([T,D])=>{I||(b(T),g.current=D,y(!1))}).catch(T=>{console.error("Failed to load settings:",T),I||y(!1)}),()=>{I=!0}},[]),C.useEffect(()=>()=>{Object.values(k.current).forEach(clearTimeout)},[]),C.useEffect(()=>{l||o()},[l,o]);const A=C.useCallback((I,T)=>{navigator.clipboard.writeText(I).then(()=>{x(T),setTimeout(()=>x(null),1500)})},[]),N=async I=>{if($("model",I),t)try{await ze().setModel(t,I)}catch(T){console.error("Model change failed:",T)}},j=async I=>{if($("permissions.defaultMode",I),t)try{await ze().setMode(t,I)}catch(T){console.error("Mode change failed:",T)}},$=C.useCallback(async(I,T)=>{const D=I.split(".")[0];let R=T;if(I.includes(".")){const G=I.split("."),H={...g.current[D]??{}};let q=H;for(let B=1;B<G.length-1;B++)q[G[B]]=q[G[B]]?{...q[G[B]]}:{},q=q[G[B]];q[G[G.length-1]]=T,R=H}try{const G=await fetch(`/api/v1/settings/${D}?scope=user`,{method:"PUT",headers:ve({"Content-Type":"application/json"}),body:JSON.stringify({value:R})});G.ok||G.status===204?(I.includes(".")?(g.current={...g.current,[D]:R},b(P=>({...P,[D]:{...P[D]??{},...R}}))):(g.current={...g.current,[I]:T},b(P=>({...P,[I]:T}))),L(I,"success")):(console.error(`Failed to save setting "${I}": HTTP ${G.status}`),L(I,"error"))}catch(G){console.error(`Failed to save setting "${I}":`,G),L(I,"error")}},[]),L=C.useCallback((I,T)=>{w(D=>({...D,[I]:T})),k.current[I]&&clearTimeout(k.current[I]),k.current[I]=setTimeout(()=>{w(D=>{const R={...D};return delete R[I],R})},1500)},[]),E={disconnected:"bg-gray-400",connecting:"bg-accent-yellow animate-pulse",connected:"bg-accent-green",error:"bg-accent-red"}[e],M={connected:"connection.connected",connecting:"connection.connecting",disconnected:"connection.disconnected",error:"connection.error"},O=c==="light"?rw:c==="dark"?Xv:b2,z=u(c==="light"?"theme.light":c==="dark"?"theme.dark":"theme.system"),U=p==="system"?JA:Uv,Q=u(p==="zh"?"locale.zh":p==="en"?"locale.en":"locale.system");return i.jsx("div",{className:"settings-view",children:i.jsx("div",{className:"settings-content",children:i.jsxs("div",{className:"settings-sections",children:[i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("sidebar.connectionStatus")}),i.jsxs("div",{className:"settings-card",children:[i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.status")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2 h-2 rounded-full ${E}`}),i.jsx("span",{className:"settings-value",children:u(M[e]||"connection.disconnected")})]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.sessionId")}),i.jsx("span",{className:"settings-value font-mono text-[12px]",children:t?t.substring(0,12):u("sidebar.notConnected")})]})]})]}),i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.appearance")}),i.jsxs("div",{className:"settings-card",children:[i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.theme")}),i.jsxs("button",{onClick:d,className:"settings-toggle-btn",children:[i.jsx(O,{size:14,className:"text-accent-brand"}),i.jsx("span",{children:z})]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.language")}),i.jsxs("button",{onClick:m,className:"settings-toggle-btn",children:[i.jsx(U,{size:14,className:"text-accent-brand"}),i.jsx("span",{children:Q})]})]})]})]}),n.length>0&&i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.model")}),i.jsx("div",{className:"settings-card",children:i.jsx("select",{value:r,onChange:I=>N(I.target.value),className:"settings-select",children:n.map(I=>i.jsx("option",{value:I.id,children:I.name||I.id},I.id))})})]}),s.length>0&&i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.mode")}),i.jsx("div",{className:"settings-card",children:i.jsx("select",{value:a,onChange:I=>j(I.target.value),className:"settings-select",children:s.map(I=>i.jsx("option",{value:I.id,title:h(`mode.${I.id}.desc`)||I.description,children:h(`mode.${I.id}`)||I.name},I.id))})})]}),_?i.jsx("div",{className:"settings-group",children:i.jsx("span",{className:"settings-value",children:u("settings.loading")})}):$8.map(I=>i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u(I.titleKey)}),i.jsx("div",{className:"settings-card",children:I.items.map(T=>i.jsx(j8,{item:T,value:O8(f,T.key),feedback:S[T.key],onSave:$},T.key))})]},I.titleKey)),l&&i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.systemInfo")}),i.jsxs("div",{className:"settings-card",children:[i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.cwd")}),i.jsxs("button",{onClick:()=>A(l.cwd,"cwd"),className:"settings-copy-btn",title:l.cwd,children:[i.jsx("span",{className:"truncate cursor-pointer hover:underline hover:text-accent-brand",onClick:I=>{I.stopPropagation(),oh(l.cwd)},children:l.cwd}),v==="cwd"?i.jsx(Fn,{size:12,className:"shrink-0 text-accent-green"}):i.jsx(Ci,{size:12,className:"shrink-0 text-text-tertiary"})]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.os")}),i.jsxs("span",{className:"settings-value",children:[l.os," ",l.arch]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.nodeVersion")}),i.jsx("span",{className:"settings-value",children:l.nodeVersion})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.gatewayMode")}),i.jsx("span",{className:"settings-value capitalize",children:l.gatewayMode})]}),l.tunnelUrl&&i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.tunnelUrl")}),i.jsxs("button",{onClick:()=>A(l.tunnelUrl,"tunnel"),className:"settings-copy-btn",title:l.tunnelUrl,children:[i.jsx("span",{className:"truncate",children:l.tunnelUrl.replace(/^https?:\/\//,"")}),v==="tunnel"?i.jsx(Fn,{size:12,className:"shrink-0 text-accent-green"}):i.jsx(Ci,{size:12,className:"shrink-0 text-text-tertiary"})]})]})]})]})]})})})}function j8({item:e,value:t,feedback:r,onSave:n}){const{t:s}=de(),[a,l]=C.useState(""),o=C.useRef(null);C.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]),C.useEffect(()=>{e.type==="text"||e.type==="number"?l(t!=null?String(t):""):e.type==="json"&&l(t!=null?JSON.stringify(t,null,2):"")},[t,e.type]);const c=C.useCallback(()=>{n(e.key,!t)},[e.key,t,n]),d=C.useCallback(h=>{n(e.key,h||void 0)},[e.key,n]),u=C.useCallback(h=>{l(h),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{if(e.type==="number"){const p=Number(h);!isNaN(p)&&h.trim()!==""&&n(e.key,p)}else if(e.type==="json")try{const p=JSON.parse(h);n(e.key,p)}catch{}else n(e.key,h)},600)},[e.key,e.type,n]);return i.jsxs("div",{className:"settings-row",children:[i.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"settings-label",children:s(e.labelKey)}),r&&i.jsx("span",{className:`settings-save-feedback ${r==="success"?"success":"error"}`,children:s(r==="success"?"settings.saved":"settings.saveFailed")})]}),e.descKey&&i.jsx("span",{className:"settings-desc",children:s(e.descKey)})]}),i.jsxs("div",{className:"flex items-center shrink-0 ml-3",children:[e.type==="toggle"&&i.jsx("button",{className:`settings-toggle-switch ${t?"on":""}`,onClick:c}),e.type==="select"&&e.options&&i.jsxs("select",{value:t??"",onChange:h=>d(h.target.value),className:"settings-inline-select",children:[i.jsx("option",{value:"",children:"-"}),e.options.map(h=>i.jsx("option",{value:h.value,children:s(h.labelKey)},h.value))]}),e.type==="text"&&i.jsx("input",{type:"text",value:a,onChange:h=>u(h.target.value),placeholder:s("settings.notSet"),className:"settings-input"}),e.type==="number"&&i.jsx("input",{type:"number",value:a,onChange:h=>u(h.target.value),className:"settings-input",style:{width:80}}),e.type==="json"&&i.jsx("textarea",{value:a,onChange:h=>u(h.target.value),placeholder:"{}",className:"settings-input wide",rows:3,style:{width:"100%",resize:"vertical"}})]})]})}function vd(){return er.getState().sessionId??void 0}const B8=Ke((e,t)=>({tasks:[],loading:!1,error:null,fetchTasks:async()=>{const r=vd();if(r){e({loading:!0,error:null});try{const n=new URLSearchParams({sessionId:r}),s=await fetch(`/api/v1/scheduled-tasks?${n}`,{headers:ve()});if(!s.ok)throw new Error(`HTTP ${s.status}`);const a=await s.json(),l=a.data??a;e({tasks:l.tasks||[],loading:!1})}catch(n){console.error("[ScheduledTasks] Fetch error:",n),e({error:n.message,loading:!1})}}},createTask:async(r,n,s=!0,a=!1)=>{var o;const l=vd();if(l)try{const c=await fetch("/api/v1/scheduled-tasks",{method:"POST",headers:{"Content-Type":"application/json",...ve()},body:JSON.stringify({cron:r,prompt:n,recurring:s,durable:a,sessionId:l})});if(!c.ok){const d=await c.json().catch(()=>({}));throw new Error(((o=d.error)==null?void 0:o.message)||`HTTP ${c.status}`)}await t().fetchTasks()}catch(c){throw console.error("[ScheduledTasks] Create error:",c),e({error:c.message}),c}},deleteTask:async r=>{const n=vd();if(n)try{const s=new URLSearchParams({sessionId:n}),a=await fetch(`/api/v1/scheduled-tasks/${r}?${s}`,{method:"DELETE",headers:ve()});if(!a.ok&&a.status!==204)throw new Error(`HTTP ${a.status}`);await t().fetchTasks()}catch(s){throw console.error("[ScheduledTasks] Delete error:",s),e({error:s.message}),s}}})),P8=[{label:"5m",cron:"*/5 * * * *"},{label:"30m",cron:"*/30 * * * *"},{label:"1h",cron:"7 * * * *"},{label:"1d",cron:"3 9 * * *"},{label:"1w",cron:"3 9 * * 1"}];function F8({onSubmit:e,onCancel:t}){const{t:r}=de(),[n,s]=C.useState("*/5 * * * *"),[a,l]=C.useState(""),[o,c]=C.useState(!0),[d,u]=C.useState(!1),[h,p]=C.useState(!1),[m,v]=C.useState(null),x=async()=>{if(!(!n.trim()||!a.trim())){p(!0),v(null);try{await e(n.trim(),a.trim(),o,d),t()}catch(f){v(f.message||"Failed to create task")}finally{p(!1)}}};return i.jsxs("div",{className:"border border-accent-brand/30 rounded-xl p-4 bg-bg-secondary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:r("scheduled.create")}),i.jsx("button",{onClick:t,className:"p-1 rounded hover:bg-bg-secondary text-text-tertiary",children:i.jsx(at,{size:14})})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.cron")}),i.jsx("input",{type:"text",value:n,onChange:f=>s(f.target.value),placeholder:"*/5 * * * *",className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none font-mono"}),i.jsx("div",{className:"flex gap-1.5 mt-1.5",children:P8.map(f=>i.jsx("button",{onClick:()=>s(f.cron),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${n===f.cron?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-tertiary hover:text-text-secondary hover:border-border-default/80"}`,children:f.label},f.label))})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.prompt")}),i.jsx("textarea",{value:a,onChange:f=>l(f.target.value),placeholder:r("scheduled.promptPlaceholder"),rows:2,className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none resize-none"})]}),i.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[i.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:o,onChange:f=>c(f.target.checked),className:"rounded"}),r("scheduled.recurring")]}),i.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:f=>u(f.target.checked),className:"rounded"}),r("scheduled.durable")]})]}),m&&i.jsx("div",{className:"text-xs text-accent-red mb-2",children:m}),i.jsxs("button",{onClick:x,disabled:h||!n.trim()||!a.trim(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[i.jsx(Ot,{size:14}),r(h?"scheduled.creating":"scheduled.create")]})]})}function z8({task:e,onDelete:t}){const{t:r}=de(),[n,s]=C.useState(!1),a=async()=>{s(!0);try{await t(e.id)}finally{s(!1)}},l=e.durable||e.permanent;return i.jsxs("div",{className:"group flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default hover:border-accent-brand/30 transition-colors",children:[i.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.recurring?i.jsx(KE,{size:18,className:"text-accent-blue"}):i.jsx(nw,{size:18,className:"text-accent-yellow"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:e.humanSchedule}),i.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${e.recurring?"bg-accent-blue/10 text-accent-blue":"bg-accent-yellow/10 text-accent-yellow"}`,children:e.recurring?r("scheduled.recurring"):r("scheduled.oneShot")}),l&&i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent-green/10 text-accent-green",children:r("scheduled.durable")})]}),i.jsx("p",{className:"text-xs text-text-secondary truncate",title:e.prompt,children:e.prompt}),i.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-[10px] text-text-tertiary",children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(ps,{size:10}),"ID: ",e.id]}),e.lastFiredAt&&i.jsxs("span",{children:[r("scheduled.lastFired"),": ",new Date(e.lastFiredAt).toLocaleString()]})]})]}),i.jsx("button",{onClick:a,disabled:n,className:"flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-accent-red/10 text-text-tertiary hover:text-accent-red transition-all disabled:opacity-50",title:r("scheduled.delete"),children:i.jsx(Oi,{size:14})})]})}const U8=3e3;function R1(){const{t:e}=de(),{setMainView:t}=De(),{setExternalInput:r,sessionId:n}=er(),{tasks:s,loading:a,fetchTasks:l,createTask:o,deleteTask:c}=B8(),[d,u]=C.useState(!1);C.useEffect(()=>{l()},[l,n]);const[h,p]=C.useState([]),[m,v]=C.useState(!0),[x,f]=C.useState(null),[b,g]=C.useState(!1),[_,y]=C.useState(!1),S=C.useRef(n);S.current=n;const w=C.useRef(null),k=C.useCallback(()=>{w.current&&(clearInterval(w.current),w.current=null)},[]),A=C.useCallback(async()=>{const L=new URLSearchParams,E=S.current;E&&L.append("sessionId",E);const M=L.toString(),O=await fetch(`/api/v1/tasks/templates${M?"?"+M:""}`,{headers:ve()});if(!O.ok)throw new Error(`HTTP ${O.status}`);const z=await O.json(),U=z.data??z;return p(U.templates||[]),f(U.error||null),U.status},[]),N=C.useCallback(()=>{k(),w.current=setInterval(async()=>{try{const L=await A();L!=="loading"&&(k(),g(!1),L==="done"&&(y(!0),setTimeout(()=>y(!1),2e3)))}catch(L){k(),g(!1),f(L.message||"Failed to load templates")}},U8)},[A,k]);C.useEffect(()=>{let L=!1;return(async()=>{try{if(!S.current){L||v(!1);return}const E=await A();if(L)return;E==="loading"&&(g(!0),N())}catch(E){L||f(E.message)}finally{L||v(!1)}})(),()=>{L=!0,k()}},[A,N,k,n]);const j=C.useCallback(async()=>{g(!0),f(null),y(!1);try{const L=new URLSearchParams,E=S.current;E&&L.append("sessionId",E);const M=L.toString(),O=await fetch(`/api/v1/tasks/templates/refresh${M?"?"+M:""}`,{method:"POST",headers:ve()});if(!O.ok)throw new Error(`HTTP ${O.status}`);N()}catch(L){f(L.message||"Failed to trigger refresh"),g(!1)}},[N]),$=C.useCallback(L=>{r({text:L.command}),t("chat")},[r,t]);return i.jsx("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:i.jsxs("div",{className:"flex-1 overflow-y-auto",children:[i.jsx("div",{className:"border-b border-border-default",children:i.jsxs("div",{className:"px-6 py-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("scheduled.title")}),i.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("scheduled.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>l(),className:"p-2 rounded-lg border border-border-default text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-colors",title:e("tasks.refresh"),children:i.jsx(St,{size:14,className:a?"animate-spin":""})}),i.jsxs("button",{onClick:()=>u(!d),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm transition-colors ${d?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/30"}`,children:[i.jsx(Ot,{size:14}),e("scheduled.create")]})]})]}),d&&i.jsx("div",{className:"mb-3",children:i.jsx(F8,{onSubmit:o,onCancel:()=>u(!1)})}),a&&s.length===0?i.jsxs("div",{className:"py-8 text-center text-text-tertiary text-sm",children:[i.jsx(St,{size:16,className:"animate-spin mx-auto mb-2"}),e("scheduled.loading")]}):s.length===0?i.jsxs("div",{className:"py-8 text-center",children:[i.jsx(ps,{size:32,className:"mx-auto mb-2 text-text-tertiary opacity-30"}),i.jsx("p",{className:"text-sm text-text-tertiary",children:e("scheduled.empty")}),i.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:e("scheduled.emptyHint")})]}):i.jsx("div",{className:"space-y-2",children:s.map(L=>i.jsx(z8,{task:L,onDelete:c},L.id))})]})}),i.jsxs("div",{className:"px-6 py-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("tasks.title")}),i.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("tasks.subtitle")})]}),i.jsxs("button",{onClick:j,disabled:b,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${_?"border-green-500/50 text-green-500":b?"opacity-50 cursor-not-allowed border-border-default text-text-secondary":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,children:[_?i.jsx(Fn,{size:14}):i.jsx(St,{size:14,className:b?"animate-spin":""}),i.jsx("span",{children:e(_?"tasks.refreshed":"tasks.refresh")})]})]}),m&&!b&&i.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:i.jsx(bn,{size:"small",text:e("tasks.loading")})}),x&&!m&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[i.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"!"}),i.jsx("div",{className:"text-text-secondary text-sm mb-4",children:e("tasks.error")}),i.jsx("button",{onClick:j,className:"px-4 py-2 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:e("tasks.retry")})]}),!m&&h.length===0&&!x&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:[i.jsx(KA,{size:32,className:"mb-2 opacity-30"}),i.jsx("div",{className:"text-sm",children:e("tasks.empty")})]}),h.length>0&&i.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${b?"opacity-50 pointer-events-none":"opacity-100"}`,children:h.map(L=>{const E=H8(L.icon);return i.jsxs("div",{onClick:()=>$(L),className:"group flex items-center gap-4 px-4 py-3.5 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all cursor-pointer",children:[i.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-bg-secondary flex items-center justify-center group-hover:bg-accent-brand/10 transition-colors",children:i.jsx(E,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:L.title}),i.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:L.description})]})]},L.id)})})]})]})})}function H8(e){switch(e){case"Newspaper":return my;case"MessageSquare":return my;case"GitBranch":return gs;case"Package":return EE;case"FileText":return an;case"Zap":return pi;case"Clock":return ps;default:return ps}}function Lu({node:e,path:t}){const r=De(a=>a.setRatio),n=Ei(a=>a.cwd),s=C.useCallback(a=>{r(t,a)},[r,t]);return e.type==="leaf"?i.jsx(Pl,{paneId:e.paneId,initialCwd:n}):i.jsxs(lh,{direction:e.direction,ratio:e.ratio,onRatioChange:s,children:[i.jsx(Lu,{node:e.children[0],path:[...t,0]}),i.jsx(Lu,{node:e.children[1],path:[...t,1]})]})}function L1(){const e=De(t=>t.layout);return i.jsx("div",{className:"flex-1 w-full h-full min-h-0 overflow-hidden",children:i.jsx(Lu,{node:e,path:[]})})}function G8({isOpen:e,onClose:t,onImageSelect:r,onFileSelect:n,onNewChat:s,onHistory:a,mainView:l}){const{t:o,tryT:c}=de(),d=C.useRef(null),[u,h]=C.useState(null),[p,m]=C.useState(0),{sessionId:v,modes:x,currentMode:f,models:b,currentModel:g,thinkingEnabled:_,setCurrentMode:y,setCurrentModel:S,setThinkingEnabled:w}=er(),k=C.useCallback((T,D)=>c(`mode.${T}`)||D||T,[c]),A=C.useCallback((T,D)=>c(`mode.${T}.desc`)||D,[c]),N=C.useCallback(async()=>{if(!v)return;const T=!_;w(T);try{await ze().setConfigOption(v,"thought_level",T?"enabled":"disabled")}catch(D){w(!T),console.error("[BottomSheet] toggle thinking failed:",D)}},[v,_,w]),j=C.useCallback(async T=>{if(!v||T===f)return;const D=f;y(T);try{await ze().setMode(v,T)}catch(R){y(D),console.error("[BottomSheet] setMode failed:",R)}},[v,f,y]),$=C.useCallback(async T=>{const D=T.target.value;if(!v||D===g)return;const R=g;S(D);try{await ze().setModel(v,D)}catch(G){S(R),console.error("[BottomSheet] setModel failed:",G)}},[v,g,S]),L=C.useCallback(()=>{r(),t()},[r,t]),E=C.useCallback(()=>{n(),t()},[n,t]),M=[{type:"attachment",icon:i.jsx(Wv,{size:22}),label:o("input.menu.image"),action:L},{type:"attachment",icon:i.jsx(an,{size:22}),label:o("input.menu.file"),action:E},{type:"action",icon:i.jsx(Ot,{size:20}),label:o("chat.newChat"),action:s},{type:"action",icon:i.jsx(Gv,{size:20}),label:o("sidebar.chatHistory"),action:a},{type:"nav",view:"changes",icon:i.jsx(Ll,{size:20}),label:o("sidebar.changes")},{type:"nav",view:"tasks",icon:i.jsx(Gu,{size:20}),label:o("sidebar.nav.tasks")},{type:"nav",view:"terminal",icon:i.jsx(qs,{size:20}),label:o("sidebar.terminalMode")},{type:"nav",view:"plugins",icon:i.jsx(Fs,{size:20}),label:o("sidebar.nav.plugins")},{type:"nav",view:"settings",icon:i.jsx(Dl,{size:20}),label:o("sidebar.preferences")}].filter(T=>!(T.type==="action"&&!T.action)),O=8,z=Math.ceil(M.length/O),U=[];for(let T=0;T<z;T++)U.push(M.slice(T*O,(T+1)*O));C.useEffect(()=>{const T=d.current;if(!T)return;const D=()=>{const R=T.clientWidth;if(R>0){const G=Math.round(T.scrollLeft/R);m(G)}};return T.addEventListener("scroll",D,{passive:!0}),()=>T.removeEventListener("scroll",D)},[]);const Q=C.useCallback(T=>{const D=d.current;D&&D.scrollTo({left:T*D.clientWidth,behavior:"smooth"})},[]),I=C.useCallback(()=>{h(null)},[]);return e?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"bottom-sheet-inline",children:[(x.length>0||b.length>0)&&i.jsxs("div",{className:"bottom-sheet-selectors",children:[x.length>0&&i.jsxs("div",{className:"bottom-sheet-selector-row",children:[i.jsx("label",{className:"bottom-sheet-selector-label",children:o("input.modeSelector")}),i.jsx("div",{className:"bottom-sheet-selector-chips",children:x.map(T=>{const D=k(T.id,T.name),R=A(T.id,T.description);return i.jsx("button",{type:"button",onClick:()=>j(T.id),className:`bottom-sheet-chip ${f===T.id?"active":""}`,title:R,children:D},T.id)})})]}),b.length>0&&i.jsxs("div",{className:"bottom-sheet-selector-row bottom-sheet-model-row",children:[i.jsxs("button",{type:"button",onClick:N,className:"bottom-sheet-thinking-toggle",title:o("input.deepThinkingDesc"),children:[i.jsx("span",{className:"bottom-sheet-thinking-icon",children:"∞"}),i.jsx("span",{className:"bottom-sheet-thinking-label",children:o("input.deepThinking")}),i.jsx("span",{className:`bottom-sheet-switch ${_?"on":""}`,children:i.jsx("span",{className:"bottom-sheet-switch-knob"})})]}),i.jsxs("div",{className:"bottom-sheet-model-line",children:[i.jsx("label",{className:"bottom-sheet-selector-label",htmlFor:"bottom-sheet-model-select",children:o("input.modelSelector")}),i.jsx("select",{id:"bottom-sheet-model-select",className:"bottom-sheet-model-select",value:g,onChange:$,children:b.map(T=>i.jsx("option",{value:T.id,children:T.name},T.id))})]})]})]}),i.jsx("div",{ref:d,className:"bottom-sheet-scroll",children:U.map((T,D)=>i.jsx("div",{className:"bottom-sheet-page",children:i.jsx("div",{className:"bottom-sheet-grid",children:T.map((R,G)=>i.jsxs("button",{className:R.type==="nav"&&l===R.view?"active":"",onClick:()=>{var P;R.type==="attachment"||R.type==="action"?(P=R.action)==null||P.call(R):R.type==="nav"&&R.view&&h(R.view)},children:[R.icon,i.jsx("span",{children:R.label})]},G))})},D))}),z>1&&i.jsx("div",{className:"bottom-sheet-pagination",children:Array.from({length:z}).map((T,D)=>i.jsx("button",{className:`pagination-dot ${D===p?"active":""}`,onClick:()=>Q(D)},D))})]}),u&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"floating-panel-overlay",onClick:I}),i.jsxs("div",{className:"floating-panel-container",children:[i.jsx("div",{className:"floating-panel-header",children:i.jsx("button",{onClick:I,className:"floating-panel-close-btn",title:o("common.close"),children:i.jsx(at,{size:24})})}),i.jsxs("div",{className:"floating-panel-content",children:[u==="changes"&&i.jsx(V0,{}),u==="tasks"&&i.jsx(R1,{}),u==="terminal"&&i.jsx(L1,{}),u==="plugins"&&i.jsx(T1,{}),u==="settings"&&i.jsx(N1,{})]})]})]})]}):null}const lv=5,D1=10*1024*1024,ya=["image/jpeg","image/png","image/gif","image/webp"];let M1=0;function W8(e){return!ya.includes(e.type)||e.size>D1?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const n=r.result,s=n.split(",")[1]||"";t({id:`img-${++M1}`,dataUrl:n,data:s,mimeType:e.type})},r.onerror=()=>t(null),r.readAsDataURL(e)})}const q8=10,Q8=1*1024*1024,V8=new Set([".txt",".md",".markdown",".json",".jsonl",".yaml",".yml",".toml",".xml",".html",".htm",".css",".scss",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".cpp",".h",".hpp",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".gql",".env",".ini",".cfg",".conf",".properties",".csv",".tsv",".log",".dockerfile",".makefile",".cmake",".gitignore",".gitattributes",".editorconfig",".vue",".svelte",".astro"]);let K8=0;function $1(e){if(e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||e.type==="application/javascript")return!0;const t=e.name.toLowerCase(),r=t.lastIndexOf(".");if(r!==-1){const s=t.slice(r);if(V8.has(s))return!0}const n=t.split("/").pop()||t;return!!["makefile","dockerfile","cmakelists.txt","gemfile","rakefile","procfile"].includes(n)}function Y8(e){return!$1(e)||e.size>Q8?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const n=r.result;t({id:`file-${++K8}`,name:e.name,size:e.size,text:n,mimeType:e.type||"text/plain"})},r.onerror=()=>t(null),r.readAsText(e)})}function Z8(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function X8({onNavigate:e,onNewChat:t,onHistory:r,mainView:n,showBottomSheet:s=!1,setShowBottomSheet:a}){const l=C.useCallback(Y=>{a&&a(typeof Y=="function"?Y(s):Y)},[a,s]),[o,c]=C.useState(()=>window.innerWidth<=768),[d,u]=C.useState(""),[h,p]=C.useState([]),[m,v]=C.useState([]),[x,f]=C.useState(0),[b,g]=C.useState(!1),[_,y]=C.useState(null),[S,w]=C.useState(0),[k,A]=C.useState([]),[N,j]=C.useState(0),[$,L]=C.useState(null),E=C.useRef(null),M=C.useRef(null),O=C.useRef(null),z=C.useRef(null),U=C.useRef(null),Q=C.useRef(null),I=C.useRef(null),T=C.useRef(null),D=C.useRef(null),R=C.useRef(null),G=C.useRef(0),P=C.useRef(!1),H=C.useRef(!1),{sessionId:q,commands:B,thinkingEnabled:F,setThinkingEnabled:Z,promptSuggestion:J,setPromptSuggestion:te,externalInput:ne,setExternalInput:re,modes:me,currentMode:he,models:pe,currentModel:ae,setCurrentMode:ye,setCurrentModel:be}=er(),[le,_e]=C.useState(!1),[Te,$e]=C.useState(!1),{isAgentRunning:Ze,hasPendingInterruption:ce,timeline:Ce,addUserMessage:Le,addQueuedUserMessage:lt,setSessionEnd:jt,resolveInterruption:Qt}=$t(),{t:xe,tryT:Ne}=de();C.useEffect(()=>{if(ne!==null){if(typeof ne.text=="string"&&u(ne.text),ne.images!==void 0){const Y=ne.images.slice(0,lv).map(oe=>({id:`img-${++M1}`,dataUrl:oe.dataUrl,data:oe.data,mimeType:oe.mimeType}));p(Y)}re(null),te(null),requestAnimationFrame(()=>{var Y;(Y=E.current)==null||Y.focus()})}},[ne,re,te]);const ir=C.useCallback(async Y=>{const oe=Array.from(Y).filter(Be=>ya.includes(Be.type)&&Be.size<=D1);if(oe.length===0)return;f(Be=>Be+oe.length);const Xe=(await Promise.all(oe.map(W8))).filter(Be=>Be!==null);f(Be=>Math.max(0,Be-oe.length)),Xe.length>0&&p(Be=>{const Vt=lv-Be.length;return[...Be,...Xe.slice(0,Vt)]})},[]),Ys=C.useCallback(Y=>{p(oe=>oe.filter(Se=>Se.id!==Y))},[]),zr=C.useCallback(async Y=>{const oe=Array.from(Y),Xe=(await Promise.all(oe.map(Y8))).filter(Be=>Be!==null);Xe.length!==0&&v(Be=>{const Vt=q8-Be.length;return[...Be,...Xe.slice(0,Vt)]})},[]),vn=C.useCallback(Y=>{v(oe=>oe.filter(Se=>Se.id!==Y))},[]),_s=C.useCallback(Y=>{var oe;Y.preventDefault(),Y.stopPropagation(),G.current++,(oe=Y.dataTransfer)!=null&&oe.types.includes("Files")&&g(!0)},[]),so=C.useCallback(Y=>{Y.preventDefault(),Y.stopPropagation(),G.current--,G.current===0&&g(!1)},[]),io=C.useCallback(Y=>{Y.preventDefault(),Y.stopPropagation()},[]),Ur=C.useCallback(Y=>{var oe;if(Y.preventDefault(),Y.stopPropagation(),G.current=0,g(!1),(oe=Y.dataTransfer)!=null&&oe.files){const Se=Array.from(Y.dataTransfer.files),Xe=Se.filter(Vt=>ya.includes(Vt.type)),Be=Se.filter(Vt=>!ya.includes(Vt.type)&&$1(Vt));Xe.length>0&&ir(Xe),Be.length>0&&zr(Be)}},[ir,zr]),Zi=C.useCallback(Y=>{var Se;const oe=(Se=Y.clipboardData)==null?void 0:Se.files;oe&&oe.length>0&&Array.from(oe).some(Be=>ya.includes(Be.type))&&(Y.preventDefault(),ir(oe))},[ir]),Xi=C.useCallback(()=>{var Y;(Y=M.current)==null||Y.click()},[]),oc=C.useCallback(()=>{var Y;(Y=O.current)==null||Y.click()},[]),Gn=C.useCallback(Y=>{Y.target.files&&ir(Y.target.files),Y.target.value=""},[ir]),lc=C.useCallback(Y=>{Y.target.files&&zr(Y.target.files),Y.target.value=""},[zr]),ln=C.useMemo(()=>{const Y=d.trimStart();if(!Y.startsWith("/")||Y.includes(" "))return[];const oe=Y.substring(1).toLowerCase();return B.filter(Se=>{const Xe=Ne(`command.${Se.name}.description`)??Se.description;return Se.name.toLowerCase().includes(oe)||Se.description.toLowerCase().includes(oe)||Xe.toLowerCase().includes(oe)}).slice(0,8)},[d,B,Ne]),Wn=ln.length>0;C.useEffect(()=>{w(0)},[ln.length]),C.useEffect(()=>{if(Wn&&z.current){const Y=z.current.children[S];Y==null||Y.scrollIntoView({block:"nearest"})}},[S,Wn]);const Ji=C.useMemo(()=>{if($===null)return null;const Y=d.substring($+1),oe=Y.search(/\s/),Se=oe===-1?Y:Y.substring(0,oe);return oe===0?null:Se},[d,$]),qn=Ji!==null&&k.length>0,ea=C.useRef(null);C.useEffect(()=>{if(Ji===null){A([]);return}return ea.current&&clearTimeout(ea.current),ea.current=setTimeout(async()=>{try{const Y=new URLSearchParams;Ji&&Y.set("query",Ji),Y.set("limit","15");const oe=await fetch(`/api/v1/fs/search?${Y.toString()}`,{headers:ve()});if(oe.ok){const Se=await oe.json();A(Se.items||[]),j(0)}else A([])}catch{A([])}},150),()=>{ea.current&&clearTimeout(ea.current)}},[Ji]),C.useEffect(()=>{if(qn&&U.current){const Y=U.current.children[N];Y==null||Y.scrollIntoView({block:"nearest"})}},[N,qn]);const cc=C.useRef(!1),dc=C.useCallback(Y=>{if($===null)return;const oe=d.substring(0,$),Se=d.substring($+1),Xe=Se.search(/\s/),Be=Xe===-1?"":Se.substring(Xe),cn=Be.length===0||!/^\s/.test(Be)?" ":"",vs=`${oe}@${Y.path}${cn}${Be}`,ta=oe.length+1+Y.path.length+cn.length;u(vs),A([]),L(null),cc.current=!0,requestAnimationFrame(()=>{const Zs=E.current;Zs&&(Zs.focus(),Zs.setSelectionRange(ta,ta))})},[d,$]);C.useEffect(()=>{const Y=()=>c(window.innerWidth<=768);return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),C.useEffect(()=>{var Y;!o&&!Ze&&((Y=E.current)==null||Y.focus())},[o,Ze]),C.useEffect(()=>{const Y=E.current;if(Y){Y.style.height="auto";const oe=window.innerHeight*.2,Se=Math.min(Y.scrollHeight,oe);Y.style.height=`${Se}px`,Y.style.overflowY=Y.scrollHeight>oe?"auto":"hidden"}},[d]);const uc=C.useCallback(Y=>{var oe;u(`/${Y.name} `),(oe=E.current)==null||oe.focus()},[]),xs=C.useCallback(async Y=>{var Jb;const oe=(Y??d).trim(),Se=h.length>0,Xe=m.length>0;if(!oe&&!(Se||Xe)||!q||ce)return;u(""),te(null);const Vt=[...h],cn=[...m];p([]),v([]);const vs=Vt.length>0?Vt.map(ft=>({data:ft.data,mimeType:ft.mimeType})):void 0,ta=cn.length>0?cn.map(ft=>({name:ft.name,text:ft.text,mimeType:ft.mimeType})):void 0,Zs=cn.length>0?cn.map(ft=>({name:ft.name,size:ft.size,mimeType:ft.mimeType})):void 0;if((Jb=E.current)==null||Jb.blur(),Ze)lt(oe,vs,Zs),ze().prompt(q,oe,vs,ta).catch(ft=>{console.error("Queued prompt failed:",ft)});else{if(H.current)return;H.current=!0,Le(oe,vs,Zs);try{const ft=await ze().prompt(q,oe,vs,ta);jt(ft.stopReason,ft.errorMessage,ft.errorCategory)}catch(ft){console.error("Prompt failed:",ft),jt("error",ft instanceof Error?ft.message:xe("input.promptFailed"))}finally{H.current=!1}}},[d,h,m,q,Ze,ce,Le,lt,jt,te,xe]),F1=C.useCallback(async()=>{if(q)try{const Y=ze(),oe=Ce.filter(Se=>Se.type==="interruption"&&!Se.resolved);for(const Se of oe)if(Se.type==="interruption")try{await Y.respondToInterruption(q,Se.id,"deny",Se.toolCallId),Qt(Se.id,"deny")}catch{}await Y.cancel(q)}catch(Y){console.error("Cancel failed:",Y)}},[q,Ce,Qt]),z1=C.useCallback(()=>{P.current=!0},[]),U1=C.useCallback(()=>{P.current=!1},[]),H1=C.useCallback(Y=>{Y.preventDefault(),y({x:Y.clientX,y:Y.clientY})},[]),G1=C.useCallback(()=>{const Y=E.current;if(!Y)return;const oe=Y.selectionStart??d.length,Se=Y.selectionEnd??oe,Xe=d.slice(0,oe)+`
1030
+ ${d.date}`,children:[i.jsx("span",{className:"scm-graph-dot",style:{background:iv[u%iv.length]}}),i.jsx("span",{className:"scm-graph-msg",children:d.message}),i.jsx("span",{className:"scm-graph-time",children:c(d.date)})]},d.hash))]})]})}function E1(){const{t:e}=de(),{isGitRepo:t,loading:r,files:n,currentBranch:s,ahead:a,behind:l,pushing:o,pulling:c,branches:d,branchesLoading:u,lastOperationMessage:h,refresh:p,loadBranches:m,stageFile:v,unstageFile:x,stageAll:f,unstageAll:b,discardFile:g,discardAll:_,push:y,pull:S,switchBranch:w,createBranch:k,clearOperationMessage:A}=Bn(),N=mt(D=>D.openFile),j=yt(D=>D.scmViewMode),$=yt(D=>D.setScmViewMode),[L,E]=C.useState(!0),[M,O]=C.useState(!0);C.useEffect(()=>{p(),Bn.getState().startWatching()},[p]),C.useEffect(()=>{if(h){const D=setTimeout(A,3e3);return()=>clearTimeout(D)}},[h,A]);const z=C.useCallback(D=>{w(D)},[w]),U=C.useCallback(async(D,R)=>{yt.getState().bottomPanelMaximized&&yt.setState({bottomPanelMaximized:!1});try{const G=await h1(D,R);mt.getState().openDiffTab(D,{oldText:G.oldText,newText:G.newText,staged:R})}catch{}},[]),Q=C.useCallback(D=>{N(D)},[N]),I=n.filter(D=>D.staged),T=n.filter(D=>!D.staged);return t?i.jsxs("div",{className:"scm-panel",children:[i.jsxs("div",{className:"scm-header",children:[i.jsx("span",{className:"scm-header-title",children:e("ide.scm.title")}),i.jsxs("div",{className:"scm-header-actions",children:[i.jsx("button",{className:`scm-icon-btn ${j==="list"?"active":""}`,onClick:()=>$("list"),title:e("ide.listView"),children:i.jsx(Yv,{size:14})}),i.jsx("button",{className:`scm-icon-btn ${j==="tree"?"active":""}`,onClick:()=>$("tree"),title:e("ide.treeView"),children:i.jsx(sw,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:p,disabled:r,title:e("ide.refresh"),children:i.jsx(St,{size:14,className:r?"animate-spin":""})})]})]}),i.jsxs("div",{className:"scm-scroll",children:[i.jsxs("div",{className:"scm-section",children:[i.jsxs("button",{className:"scm-section-header",onClick:()=>E(D=>!D),children:[L?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{children:e("ide.scm.repositories")})]}),L&&i.jsx(p1,{currentBranch:s,branches:d,branchesLoading:u,onSwitch:z,onCreate:k,onLoadBranches:m,actions:i.jsxs(i.Fragment,{children:[(a>0||l>0)&&i.jsxs("span",{className:"scm-branch-sync",children:[a>0&&i.jsxs("span",{children:["↑",a]}),l>0&&i.jsxs("span",{children:["↓",l]})]}),i.jsxs("div",{className:"scm-branch-actions",children:[i.jsx("button",{className:"scm-icon-btn",onClick:S,disabled:c,title:e("ide.scm.pull"),children:c?i.jsx(He,{size:14,className:"animate-spin"}):i.jsx(jv,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:y,disabled:o,title:e("ide.scm.push"),children:o?i.jsx(He,{size:14,className:"animate-spin"}):i.jsx(Jo,{size:14})}),i.jsx("button",{className:"scm-icon-btn",onClick:p,disabled:r,title:e("ide.refresh"),children:i.jsx(St,{size:12,className:r?"animate-spin":""})})]})]})})]}),i.jsxs("div",{className:"scm-section",children:[i.jsxs("button",{className:"scm-section-header",onClick:()=>O(D=>!D),children:[M?i.jsx(rt,{size:14}):i.jsx(We,{size:14}),i.jsx("span",{children:e("ide.scm.changes")}),i.jsx("span",{className:"scm-section-count",children:n.length})]}),h&&i.jsx("div",{className:"scm-operation-msg",children:h}),M&&i.jsxs(i.Fragment,{children:[I.length>0&&i.jsx(sv,{files:I,viewMode:j,sectionTitle:e("ide.scm.stagedChanges"),sectionCount:I.length,sectionActions:i.jsx("button",{className:"scm-file-action-btn",onClick:()=>b(),title:e("ide.scm.unstageAll"),children:i.jsx(Pa,{size:13})}),onUnstage:x,onSelect:D=>U(D,!0),onOpenFile:Q}),T.length>0&&i.jsx(sv,{files:T,viewMode:j,sectionTitle:e("ide.scm.changes"),sectionCount:T.length,sectionActions:i.jsxs(i.Fragment,{children:[i.jsx("button",{className:"scm-file-action-btn",onClick:()=>_(),title:e("ide.scm.discardAll"),children:i.jsx(zs,{size:13})}),i.jsx("button",{className:"scm-file-action-btn",onClick:()=>f(),title:e("ide.scm.stageAll"),children:i.jsx(Ot,{size:13})})]}),onStage:v,onDiscard:g,onSelect:D=>U(D,!1),onOpenFile:Q}),n.length===0&&!r&&i.jsxs("div",{className:"scm-empty",children:[i.jsx(Fn,{size:20,strokeWidth:1.5,style:{opacity:.3}}),i.jsx("span",{children:e("ide.scm.noChanges")})]})]})]}),i.jsx(b8,{})]})]}):i.jsxs("div",{className:"scm-panel",children:[i.jsx("div",{className:"scm-header",children:i.jsx("span",{className:"scm-header-title",children:e("ide.scm.title")})}),i.jsxs("div",{className:"ide-panel-placeholder",children:[i.jsx(gs,{size:32,strokeWidth:1,style:{opacity:.2}}),i.jsx("div",{className:"ide-panel-placeholder-text",children:e("ide.scm.notGitRepo")})]})]})}function y8({activePanel:e,onMenuClick:t}){return i.jsxs("div",{className:"ide-side-panel-content",children:[e==="explorer"&&i.jsx(y1,{onMenuClick:t}),e==="search"&&i.jsx(w1,{}),e==="source-control"&&i.jsx(E1,{})]})}function _8({onMenuClick:e,activeTab:t,mdToggleBtn:r,cursorInfo:n,imageInfo:s,previewZoom:a,isMarkdownSource:l,quickOpenVisible:o,setQuickOpenVisible:c,onContentChange:d,onSave:u,onCursorChange:h,onImageInfo:p,onZoomChange:m}){const{t:v}=de(),{rootPath:x,openFile:f,revealInTree:b}=mt(),{activePanel:g,sidePanelWidth:_,sidePanelCollapsed:y,setSidePanelWidth:S,setSidePanelCollapsed:w,bottomPanelHeight:k,bottomPanelCollapsed:A,bottomPanelMaximized:N,setBottomPanelHeight:j,setBottomPanelCollapsed:$,toggleBottomPanelMaximize:L}=yt(),E=tv({direction:"horizontal",initialSize:_,minSize:160,maxSize:600,collapsible:!0,defaultCollapsed:y,onResize:S,onCollapse:w}),M=tv({direction:"vertical",initialSize:k,minSize:140,maxSize:typeof window<"u"?Math.max(300,window.innerHeight-80):500,collapsible:!0,defaultCollapsed:A,reverse:!0,onResize:j,onCollapse:$,onMaximize:L,maximizeThreshold:.85}),O=Bn(D=>D.files.length);C.useEffect(()=>(Bn.getState().refresh(),Bn.getState().startWatching(),()=>{Bn.getState().stopWatching()}),[]);const z=typeof navigator<"u"&&navigator.platform.includes("Mac"),U=()=>t?t.viewMode==="diff"&&t.diffData?i.jsx("div",{className:"editor-container",children:i.jsx(Ps,{path:t.path,oldText:t.diffData.oldText,newText:t.diffData.newText})}):t.viewMode==="editor"||l?i.jsx("div",{className:"editor-container",children:i.jsx(u1,{path:t.path,content:t.content,language:t.language,onContentChange:d,onSave:u,minimap:!0,onCursorChange:h})}):i.jsx(g1,{path:t.path,name:t.name,content:t.content,viewMode:t.viewMode,onImageInfo:p,onZoomChange:m}):i.jsx(x8,{isMac:z,t:v}),Q=o&&x&&i.jsx(v1,{isOpen:o,onClose:()=>c(!1),onSelect:D=>{f(D),c(!1)},rootPath:x}),I=g&&!E.collapsed,T=!M.collapsed;return i.jsxs("div",{className:"ide-layout",children:[Q,i.jsxs("div",{className:"ide-layout-row",ref:E.containerRef,children:[i.jsx(d8,{gitFileCount:O}),I&&i.jsxs("div",{className:"ide-side-panel",style:{width:E.size},children:[i.jsx(y8,{activePanel:g,onMenuClick:e}),i.jsx("div",{...E.sashProps})]}),i.jsxs("div",{className:"ide-main-area",ref:M.containerRef,children:[!N&&i.jsxs("div",{className:"ide-editor-area",style:{flex:T?void 0:1,height:T?`calc(100% - ${M.size}px)`:"100%"},children:[i.jsx(f1,{actions:r}),t&&x&&i.jsx(o8,{filePath:t.path,rootPath:x,onSegmentClick:b,onOpenFile:f}),i.jsx("div",{className:"ide-editor-content",onDragOver:D=>{D.preventDefault(),D.dataTransfer.dropEffect="copy"},onDrop:D=>{D.preventDefault();const R=D.dataTransfer.getData("application/x-file-paths")||D.dataTransfer.getData("text/plain");if(R){try{const G=JSON.parse(R),P=Array.isArray(G)?G:[R];P.length>0&&f(P[0])}catch{R&&f(R)}setTimeout(()=>{const G=document.querySelector(".ide-editor-content .monaco-editor textarea");G==null||G.focus()},100)}},children:U()})]}),T&&i.jsxs(i.Fragment,{children:[!N&&i.jsx("div",{...M.sashProps}),i.jsx("div",{className:"ide-bottom-panel-wrap",style:{height:N?"100%":M.size},children:i.jsx(_1,{})})]})]})]}),i.jsx("div",{className:"ide-statusbar-drag-zone",onPointerDown:M.sashProps.onPointerDown,onDoubleClick:M.sashProps.onDoubleClick,children:i.jsx(m1,{language:(t==null?void 0:t.language)||"",cursorLine:n.line,cursorColumn:n.col,selectedCount:n.selectedChars,selectedLines:n.selectedLines,viewMode:t?l?"editor":t.viewMode:"editor",imageInfo:s,zoom:a})})]})}function x8({isMac:e,t}){const r=C.useRef(null),[n,s]=C.useState(!1);return C.useEffect(()=>{const a=r.current;if(!a)return;const l=new ResizeObserver(o=>{for(const c of o)s(c.contentRect.height<300)});return l.observe(a),()=>l.disconnect()},[]),i.jsxs("div",{className:"editor-empty",ref:r,children:[i.jsx("div",{className:"ide-empty-icon",children:i.jsx("img",{src:x1,alt:"CodeBuddy",width:"64",height:"64",style:{opacity:.15,filter:"grayscale(1)"}})}),!n&&i.jsxs("div",{className:"editor-empty-shortcuts",children:[i.jsxs("div",{className:"editor-empty-hint",children:[i.jsxs("kbd",{children:[e?"⌘":"Ctrl","+P"]}),i.jsx("span",{children:t("editor.quickOpen")})]}),i.jsxs("div",{className:"editor-empty-hint",children:[i.jsxs("kbd",{children:[e?"⌘":"Ctrl","+B"]}),i.jsx("span",{children:t("ide.toggleSidebar")||"Toggle Sidebar"})]}),i.jsxs("div",{className:"editor-empty-hint",children:[i.jsxs("kbd",{children:[e?"⌃":"Ctrl","+`"]}),i.jsx("span",{children:t("ide.toggleTerminal")||"Toggle Terminal"})]})]})]})}function v8(){const{t:e}=de(),t=yt(a=>a.activeMobilePanel),r=yt(a=>a.setActiveMobilePanel),n=Bn(a=>a.files.length),s=[{id:"explorer",icon:i.jsx(zv,{size:20,strokeWidth:1.5}),label:e("ide.explorer")||"Explorer"},{id:"search",icon:i.jsx(br,{size:20,strokeWidth:1.5}),label:e("ide.search")||"Search"},{id:"source-control",icon:i.jsx(gs,{size:20,strokeWidth:1.5}),label:e("ide.sourceControl")||"Source Control",badge:n},{id:"terminal",icon:i.jsx(qs,{size:20,strokeWidth:1.5}),label:e("ide.terminal")||"Terminal"}];return i.jsx("div",{className:"mobile-tab-bar",children:s.map(a=>i.jsxs("button",{className:`mobile-tab-bar-btn ${t===a.id?"active":""}`,onClick:()=>r(a.id),children:[i.jsxs("span",{className:"mobile-tab-bar-icon",children:[a.icon,a.badge!=null&&a.badge>0&&i.jsx("span",{className:"mobile-tab-bar-badge",children:a.badge>99?"99+":a.badge})]}),i.jsx("span",{className:"mobile-tab-bar-label",children:a.label})]},a.id))})}const w8=1e3;function av({onMenuClick:e}){const{t}=de(),{tabs:r,activeTabId:n,updateTabContent:s,saveTab:a,closeTab:l}=mt(),{setRootPath:o,openFile:c,rootPath:d}=mt(),[u,h]=C.useState(!1),p=yt(P=>P.toggleBottomPanel),[m,v]=C.useState(()=>window.innerWidth<768),[x,f]=C.useState(!1),b=C.useRef("");C.useEffect(()=>{const P=async()=>{if(ah()!=="editor")return;const q=hl(),B=q.get("path");if(!B)return;const F=q.get("line"),Z=q.get("col"),J=`${B}:${F}:${Z}`;if(J===b.current)return;if(b.current=J,await $R(B)==="directory")await o(B);else{const ne=B.substring(0,B.lastIndexOf("/"));ne&&await o(ne);const re=F?parseInt(F,10):void 0,me=re?{line:re,col:Z?parseInt(Z,10):1,query:""}:void 0;c(B,void 0,me)}};P();const H=()=>P();return window.addEventListener("hashchange",H),()=>window.removeEventListener("hashchange",H)},[]),C.useEffect(()=>{const P=window.matchMedia("(min-width: 768px)"),H=q=>{v(!q.matches),q.matches&&f(!1)};return P.addEventListener("change",H),()=>P.removeEventListener("change",H)},[]),C.useEffect(()=>{m&&n&&f(!0)},[m,n,r.length]);const g=mt(P=>P.pendingReveal);C.useEffect(()=>{m&&g&&n&&f(!0)},[m,g,n]);const _=r.find(P=>P.id===n)||null,y=C.useRef(),S=C.useCallback(P=>{if(!n)return;s(n,P),clearTimeout(y.current);const H=n;y.current=setTimeout(()=>{const q=mt.getState().tabs.find(B=>B.id===H);!q||!q.isDirty||a(H)},w8)},[n,s,a]);C.useEffect(()=>()=>clearTimeout(y.current),[]),C.useEffect(()=>{const P=H=>{const q=H.metaKey||H.ctrlKey;if(q&&H.key==="p"&&!H.shiftKey&&(H.preventDefault(),h(!0)),q&&H.key==="w"&&!H.shiftKey&&(H.preventDefault(),n&&l(n)),q&&H.key==="b"&&!H.shiftKey){H.preventDefault();const B=yt.getState();B.setSidePanelCollapsed(!B.sidePanelCollapsed)}q&&H.key==="`"&&(H.preventDefault(),p())};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[n,l,p]);const w=C.useCallback(()=>{clearTimeout(y.current),n&&a(n)},[n,a]),[k,A]=C.useState({line:1,col:1,selectedChars:0,selectedLines:0}),N=C.useCallback((P,H,q,B)=>{A({line:P,col:H,selectedChars:q,selectedLines:B})},[]),[j,$]=C.useState(null),[L,E]=C.useState(1),[M,O]=C.useState(new Set),z=(_==null?void 0:_.viewMode)==="markdown"&&M.has(_.id),U=C.useCallback(()=>{n&&O(P=>{const H=new Set(P);return H.has(n)?H.delete(n):H.add(n),H})},[n]),Q=(_==null?void 0:_.viewMode)==="markdown"?z?i.jsx("button",{className:"editor-action-btn",onClick:U,title:t("editor.preview"),children:i.jsx(Pu,{size:16})}):i.jsx("button",{className:"editor-action-btn",onClick:U,title:t("editor.source"),children:i.jsx(Rl,{size:16})}):null,I=C.useCallback(()=>{const P=new URLSearchParams(window.location.search);P.set("standalone","1"),window.open(`#/editor?${P.toString()}`,"_blank","noopener,noreferrer")},[]),T=i.jsxs(i.Fragment,{children:[Q,i.jsx("button",{className:"editor-action-btn",onClick:I,title:t("editor.openInNewWindow"),children:i.jsx(Ar,{size:16})})]}),D=yt(P=>P.activeMobilePanel),R=yt(P=>P.createBottomTerminal),G=yt(P=>P.bottomTerminals);if(C.useEffect(()=>{m&&D==="terminal"&&G.length===0&&R()},[m,D,G.length,R]),m){const P=u&&d&&i.jsx(v1,{isOpen:u,onClose:()=>h(!1),onSelect:q=>{c(q),h(!1)},rootPath:d}),H=_?_.viewMode==="editor"||z?i.jsx("div",{className:"editor-container",children:i.jsx(u1,{path:_.path,content:_.content,language:_.language,onContentChange:S,onSave:w,minimap:!1,onCursorChange:N})}):i.jsx(g1,{path:_.path,name:_.name,content:_.content,viewMode:_.viewMode,onImageInfo:$,onZoomChange:E}):null;return i.jsxs("div",{className:"editor-view editor-view-mobile",children:[P,i.jsxs("div",{className:"mobile-panel-content",children:[D==="explorer"&&i.jsx("div",{className:"editor-sidebar editor-sidebar-mobile",children:i.jsx(y1,{onMenuClick:e})}),D==="search"&&i.jsx(w1,{}),D==="source-control"&&i.jsx(E1,{}),D==="terminal"&&i.jsx("div",{className:"mobile-terminal-panel",children:i.jsx(_1,{})})]}),i.jsx("div",{className:`editor-mobile-panel ${x?"open":""}`,children:i.jsxs("div",{className:"editor-main",children:[i.jsxs("div",{className:"editor-mobile-header",children:[i.jsx("button",{className:"editor-mobile-back",onClick:()=>f(!1),children:i.jsx(Mi,{size:18})}),i.jsx("div",{className:"editor-mobile-tabs-wrap",children:i.jsx(f1,{actions:T})})]}),H,_&&i.jsx(m1,{language:_.language,cursorLine:k.line,cursorColumn:k.col,selectedCount:k.selectedChars,selectedLines:k.selectedLines,viewMode:z?"editor":_.viewMode,imageInfo:j,zoom:L})]})}),i.jsx(v8,{})]})}return i.jsx("div",{className:"editor-view",children:i.jsx(_8,{onMenuClick:e,activeTab:_,editorContent:null,mdToggleBtn:T,cursorInfo:k,imageInfo:j,previewZoom:L,isMarkdownSource:z,quickOpenVisible:u,setQuickOpenVisible:h,onContentChange:S,onSave:w,onCursorChange:N,onImageInfo:$,onZoomChange:E})})}class Kt extends C.Component{constructor(r){super(r);fe(this,"handleRetry",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,n){console.error(`[ErrorBoundary${this.props.viewName?` - ${this.props.viewName}`:""}]`,r,n)}render(){var r;return this.state.hasError?i.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:i.jsxs("div",{className:"text-center max-w-md",children:[i.jsx("div",{className:"text-[48px] mb-4 text-text-tertiary",children:"!"}),i.jsx("h2",{className:"text-text-primary text-[16px] font-semibold mb-2",children:this.props.errorTitle||"Something went wrong"}),i.jsx("p",{className:"text-text-tertiary text-[13px] mb-4 break-words",children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),i.jsx("button",{onClick:this.handleRetry,className:"px-6 py-2 bg-accent-brand text-bg-primary rounded-lg text-[13px] font-medium hover:opacity-90 active:scale-95 transition-all",children:this.props.retryLabel||"Retry"})]})}):this.props.children}}function S8(e){return!Number.isFinite(e)||e<0?"0":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function k8(e,t,r,n){const s=Math.max(1,Math.round(e/1e3)),a=n(t===1?"goal.recap.stats.turn":"goal.recap.stats.turns"),l=n(r===1?"goal.recap.stats.token":"goal.recap.stats.tokens");return`${s}s · ${t} ${a} · ${S8(r)} ${l}`}function C8(){const e=$t(a=>a.goalRecap),t=$t(a=>a.dismissGoalRecap),{t:r}=de();C.useEffect(()=>{if(!e)return;const a=l=>{l.key==="Escape"&&(l.preventDefault(),t())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,t]);const n=C.useCallback(()=>t(),[t]),s=C.useMemo(()=>A8(e,r),[e,r]);return e?i.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:n}),i.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"goal-recap-title",className:"relative bg-bg-card border border-border-default rounded-xl shadow-2xl w-full max-w-[480px] mx-4 overflow-hidden",children:[i.jsx("div",{className:"px-5 pt-5 pb-4 flex flex-col gap-3",children:s}),i.jsxs("div",{className:"px-5 pb-4 pt-2 border-t border-border-default text-text-tertiary text-[12px]",children:[i.jsx("span",{className:"text-text-secondary",children:r("goal.recap.footer.setAnother")}),i.jsx("span",{children:r("goal.recap.footer.toSetAnother")}),i.jsx("span",{className:"text-text-secondary",children:"Esc"}),i.jsxs("span",{children:[" ",r("goal.recap.footer.escDismiss")]})]})]})]}):null}function A8(e,t){if(!e)return null;if(e.active)return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Nd,{size:18,className:"text-accent-brand"}),i.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.active")})]}),i.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed",children:[t("goal.progress.condition"),": ",e.active.condition]})]});if(e.latest){const{ok:r,reason:n,condition:s,durationMs:a,turnCount:l,tokenDelta:o}=e.latest,c=r?Nl:ki,d=r?"text-accent-green":"text-accent-red",u=t(r?"goal.recap.achieved":"goal.recap.impossible"),h=k8(a,l,o,t);return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(c,{size:18,className:d}),i.jsx("h3",{id:"goal-recap-title",className:`text-[15px] font-semibold ${d}`,children:u})]}),i.jsx("div",{className:"text-text-secondary text-[12px]",children:h}),i.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed mt-2",children:[t("goal.progress.condition"),": ",s]}),n?i.jsxs("div",{className:"text-text-tertiary text-[12px] break-words leading-relaxed",children:[t("goal.progress.reason"),": ",n]}):null]})}return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Nd,{size:18,className:"text-text-tertiary"}),i.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.empty.title")})]}),i.jsx("div",{className:"text-text-secondary text-[13px] leading-relaxed",children:t("goal.recap.empty.hint")}),i.jsx("div",{className:"text-text-tertiary text-[12px] leading-relaxed",children:t("goal.recap.empty.example")})]})}function E8(e,t){const n=Date.now()-e,s=Math.floor(n/6e4),a=Math.floor(n/36e5),l=Math.floor(n/864e5);return t==="zh"?s<1?"刚刚":s<60?`${s} 分钟前`:a<24?`${a} 小时前`:l<30?`${l} 天前`:new Date(e).toLocaleDateString("zh-CN"):s<1?"Just now":s<60?`${s}m ago`:a<24?`${a}h ago`:l<30?`${l}d ago`:new Date(e).toLocaleDateString("en-US")}function T8({isOpen:e,onClose:t,onSwitchSession:r}){const{t:n,resolved:s}=de(),[a,l]=C.useState([]),[o,c]=C.useState(!0),[d,u]=C.useState(null),[h,p]=C.useState(null),[m,v]=C.useState(null),[x,f]=C.useState(""),b=C.useRef(null),[g,_]=C.useState(null),y=C.useCallback(async()=>{c(!0),u(null);try{const $=await fetch("/api/v1/sessions",{headers:ve()});if(!$.ok)throw new Error(`HTTP ${$.status}`);const L=await $.json(),E=L.data??L;l(E.sessions||[])}catch($){u($.message||"Unknown error")}finally{c(!1)}},[]);C.useEffect(()=>{e&&y()},[e,y]);const S=C.useCallback(async $=>{var L;try{const E=await fetch(`/api/v1/sessions/${encodeURIComponent($.id)}`,{method:"DELETE",headers:ve()});if(!E.ok){const M=await E.json().catch(()=>({}));throw new Error(((L=M.error)==null?void 0:L.message)||M.error||`HTTP ${E.status}`)}l(M=>M.filter(O=>O.id!==$.id))}catch(E){console.error("[history] Delete failed:",E)}finally{_(null)}},[]),w=C.useCallback(async($,L)=>{var M;const E=L.trim();if(E)try{const O=await fetch(`/api/v1/sessions/${encodeURIComponent($.id)}/rename`,{method:"POST",headers:ve({"Content-Type":"application/json"}),body:JSON.stringify({name:E})});if(!O.ok){const z=await O.json().catch(()=>({}));throw new Error(((M=z.error)==null?void 0:M.message)||z.error||`HTTP ${O.status}`)}l(z=>z.map(U=>U.id===$.id?{...U,name:E}:U))}catch(O){console.error("[history] Rename failed:",O)}finally{v(null),f("")}},[]),k=C.useCallback(($,L)=>{L.stopPropagation(),v($),f($.name),setTimeout(()=>{var E;return(E=b.current)==null?void 0:E.focus()},50)},[]),A=C.useCallback(($,L)=>{L.stopPropagation(),!$.isCurrent&&_($)},[]),N=C.useCallback(async $=>{if(!($.isCurrent||h)){p($.id);try{await(r==null?void 0:r($.id)),t()}finally{p(null)}}},[h,r,t]),j=()=>o?i.jsx("div",{className:"history-loading",children:i.jsx(bn,{size:"small",text:n("history.loading")})}):d?i.jsxs("div",{className:"history-error",children:[i.jsx("p",{className:"history-error-text",children:n("history.loadError")}),i.jsx("button",{className:"history-retry-btn",onClick:y,children:n("history.retry")})]}):a.length===0?i.jsxs("div",{className:"history-empty",children:[i.jsx($i,{size:48,className:"text-text-tertiary"}),i.jsx("p",{className:"history-empty-title",children:n("history.noData")}),i.jsx("p",{className:"history-empty-hint",children:n("history.noDataHint")})]}):i.jsx("div",{className:"history-list",children:a.map(($,L)=>{const E=fl($.updatedAt),M=L>0?fl(a[L-1].updatedAt):null,O=E!==M;return i.jsxs("div",{children:[O&&i.jsx(es,{label:cS($.updatedAt,s)}),i.jsxs("div",{className:`history-session-item${$.isCurrent?" current":""}${!$.isCurrent&&!h?" clickable":""}`,onClick:()=>!$.isCurrent&&!h&&N($),children:[i.jsxs("div",{className:"history-session-info",children:[i.jsx("p",{className:"history-session-name",children:$.name}),i.jsxs("div",{className:"history-session-meta",children:[$.isCurrent&&i.jsx("span",{className:"history-session-badge",children:n("history.current")}),i.jsx("span",{children:n("history.messages").replace("{count}",String($.messageCount))}),i.jsx("span",{children:E8($.updatedAt,s)})]})]}),i.jsxs("div",{className:"history-session-actions",children:[h===$.id&&i.jsx("div",{className:"history-session-switching",children:i.jsx("div",{className:"history-session-spinner"})}),h!==$.id&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:"history-action-btn",title:n("history.rename"),onClick:z=>k($,z),children:i.jsx(LE,{size:14})}),!$.isCurrent&&i.jsx("button",{className:"history-action-btn danger",title:n("history.delete"),onClick:z=>A($,z),children:i.jsx(Oi,{size:14})})]})]})]})]},$.id)})});return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`history-drawer-overlay ${e?"open":""}`,onClick:t}),i.jsxs("div",{className:`history-drawer ${e?"open":""}`,children:[i.jsxs("div",{className:"history-drawer-header",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"history-drawer-title",children:n("history.title")}),i.jsx("p",{className:"history-drawer-subtitle",children:n("history.description")})]}),i.jsx("button",{onClick:t,className:"history-drawer-close",children:i.jsx(at,{size:16})})]}),i.jsx("div",{className:"history-content",children:j()})]}),m&&i.jsx("div",{className:"history-rename-overlay",onClick:()=>v(null),children:i.jsxs("div",{className:"history-rename-dialog",onClick:$=>$.stopPropagation(),children:[i.jsx("h3",{children:n("history.renameTitle")}),i.jsx("input",{ref:b,className:"history-rename-input",value:x,onChange:$=>f($.target.value),placeholder:n("history.renamePlaceholder"),onKeyDown:$=>{$.key==="Enter"&&x.trim()&&w(m,x),$.key==="Escape"&&v(null)}}),i.jsxs("div",{className:"history-rename-actions",children:[i.jsx("button",{className:"history-rename-cancel",onClick:()=>v(null),children:n("history.renameCancel")}),i.jsx("button",{className:"history-rename-ok",disabled:!x.trim(),onClick:()=>w(m,x),children:n("history.renameOk")})]})]})}),g&&i.jsx("div",{className:"history-delete-overlay",onClick:()=>_(null),children:i.jsxs("div",{className:"history-delete-dialog",onClick:$=>$.stopPropagation(),children:[i.jsx("p",{children:n("history.deleteConfirm")}),i.jsxs("div",{className:"history-delete-actions",children:[i.jsx("button",{className:"history-delete-cancel",onClick:()=>_(null),children:n("history.deleteCancel")}),i.jsx("button",{className:"history-delete-ok",onClick:()=>S(g),children:n("history.deleteOk")})]})]})})]})}function $o(e,t){return`${e}@${t}`}async function As(e,t){return Ve(e,{method:"POST",headers:{"Content-Type":"application/json",...ve()},body:t?JSON.stringify(t):void 0})}async function I8(e){return Ve(e,{method:"DELETE",headers:ve()})}async function ov(e){return Ve(e,{method:"GET",headers:ve()})}const N8=Ke((e,t)=>({plugins:[],loading:!1,error:null,marketplaces:[],marketplaceLoading:!1,availablePlugins:[],browsingMarketplace:null,browsingLoading:!1,browsingError:null,operatingPlugins:new Set,fetchPlugins:async()=>{e({loading:!0,error:null});try{const r=await ov("/api/v1/plugins");if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=(await r.json()).data,a=Array.isArray(s)?s.map(l=>({...l,canRemove:l.canRemove,canSwitchoff:l.canSwitchoff,canEdit:l.canEdit})):[];e({plugins:a,loading:!1})}catch(r){console.warn("[plugin-store] fetchPlugins failed:",r),e({error:r.message,loading:!1})}},fetchMarketplaces:async()=>{e({marketplaceLoading:!0});try{const r=await ov("/api/v1/plugins/marketplaces");if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=(await r.json()).data;e({marketplaces:Array.isArray(s)?s:[],marketplaceLoading:!1})}catch(r){console.warn("[plugin-store] fetchMarketplaces failed:",r),e({marketplaceLoading:!1})}},browseMarketplace:async r=>{var n;e({browsingMarketplace:r,browsingLoading:!0,browsingError:null});try{const s=await As("/api/v1/plugins/marketplaces/browse",{marketplace:r});if(!s.ok){const c=await s.json().catch(()=>null);throw new Error(((n=c==null?void 0:c.error)==null?void 0:n.message)||`HTTP ${s.status}`)}const a=await s.json(),o=(Array.isArray(a.data)?a.data:[]).map(c=>({name:c.name,version:c.version,description:c.description,marketplace:c.marketplaceName||r,installed:!!c.status,author:c.author,license:c.license,homepage:c.homepage,repository:c.repository,keywords:c.keywords,category:c.category,features:c.features,source:c.source}));e({availablePlugins:o,browsingLoading:!1})}catch(s){console.warn("[plugin-store] browseMarketplace failed:",s),e({browsingError:s.message,browsingLoading:!1})}},browseAllMarketplaces:async()=>{const{marketplaces:r}=t();if(r.length!==0){e({browsingMarketplace:"__all__",browsingLoading:!0,browsingError:null});try{const n=await Promise.allSettled(r.map(async c=>{var p;const d=await As("/api/v1/plugins/marketplaces/browse",{marketplace:c.name});if(!d.ok){const m=await d.json().catch(()=>null);throw new Error(((p=m==null?void 0:m.error)==null?void 0:p.message)||`HTTP ${d.status}`)}const u=await d.json();return(Array.isArray(u.data)?u.data:[]).map(m=>({name:m.name,version:m.version,description:m.description,marketplace:m.marketplaceName||c.name,installed:!!m.status,author:m.author,license:m.license,homepage:m.homepage,repository:m.repository,keywords:m.keywords,category:m.category,features:m.features,source:m.source}))})),s=[];let a=!1;for(const c of n)c.status==="fulfilled"?s.push(...c.value):a=!0;const l=new Set,o=s.filter(c=>{const d=`${c.name}@${c.marketplace}`;return l.has(d)?!1:(l.add(d),!0)});e({availablePlugins:o,browsingLoading:!1,browsingError:a&&o.length===0?"Some marketplaces failed to load":null})}catch(n){console.warn("[plugin-store] browseAllMarketplaces failed:",n),e({browsingError:n.message,browsingLoading:!1})}}},enablePlugin:async(r,n)=>{var a;const s=$o(r,n);e(l=>({operatingPlugins:new Set(l.operatingPlugins).add(s)}));try{const l=await As("/api/v1/plugins/enable",{plugin:s});if(!l.ok){const o=await l.json().catch(()=>null);throw new Error(((a=o==null?void 0:o.error)==null?void 0:a.message)||`HTTP ${l.status}`)}await t().fetchPlugins()}finally{e(l=>{const o=new Set(l.operatingPlugins);return o.delete(s),{operatingPlugins:o}})}},disablePlugin:async(r,n)=>{var a;const s=$o(r,n);e(l=>({operatingPlugins:new Set(l.operatingPlugins).add(s)}));try{const l=await As("/api/v1/plugins/disable",{plugin:s});if(!l.ok){const o=await l.json().catch(()=>null);throw new Error(((a=o==null?void 0:o.error)==null?void 0:a.message)||`HTTP ${l.status}`)}await t().fetchPlugins()}finally{e(l=>{const o=new Set(l.operatingPlugins);return o.delete(s),{operatingPlugins:o}})}},uninstallPlugin:async(r,n)=>{var a;const s=$o(r,n);e(l=>({operatingPlugins:new Set(l.operatingPlugins).add(s)}));try{const l=await As("/api/v1/plugins/uninstall",{plugin:s});if(!l.ok){const o=await l.json().catch(()=>null);throw new Error(((a=o==null?void 0:o.error)==null?void 0:a.message)||`HTTP ${l.status}`)}await t().fetchPlugins()}finally{e(l=>{const o=new Set(l.operatingPlugins);return o.delete(s),{operatingPlugins:o}})}},installPlugin:async(r,n,s)=>{var l;const a=$o(r,n);e(o=>({operatingPlugins:new Set(o.operatingPlugins).add(a)}));try{const o=await As("/api/v1/plugins",{plugin:a,options:s?{scope:s}:void 0});if(!o.ok){const d=await o.json().catch(()=>null);throw new Error(((l=d==null?void 0:d.error)==null?void 0:l.message)||`HTTP ${o.status}`)}await t().fetchPlugins();const c=t();c.browsingMarketplace&&(c.browsingMarketplace==="__all__"?await t().browseAllMarketplaces():await t().browseMarketplace(c.browsingMarketplace))}finally{e(o=>{const c=new Set(o.operatingPlugins);return c.delete(a),{operatingPlugins:c}})}},addMarketplace:async(r,n)=>{var a;const s=await As("/api/v1/plugins/marketplaces",{source:r,name:n});if(!s.ok){const l=await s.json().catch(()=>null);throw new Error(((a=l==null?void 0:l.error)==null?void 0:a.message)||`HTTP ${s.status}`)}await t().fetchMarketplaces()},removeMarketplace:async r=>{var s;const n=await I8(`/api/v1/plugins/marketplaces/${encodeURIComponent(r)}`);if(!n.ok){const a=await n.json().catch(()=>null);throw new Error(((s=a==null?void 0:a.error)==null?void 0:s.message)||`HTTP ${n.status}`)}await t().fetchMarketplaces()}}));function T1(){const{t:e}=de(),{plugins:t,marketplaces:r,loading:n,marketplaceLoading:s,error:a,operatingPlugins:l,availablePlugins:o,browsingLoading:c,browsingError:d,fetchPlugins:u,fetchMarketplaces:h,browseMarketplace:p,browseAllMarketplaces:m,enablePlugin:v,disablePlugin:x,uninstallPlugin:f,installPlugin:b,addMarketplace:g,removeMarketplace:_}=N8(),[y,S]=C.useState("installed"),[w,k]=C.useState(""),[A,N]=C.useState("all"),[j,$]=C.useState(null),[L,E]=C.useState(!1),[M,O]=C.useState(""),[z,U]=C.useState(""),[Q,I]=C.useState(!1),[T,D]=C.useState(null),[R,G]=C.useState(null),[P,H]=C.useState(null),[q,B]=C.useState(""),[F,Z]=C.useState(""),[J,te]=C.useState(null),ne=C.useCallback(ce=>{te(Ce=>Ce===ce?null:ce)},[]);C.useEffect(()=>{u(),h()},[u,h]),C.useEffect(()=>{y==="browse"&&!q&&r.length>0&&(B("__all__"),m())},[y,r,q,m]);const re=C.useCallback(async ce=>{$(null);try{ce.status==="enabled"?await x(ce.name,ce.marketplace):await v(ce.name,ce.marketplace)}catch(Ce){$(Ce.message)}},[v,x]),me=C.useCallback(async ce=>{$(null),G(null);try{await f(ce.name,ce.marketplace)}catch(Ce){$(Ce.message)}},[f]),he=C.useCallback(async(ce,Ce)=>{$(null);try{await b(ce.name,ce.marketplace,Ce)}catch(Le){$(Le.message)}},[b]),pe=C.useCallback(async()=>{const ce=M.trim();if(ce){I(!0),D(null);try{await g(ce,z.trim()||void 0),O(""),U(""),E(!1)}catch(Ce){D(Ce.message)}finally{I(!1)}}},[M,z,g]),ae=C.useCallback(async ce=>{$(null),H(null);try{if(await _(ce),q===ce&&r.length>1){const Ce=r.find(Le=>Le.name!==ce);Ce&&(B(Ce.name),p(Ce.name))}}catch(Ce){$(Ce.message)}},[_,q,r,p]),ye=C.useCallback(()=>{u(),h(),y==="browse"&&q&&(q==="__all__"?m():p(q))},[u,h,y,q,p,m]),be=C.useCallback(ce=>{B(ce),Z(""),ce==="__all__"?m():p(ce)},[p,m]),le=ce=>`${ce.name}@${ce.marketplace}`,_e=C.useMemo(()=>{const ce=new Set(t.map(Ce=>Ce.marketplace));return Array.from(ce).sort()},[t]),Te=C.useMemo(()=>{let ce=t;A!=="all"&&(ce=ce.filter(Le=>Le.marketplace===A));const Ce=w.trim().toLowerCase();return Ce&&(ce=ce.filter(Le=>Le.name.toLowerCase().includes(Ce)||Le.description&&Le.description.toLowerCase().includes(Ce)||Le.marketplace.toLowerCase().includes(Ce))),ce},[t,A,w]),$e=C.useMemo(()=>{let ce=o;const Ce=F.trim().toLowerCase();return Ce&&(ce=ce.filter(Le=>Le.name.toLowerCase().includes(Ce)||Le.description&&Le.description.toLowerCase().includes(Ce))),ce},[o,F]),Ze=t.filter(ce=>ce.status==="enabled").length;return i.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[i.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:i.jsxs("div",{className:"max-w-3xl mx-auto",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("plugins.title")}),y==="installed"&&t.length>0&&i.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[t.length," ",e("plugins.totalCount")," · ",Ze," ",e("plugins.enabled")]}),y==="browse"&&q&&!c&&o.length>0&&i.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[o.length," ",e("plugins.totalCount")]}),y==="marketplaces"&&r.length>0&&i.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[r.length," ",e("plugins.totalCount")]})]}),i.jsx("button",{onClick:ye,disabled:n||c,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${n||c?"opacity-50 cursor-not-allowed border-border-muted text-text-secondary":"border-border-muted text-text-secondary hover:text-text-primary hover:border-text-primary/20 hover:bg-bg-secondary"}`,title:e("plugins.refresh"),children:i.jsx(St,{size:14,className:n||c?"animate-spin":""})})]}),i.jsxs("div",{className:"flex gap-1 border-b border-border-muted",children:[i.jsx("button",{onClick:()=>{S("installed"),$(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${y==="installed"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.installedPlugins")}),i.jsx("button",{onClick:()=>{S("browse"),$(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${y==="browse"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.browseMarketplace")}),i.jsx("button",{onClick:()=>{S("marketplaces"),$(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${y==="marketplaces"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.marketplaces")})]}),y==="installed"&&t.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx(br,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),i.jsx("input",{type:"text",value:w,onChange:ce=>k(ce.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),w&&i.jsx("button",{onClick:()=>k(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:i.jsx(at,{size:12})})]}),_e.length>1&&i.jsxs("select",{value:A,onChange:ce=>N(ce.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[i.jsx("option",{value:"all",children:e("plugins.allMarketplaces")}),_e.map(ce=>i.jsx("option",{value:ce,children:ce},ce))]})]}),y==="browse"&&r.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx(br,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),i.jsx("input",{type:"text",value:F,onChange:ce=>Z(ce.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),F&&i.jsx("button",{onClick:()=>Z(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:i.jsx(at,{size:12})})]}),i.jsxs("select",{value:q,onChange:ce=>be(ce.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[i.jsx("option",{value:"__all__",children:e("plugins.allMarketplaces")}),r.map(ce=>i.jsx("option",{value:ce.name,children:ce.name},ce.name))]})]})]})}),i.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:i.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[j&&i.jsxs("div",{className:"bg-accent-red/10 border border-accent-red/30 rounded-xl p-3.5 text-accent-red text-[13px] flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(rn,{size:14,className:"shrink-0"}),i.jsxs("span",{className:"truncate",children:[e("plugins.operationFailed"),": ",j]})]}),i.jsx("button",{onClick:()=>$(null),className:"w-5 h-5 flex items-center justify-center rounded-full hover:bg-accent-red/20 transition-colors shrink-0 ml-3",children:i.jsx(at,{size:12})})]}),y==="installed"&&i.jsxs(i.Fragment,{children:[n&&t.length===0&&i.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:i.jsx(bn,{size:"small",text:e("plugins.loading")})}),a&&!n&&t.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[i.jsx(rn,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),i.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),i.jsx("button",{onClick:u,className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),!n&&!a&&t.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(Fs,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noPlugins")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noPluginsHint")})]}),t.length>0&&Te.length===0&&!n&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[i.jsx(br,{size:36,className:"mb-3 opacity-30"}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),Te.length>0&&i.jsx("div",{className:"space-y-3",children:Te.map(ce=>{const Ce=le(ce);return i.jsx(R8,{plugin:ce,isEnabled:ce.status==="enabled",isOperating:l.has(Ce),isExpanded:J===Ce,confirmUninstall:R===Ce,onToggle:()=>re(ce),onUninstall:()=>me(ce),onConfirmUninstall:()=>G(Ce),onCancelUninstall:()=>G(null),onExpand:()=>ne(Ce),t:e},Ce)})})]}),y==="browse"&&i.jsxs(i.Fragment,{children:[!s&&r.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(xa,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),c&&o.length===0&&q&&i.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:i.jsx(bn,{size:"small",text:e("plugins.browsingMarketplace")})}),d&&o.length===0&&q&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[i.jsx(rn,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),i.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),i.jsx("button",{onClick:()=>q&&p(q),className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),q&&o.length===0&&!c&&!d&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(Fs,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noAvailablePlugins")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noAvailablePluginsHint")})]}),o.length>0&&$e.length===0&&!c&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[i.jsx(br,{size:36,className:"mb-3 opacity-30"}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),$e.length>0&&i.jsx("div",{className:"space-y-3",children:$e.map(ce=>{const Ce=`${ce.name}@${ce.marketplace}`;return i.jsx(L8,{plugin:ce,isInstalled:ce.installed,isOperating:l.has(Ce),isExpanded:J===Ce,onInstall:Le=>he(ce,Le),onExpand:()=>ne(Ce),t:e},Ce)})})]}),y==="marketplaces"&&i.jsxs("div",{className:"space-y-3",children:[!L&&i.jsxs("button",{onClick:()=>E(!0),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary hover:border-text-primary/30 transition-colors",children:[i.jsx(Ot,{size:12}),e("plugins.addMarketplace")]}),L&&i.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[13px] font-medium",children:e("plugins.addMarketplace")}),i.jsx("button",{onClick:()=>{E(!1),D(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:i.jsx(at,{size:12})})]}),i.jsx("input",{type:"text",value:M,onChange:ce=>O(ce.target.value),placeholder:e("plugins.sourcePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),i.jsx("input",{type:"text",value:z,onChange:ce=>U(ce.target.value),placeholder:e("plugins.namePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),T&&i.jsx("div",{className:"text-accent-red text-[12px]",children:T}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{onClick:()=>{E(!1),D(null)},className:"px-3 py-1.5 rounded-lg text-[12px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")}),i.jsxs("button",{onClick:pe,disabled:!M.trim()||Q,className:"px-3 py-1.5 rounded-lg text-[12px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5",children:[Q&&i.jsx(He,{size:12,className:"animate-spin"}),e("plugins.add")]})]})]}),s&&r.length===0&&i.jsx("div",{className:"flex items-center justify-center py-6",children:i.jsx(He,{size:18,className:"animate-spin text-text-tertiary"})}),!s&&r.length===0&&!L&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[i.jsx(xa,{size:48,className:"mb-4 opacity-30"}),i.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),i.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),r.length>0&&i.jsx("div",{className:"bg-bg-secondary rounded-xl border border-border-muted overflow-hidden",children:r.map((ce,Ce)=>i.jsxs("div",{className:`flex items-center justify-between px-4 py-3 ${Ce>0?"border-t border-border-muted":""}`,children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(xa,{size:14,className:"text-text-tertiary shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"text-[13px] font-medium truncate",children:ce.name}),ce.type&&i.jsx("div",{className:"text-[11px] text-text-tertiary",children:ce.type})]})]}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:P===ce.name?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>ae(ce.name),className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:e("plugins.removeMarketplace")}),i.jsx("button",{onClick:()=>H(null),className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")})]}):i.jsx("button",{onClick:()=>H(ce.name),className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors",title:e("plugins.removeMarketplace"),children:i.jsx(Oi,{size:13})})})]},ce.name))})]})]})})]})}function R8({plugin:e,isEnabled:t,isOperating:r,isExpanded:n,confirmUninstall:s,onToggle:a,onUninstall:l,onConfirmUninstall:o,onCancelUninstall:c,onExpand:d,t:u}){return i.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[i.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:d,children:[i.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:i.jsx(Fs,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[i.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&i.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),i.jsx("span",{className:`text-[10px] px-1.5 py-px rounded font-medium shrink-0 ${t?"bg-accent-green/15 text-accent-green":"bg-bg-tertiary text-text-tertiary"}`,children:u(t?"plugins.enabled":"plugins.disabled")})]}),e.description&&i.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${n?"":"line-clamp-2"}`,children:e.description}),i.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-text-tertiary",children:[i.jsx(xa,{size:10,className:"shrink-0"}),i.jsx("span",{children:e.marketplace}),e.installScope&&i.jsx("span",{className:"px-1.5 py-px rounded bg-bg-tertiary text-[10px] font-medium",children:u(`plugins.scope.${e.installScope}`)})]})]}),i.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:h=>h.stopPropagation(),children:r?i.jsx("div",{className:"w-[72px] flex justify-center",children:i.jsx(He,{size:16,className:"animate-spin text-text-tertiary"})}):s?i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("button",{onClick:l,className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:u("plugins.uninstall")}),i.jsx("button",{onClick:c,className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:u("plugins.cancel")})]}):i.jsxs(i.Fragment,{children:[i.jsxs("button",{onClick:e.canSwitchoff===!1?void 0:a,disabled:e.canSwitchoff===!1,className:`px-2.5 py-1.5 rounded-md text-[11px] font-medium transition-colors flex items-center gap-1 ${e.canSwitchoff===!1?"text-text-tertiary border border-border-muted cursor-not-allowed opacity-50":t?"text-text-secondary border border-border-muted hover:bg-bg-tertiary":"text-text-primary border border-border-muted hover:bg-bg-tertiary"}`,title:e.canSwitchoff===!1?u("plugins.policyCannotSwitchoff"):u(t?"plugins.disable":"plugins.enable"),children:[t?i.jsx(UE,{size:11}):i.jsx(tw,{size:11}),u(t?"plugins.disable":"plugins.enable")]}),i.jsx("button",{onClick:e.canRemove===!1?void 0:o,disabled:e.canRemove===!1,className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${e.canRemove===!1?"text-text-tertiary cursor-not-allowed opacity-30":"text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 opacity-0 group-hover:opacity-100"}`,title:e.canRemove===!1?u("plugins.policyCannotRemove"):u("plugins.uninstall"),children:i.jsx(Oi,{size:13})})]})})]}),n&&i.jsx(I1,{plugin:e,t:u})]})}function L8({plugin:e,isInstalled:t,isOperating:r,isExpanded:n,onInstall:s,onExpand:a,t:l}){return i.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[i.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:a,children:[i.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:i.jsx(Fs,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[i.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&i.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),t&&i.jsx("span",{className:"text-[10px] px-1.5 py-px rounded font-medium shrink-0 bg-accent-green/15 text-accent-green",children:l("plugins.installedLabel")})]}),e.description&&i.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${n?"":"line-clamp-2"}`,children:e.description}),i.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[i.jsx(xa,{size:10,className:"shrink-0"}),i.jsx("span",{children:e.marketplace})]})]}),i.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:o=>o.stopPropagation(),children:t?i.jsx("div",{className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-tertiary bg-bg-tertiary",children:l("plugins.installed")}):r?i.jsx("div",{className:"w-[72px] flex justify-center",children:i.jsx(He,{size:16,className:"animate-spin text-text-tertiary"})}):i.jsx(D8,{onInstall:s,t:l})})]}),n&&i.jsx(I1,{plugin:e,t:l})]})}function I1({plugin:e,t}){const r=e.source,n=typeof r=="object"&&r!==null?r.url:void 0,s=typeof r=="object"&&r!==null?r.source:typeof r=="string"?r:void 0,a="installScope"in e?e.installScope:void 0;return i.jsxs("div",{className:"border-t border-border-muted mx-5 px-0 py-3.5 space-y-2.5",children:[a&&i.jsx(Nn,{label:t("plugins.scope"),children:i.jsx("span",{className:"text-[12px] text-text-secondary",children:t(`plugins.scope.${a}`)})}),e.category&&i.jsx(Nn,{label:t("plugins.category"),children:i.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded bg-[#f5a623]/8 text-[#b8860b] font-medium",children:e.category})}),e.author&&i.jsxs(Nn,{label:t("plugins.author"),children:[i.jsx("span",{className:"text-[12px] text-text-primary font-medium",children:e.author.name}),e.author.email&&i.jsx("a",{href:`mailto:${e.author.email}`,className:"text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:l=>l.stopPropagation(),children:e.author.email}),e.author.url&&i.jsxs("a",{href:e.author.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:l=>l.stopPropagation(),children:[e.author.url,i.jsx(Ar,{size:9})]})]}),e.license&&i.jsx(Nn,{label:t("plugins.license"),children:i.jsx("span",{className:"text-[12px] text-text-secondary",children:e.license})}),e.homepage&&i.jsx(Nn,{label:t("plugins.homepage"),children:i.jsxs("a",{href:e.homepage,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:l=>l.stopPropagation(),children:[e.homepage,i.jsx(Ar,{size:10,className:"shrink-0 text-text-tertiary"})]})}),e.repository&&i.jsx(Nn,{label:t("plugins.repository"),children:i.jsxs("a",{href:e.repository,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:l=>l.stopPropagation(),children:[e.repository,i.jsx(Ar,{size:10,className:"shrink-0 text-text-tertiary"})]})}),s&&i.jsx(Nn,{label:t("plugins.source"),children:n?i.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:l=>l.stopPropagation(),children:[s,i.jsx(Ar,{size:10,className:"shrink-0 text-text-tertiary"})]}):i.jsx("span",{className:"text-[12px] text-text-secondary font-mono",children:s})}),e.keywords&&e.keywords.length>0&&i.jsx(Nn,{label:t("plugins.keywords"),children:i.jsx("div",{className:"flex flex-wrap gap-1",children:e.keywords.map(l=>i.jsx("span",{className:"text-[10px] px-1.5 py-px rounded bg-bg-tertiary text-text-tertiary",children:l},l))})}),e.features&&e.features.length>0&&i.jsx(Nn,{label:t("plugins.features"),children:i.jsx("ul",{className:"space-y-0.5",children:e.features.map((l,o)=>i.jsxs("li",{className:"text-[12px] text-text-secondary flex items-start gap-1.5",children:[i.jsx("span",{className:"text-text-tertiary shrink-0",children:"·"}),l]},o))})})]})}function Nn({label:e,children:t}){return i.jsxs("div",{className:"flex items-baseline gap-3",children:[i.jsx("span",{className:"text-[11px] text-text-tertiary w-12 shrink-0 text-right",children:e}),i.jsx("div",{className:"flex-1 min-w-0 flex items-baseline flex-wrap gap-1",children:t})]})}function D8({onInstall:e,t}){const[r,n]=C.useState(!1);return i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>n(!r),className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary transition-colors flex items-center gap-1",title:t("plugins.install"),children:[i.jsx(Bv,{size:11}),t("plugins.install")]}),r&&i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 bg-bg-primary border border-border-muted rounded-lg shadow-lg py-1 min-w-[220px]",children:[i.jsx("button",{onClick:()=>{e("user"),n(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.user")}),i.jsx("button",{onClick:()=>{e("project"),n(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.project")}),i.jsx("button",{onClick:()=>{e("project-local"),n(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.local")})]})]})}const M8=[{value:"minimal",labelKey:"settings.effort.minimal"},{value:"low",labelKey:"settings.effort.low"},{value:"medium",labelKey:"settings.effort.medium"},{value:"high",labelKey:"settings.effort.high"},{value:"xhigh",labelKey:"settings.effort.xhigh"},{value:"max",labelKey:"settings.effort.max"}],$8=[{titleKey:"settings.group.modelAndReasoning",items:[{key:"model",labelKey:"settings.item.model",descKey:"settings.item.model.desc",type:"text"},{key:"reasoningEffort",labelKey:"settings.item.reasoningEffort",descKey:"settings.item.reasoningEffort.desc",type:"select",options:M8},{key:"alwaysThinkingEnabled",labelKey:"settings.item.alwaysThinkingEnabled",type:"toggle"}]},{titleKey:"settings.group.behavior",items:[{key:"autoCompactEnabled",labelKey:"settings.item.autoCompactEnabled",type:"toggle"},{key:"includeCoAuthoredBy",labelKey:"settings.item.includeCoAuthoredBy",type:"toggle"},{key:"fileCheckpointingEnabled",labelKey:"settings.item.fileCheckpointingEnabled",descKey:"settings.item.fileCheckpointingEnabled.desc",type:"toggle"},{key:"promptSuggestionEnabled",labelKey:"settings.item.promptSuggestionEnabled",type:"toggle"},{key:"ignoreGitIgnore",labelKey:"settings.item.ignoreGitIgnore",descKey:"settings.item.ignoreGitIgnore.desc",type:"toggle"},{key:"deferToolLoading",labelKey:"settings.item.deferToolLoading",type:"toggle"},{key:"hookOutputCollapsed",labelKey:"settings.item.hookOutputCollapsed",type:"toggle"}]},{titleKey:"settings.group.memory",items:[{key:"memory.enabled",labelKey:"settings.item.memory.enabled",type:"toggle"},{key:"memory.autoMemoryEnabled",labelKey:"settings.item.memory.autoMemoryEnabled",descKey:"settings.item.memory.autoMemoryEnabled.desc",type:"toggle"}]},{titleKey:"settings.group.language",items:[{key:"language",labelKey:"settings.item.language",descKey:"settings.item.language.desc",type:"text"}]},{titleKey:"settings.group.advanced",items:[{key:"cleanupPeriodDays",labelKey:"settings.item.cleanupPeriodDays",type:"number"},{key:"imageHistoryRetainRounds",labelKey:"settings.item.imageHistoryRetainRounds",descKey:"settings.item.imageHistoryRetainRounds.desc",type:"number"},{key:"env",labelKey:"settings.item.env",descKey:"settings.item.env.desc",type:"json"}]},{titleKey:"settings.group.sandbox",items:[{key:"sandbox.enabled",labelKey:"settings.item.sandbox.enabled",descKey:"settings.item.sandbox.enabled.desc",type:"toggle"},{key:"sandbox.autoAllowBashIfSandboxed",labelKey:"settings.item.sandbox.autoAllowBashIfSandboxed",descKey:"settings.item.sandbox.autoAllowBashIfSandboxed.desc",type:"toggle"}]}];function O8(e,t){const r=t.split(".");let n=e;for(const s of r){if(n==null||typeof n!="object")return;n=n[s]}return n}function N1(){const{status:e,sessionId:t,currentModel:r,models:n,modes:s,currentMode:a}=er(),{info:l,fetch:o}=Or(),{mode:c,toggle:d}=Jt(),{t:u,tryT:h,locale:p,toggleLocale:m}=de(),[v,x]=C.useState(null),[f,b]=C.useState({}),g=C.useRef({}),[_,y]=C.useState(!1),[S,w]=C.useState({}),k=C.useRef({});C.useEffect(()=>{let I=!1;return y(!0),Promise.all([fetch("/api/v1/settings",{headers:ve()}).then(T=>{if(!T.ok)throw new Error(`Settings API: ${T.status}`);return T.json()}).then(T=>(T==null?void 0:T.data)??T??{}),fetch("/api/v1/settings?scope=user",{headers:ve()}).then(T=>{if(!T.ok)throw new Error(`User settings API: ${T.status}`);return T.json()}).then(T=>(T==null?void 0:T.data)??T??{})]).then(([T,D])=>{I||(b(T),g.current=D,y(!1))}).catch(T=>{console.error("Failed to load settings:",T),I||y(!1)}),()=>{I=!0}},[]),C.useEffect(()=>()=>{Object.values(k.current).forEach(clearTimeout)},[]),C.useEffect(()=>{l||o()},[l,o]);const A=C.useCallback((I,T)=>{navigator.clipboard.writeText(I).then(()=>{x(T),setTimeout(()=>x(null),1500)})},[]),N=async I=>{if($("model",I),t)try{await ze().setModel(t,I)}catch(T){console.error("Model change failed:",T)}},j=async I=>{if($("permissions.defaultMode",I),t)try{await ze().setMode(t,I)}catch(T){console.error("Mode change failed:",T)}},$=C.useCallback(async(I,T)=>{const D=I.split(".")[0];let R=T;if(I.includes(".")){const G=I.split("."),H={...g.current[D]??{}};let q=H;for(let B=1;B<G.length-1;B++)q[G[B]]=q[G[B]]?{...q[G[B]]}:{},q=q[G[B]];q[G[G.length-1]]=T,R=H}try{const G=await fetch(`/api/v1/settings/${D}?scope=user`,{method:"PUT",headers:ve({"Content-Type":"application/json"}),body:JSON.stringify({value:R})});G.ok||G.status===204?(I.includes(".")?(g.current={...g.current,[D]:R},b(P=>({...P,[D]:{...P[D]??{},...R}}))):(g.current={...g.current,[I]:T},b(P=>({...P,[I]:T}))),L(I,"success")):(console.error(`Failed to save setting "${I}": HTTP ${G.status}`),L(I,"error"))}catch(G){console.error(`Failed to save setting "${I}":`,G),L(I,"error")}},[]),L=C.useCallback((I,T)=>{w(D=>({...D,[I]:T})),k.current[I]&&clearTimeout(k.current[I]),k.current[I]=setTimeout(()=>{w(D=>{const R={...D};return delete R[I],R})},1500)},[]),E={disconnected:"bg-gray-400",connecting:"bg-accent-yellow animate-pulse",connected:"bg-accent-green",error:"bg-accent-red"}[e],M={connected:"connection.connected",connecting:"connection.connecting",disconnected:"connection.disconnected",error:"connection.error"},O=c==="light"?rw:c==="dark"?Xv:b2,z=u(c==="light"?"theme.light":c==="dark"?"theme.dark":"theme.system"),U=p==="system"?JA:Uv,Q=u(p==="zh"?"locale.zh":p==="en"?"locale.en":"locale.system");return i.jsx("div",{className:"settings-view",children:i.jsx("div",{className:"settings-content",children:i.jsxs("div",{className:"settings-sections",children:[i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("sidebar.connectionStatus")}),i.jsxs("div",{className:"settings-card",children:[i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.status")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2 h-2 rounded-full ${E}`}),i.jsx("span",{className:"settings-value",children:u(M[e]||"connection.disconnected")})]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.sessionId")}),i.jsx("span",{className:"settings-value font-mono text-[12px]",children:t?t.substring(0,12):u("sidebar.notConnected")})]})]})]}),i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.appearance")}),i.jsxs("div",{className:"settings-card",children:[i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.theme")}),i.jsxs("button",{onClick:d,className:"settings-toggle-btn",children:[i.jsx(O,{size:14,className:"text-accent-brand"}),i.jsx("span",{children:z})]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.language")}),i.jsxs("button",{onClick:m,className:"settings-toggle-btn",children:[i.jsx(U,{size:14,className:"text-accent-brand"}),i.jsx("span",{children:Q})]})]})]})]}),n.length>0&&i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.model")}),i.jsx("div",{className:"settings-card",children:i.jsx("select",{value:r,onChange:I=>N(I.target.value),className:"settings-select",children:n.map(I=>i.jsx("option",{value:I.id,children:I.name||I.id},I.id))})})]}),s.length>0&&i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.mode")}),i.jsx("div",{className:"settings-card",children:i.jsx("select",{value:a,onChange:I=>j(I.target.value),className:"settings-select",children:s.map(I=>i.jsx("option",{value:I.id,title:h(`mode.${I.id}.desc`)||I.description,children:h(`mode.${I.id}`)||I.name},I.id))})})]}),_?i.jsx("div",{className:"settings-group",children:i.jsx("span",{className:"settings-value",children:u("settings.loading")})}):$8.map(I=>i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u(I.titleKey)}),i.jsx("div",{className:"settings-card",children:I.items.map(T=>i.jsx(j8,{item:T,value:O8(f,T.key),feedback:S[T.key],onSave:$},T.key))})]},I.titleKey)),l&&i.jsxs("div",{className:"settings-group",children:[i.jsx("h2",{className:"settings-group-title",children:u("settings.systemInfo")}),i.jsxs("div",{className:"settings-card",children:[i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.cwd")}),i.jsxs("button",{onClick:()=>A(l.cwd,"cwd"),className:"settings-copy-btn",title:l.cwd,children:[i.jsx("span",{className:"truncate cursor-pointer hover:underline hover:text-accent-brand",onClick:I=>{I.stopPropagation(),oh(l.cwd)},children:l.cwd}),v==="cwd"?i.jsx(Fn,{size:12,className:"shrink-0 text-accent-green"}):i.jsx(Ci,{size:12,className:"shrink-0 text-text-tertiary"})]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.os")}),i.jsxs("span",{className:"settings-value",children:[l.os," ",l.arch]})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.nodeVersion")}),i.jsx("span",{className:"settings-value",children:l.nodeVersion})]}),i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.gatewayMode")}),i.jsx("span",{className:"settings-value capitalize",children:l.gatewayMode})]}),l.tunnelUrl&&i.jsxs("div",{className:"settings-row",children:[i.jsx("span",{className:"settings-label",children:u("sidebar.tunnelUrl")}),i.jsxs("button",{onClick:()=>A(l.tunnelUrl,"tunnel"),className:"settings-copy-btn",title:l.tunnelUrl,children:[i.jsx("span",{className:"truncate",children:l.tunnelUrl.replace(/^https?:\/\//,"")}),v==="tunnel"?i.jsx(Fn,{size:12,className:"shrink-0 text-accent-green"}):i.jsx(Ci,{size:12,className:"shrink-0 text-text-tertiary"})]})]})]})]})]})})})}function j8({item:e,value:t,feedback:r,onSave:n}){const{t:s}=de(),[a,l]=C.useState(""),o=C.useRef(null);C.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]),C.useEffect(()=>{e.type==="text"||e.type==="number"?l(t!=null?String(t):""):e.type==="json"&&l(t!=null?JSON.stringify(t,null,2):"")},[t,e.type]);const c=C.useCallback(()=>{n(e.key,!t)},[e.key,t,n]),d=C.useCallback(h=>{n(e.key,h||void 0)},[e.key,n]),u=C.useCallback(h=>{l(h),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{if(e.type==="number"){const p=Number(h);!isNaN(p)&&h.trim()!==""&&n(e.key,p)}else if(e.type==="json")try{const p=JSON.parse(h);n(e.key,p)}catch{}else n(e.key,h)},600)},[e.key,e.type,n]);return i.jsxs("div",{className:"settings-row",children:[i.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"settings-label",children:s(e.labelKey)}),r&&i.jsx("span",{className:`settings-save-feedback ${r==="success"?"success":"error"}`,children:s(r==="success"?"settings.saved":"settings.saveFailed")})]}),e.descKey&&i.jsx("span",{className:"settings-desc",children:s(e.descKey)})]}),i.jsxs("div",{className:"flex items-center shrink-0 ml-3",children:[e.type==="toggle"&&i.jsx("button",{className:`settings-toggle-switch ${t?"on":""}`,onClick:c}),e.type==="select"&&e.options&&i.jsxs("select",{value:t??"",onChange:h=>d(h.target.value),className:"settings-inline-select",children:[i.jsx("option",{value:"",children:"-"}),e.options.map(h=>i.jsx("option",{value:h.value,children:s(h.labelKey)},h.value))]}),e.type==="text"&&i.jsx("input",{type:"text",value:a,onChange:h=>u(h.target.value),placeholder:s("settings.notSet"),className:"settings-input"}),e.type==="number"&&i.jsx("input",{type:"number",value:a,onChange:h=>u(h.target.value),className:"settings-input",style:{width:80}}),e.type==="json"&&i.jsx("textarea",{value:a,onChange:h=>u(h.target.value),placeholder:"{}",className:"settings-input wide",rows:3,style:{width:"100%",resize:"vertical"}})]})]})}function vd(){return er.getState().sessionId??void 0}const B8=Ke((e,t)=>({tasks:[],loading:!1,error:null,fetchTasks:async()=>{const r=vd();if(r){e({loading:!0,error:null});try{const n=new URLSearchParams({sessionId:r}),s=await fetch(`/api/v1/scheduled-tasks?${n}`,{headers:ve()});if(!s.ok)throw new Error(`HTTP ${s.status}`);const a=await s.json(),l=a.data??a;e({tasks:l.tasks||[],loading:!1})}catch(n){console.error("[ScheduledTasks] Fetch error:",n),e({error:n.message,loading:!1})}}},createTask:async(r,n,s=!0,a=!1)=>{var o;const l=vd();if(l)try{const c=await fetch("/api/v1/scheduled-tasks",{method:"POST",headers:{"Content-Type":"application/json",...ve()},body:JSON.stringify({cron:r,prompt:n,recurring:s,durable:a,sessionId:l})});if(!c.ok){const d=await c.json().catch(()=>({}));throw new Error(((o=d.error)==null?void 0:o.message)||`HTTP ${c.status}`)}await t().fetchTasks()}catch(c){throw console.error("[ScheduledTasks] Create error:",c),e({error:c.message}),c}},deleteTask:async r=>{const n=vd();if(n)try{const s=new URLSearchParams({sessionId:n}),a=await fetch(`/api/v1/scheduled-tasks/${r}?${s}`,{method:"DELETE",headers:ve()});if(!a.ok&&a.status!==204)throw new Error(`HTTP ${a.status}`);await t().fetchTasks()}catch(s){throw console.error("[ScheduledTasks] Delete error:",s),e({error:s.message}),s}}})),P8=[{label:"5m",cron:"*/5 * * * *"},{label:"30m",cron:"*/30 * * * *"},{label:"1h",cron:"7 * * * *"},{label:"1d",cron:"3 9 * * *"},{label:"1w",cron:"3 9 * * 1"}];function F8({onSubmit:e,onCancel:t}){const{t:r}=de(),[n,s]=C.useState("*/5 * * * *"),[a,l]=C.useState(""),[o,c]=C.useState(!0),[d,u]=C.useState(!1),[h,p]=C.useState(!1),[m,v]=C.useState(null),x=async()=>{if(!(!n.trim()||!a.trim())){p(!0),v(null);try{await e(n.trim(),a.trim(),o,d),t()}catch(f){v(f.message||"Failed to create task")}finally{p(!1)}}};return i.jsxs("div",{className:"border border-accent-brand/30 rounded-xl p-4 bg-bg-secondary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:r("scheduled.create")}),i.jsx("button",{onClick:t,className:"p-1 rounded hover:bg-bg-secondary text-text-tertiary",children:i.jsx(at,{size:14})})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.cron")}),i.jsx("input",{type:"text",value:n,onChange:f=>s(f.target.value),placeholder:"*/5 * * * *",className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none font-mono"}),i.jsx("div",{className:"flex gap-1.5 mt-1.5",children:P8.map(f=>i.jsx("button",{onClick:()=>s(f.cron),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${n===f.cron?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-tertiary hover:text-text-secondary hover:border-border-default/80"}`,children:f.label},f.label))})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.prompt")}),i.jsx("textarea",{value:a,onChange:f=>l(f.target.value),placeholder:r("scheduled.promptPlaceholder"),rows:2,className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none resize-none"})]}),i.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[i.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:o,onChange:f=>c(f.target.checked),className:"rounded"}),r("scheduled.recurring")]}),i.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:f=>u(f.target.checked),className:"rounded"}),r("scheduled.durable")]})]}),m&&i.jsx("div",{className:"text-xs text-accent-red mb-2",children:m}),i.jsxs("button",{onClick:x,disabled:h||!n.trim()||!a.trim(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[i.jsx(Ot,{size:14}),r(h?"scheduled.creating":"scheduled.create")]})]})}function z8({task:e,onDelete:t}){const{t:r}=de(),[n,s]=C.useState(!1),a=async()=>{s(!0);try{await t(e.id)}finally{s(!1)}},l=e.durable||e.permanent;return i.jsxs("div",{className:"group flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default hover:border-accent-brand/30 transition-colors",children:[i.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.recurring?i.jsx(KE,{size:18,className:"text-accent-blue"}):i.jsx(nw,{size:18,className:"text-accent-yellow"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:e.humanSchedule}),i.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${e.recurring?"bg-accent-blue/10 text-accent-blue":"bg-accent-yellow/10 text-accent-yellow"}`,children:e.recurring?r("scheduled.recurring"):r("scheduled.oneShot")}),l&&i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent-green/10 text-accent-green",children:r("scheduled.durable")})]}),i.jsx("p",{className:"text-xs text-text-secondary truncate",title:e.prompt,children:e.prompt}),i.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-[10px] text-text-tertiary",children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(ps,{size:10}),"ID: ",e.id]}),e.lastFiredAt&&i.jsxs("span",{children:[r("scheduled.lastFired"),": ",new Date(e.lastFiredAt).toLocaleString()]})]})]}),i.jsx("button",{onClick:a,disabled:n,className:"flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-accent-red/10 text-text-tertiary hover:text-accent-red transition-all disabled:opacity-50",title:r("scheduled.delete"),children:i.jsx(Oi,{size:14})})]})}const U8=3e3;function R1(){const{t:e}=de(),{setMainView:t}=De(),{setExternalInput:r,sessionId:n}=er(),{tasks:s,loading:a,fetchTasks:l,createTask:o,deleteTask:c}=B8(),[d,u]=C.useState(!1);C.useEffect(()=>{l()},[l,n]);const[h,p]=C.useState([]),[m,v]=C.useState(!0),[x,f]=C.useState(null),[b,g]=C.useState(!1),[_,y]=C.useState(!1),S=C.useRef(n);S.current=n;const w=C.useRef(null),k=C.useCallback(()=>{w.current&&(clearInterval(w.current),w.current=null)},[]),A=C.useCallback(async()=>{const L=new URLSearchParams,E=S.current;E&&L.append("sessionId",E);const M=L.toString(),O=await fetch(`/api/v1/tasks/templates${M?"?"+M:""}`,{headers:ve()});if(!O.ok)throw new Error(`HTTP ${O.status}`);const z=await O.json(),U=z.data??z;return p(U.templates||[]),f(U.error||null),U.status},[]),N=C.useCallback(()=>{k(),w.current=setInterval(async()=>{try{const L=await A();L!=="loading"&&(k(),g(!1),L==="done"&&(y(!0),setTimeout(()=>y(!1),2e3)))}catch(L){k(),g(!1),f(L.message||"Failed to load templates")}},U8)},[A,k]);C.useEffect(()=>{let L=!1;return(async()=>{try{if(!S.current){L||v(!1);return}const E=await A();if(L)return;E==="loading"&&(g(!0),N())}catch(E){L||f(E.message)}finally{L||v(!1)}})(),()=>{L=!0,k()}},[A,N,k,n]);const j=C.useCallback(async()=>{g(!0),f(null),y(!1);try{const L=new URLSearchParams,E=S.current;E&&L.append("sessionId",E);const M=L.toString(),O=await fetch(`/api/v1/tasks/templates/refresh${M?"?"+M:""}`,{method:"POST",headers:ve()});if(!O.ok)throw new Error(`HTTP ${O.status}`);N()}catch(L){f(L.message||"Failed to trigger refresh"),g(!1)}},[N]),$=C.useCallback(L=>{r({text:L.command}),t("chat")},[r,t]);return i.jsx("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:i.jsxs("div",{className:"flex-1 overflow-y-auto",children:[i.jsx("div",{className:"border-b border-border-default",children:i.jsxs("div",{className:"px-6 py-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("scheduled.title")}),i.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("scheduled.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>l(),className:"p-2 rounded-lg border border-border-default text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-colors",title:e("tasks.refresh"),children:i.jsx(St,{size:14,className:a?"animate-spin":""})}),i.jsxs("button",{onClick:()=>u(!d),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm transition-colors ${d?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/30"}`,children:[i.jsx(Ot,{size:14}),e("scheduled.create")]})]})]}),d&&i.jsx("div",{className:"mb-3",children:i.jsx(F8,{onSubmit:o,onCancel:()=>u(!1)})}),a&&s.length===0?i.jsxs("div",{className:"py-8 text-center text-text-tertiary text-sm",children:[i.jsx(St,{size:16,className:"animate-spin mx-auto mb-2"}),e("scheduled.loading")]}):s.length===0?i.jsxs("div",{className:"py-8 text-center",children:[i.jsx(ps,{size:32,className:"mx-auto mb-2 text-text-tertiary opacity-30"}),i.jsx("p",{className:"text-sm text-text-tertiary",children:e("scheduled.empty")}),i.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:e("scheduled.emptyHint")})]}):i.jsx("div",{className:"space-y-2",children:s.map(L=>i.jsx(z8,{task:L,onDelete:c},L.id))})]})}),i.jsxs("div",{className:"px-6 py-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("tasks.title")}),i.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("tasks.subtitle")})]}),i.jsxs("button",{onClick:j,disabled:b,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${_?"border-green-500/50 text-green-500":b?"opacity-50 cursor-not-allowed border-border-default text-text-secondary":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,children:[_?i.jsx(Fn,{size:14}):i.jsx(St,{size:14,className:b?"animate-spin":""}),i.jsx("span",{children:e(_?"tasks.refreshed":"tasks.refresh")})]})]}),m&&!b&&i.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:i.jsx(bn,{size:"small",text:e("tasks.loading")})}),x&&!m&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[i.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"!"}),i.jsx("div",{className:"text-text-secondary text-sm mb-4",children:e("tasks.error")}),i.jsx("button",{onClick:j,className:"px-4 py-2 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:e("tasks.retry")})]}),!m&&h.length===0&&!x&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:[i.jsx(KA,{size:32,className:"mb-2 opacity-30"}),i.jsx("div",{className:"text-sm",children:e("tasks.empty")})]}),h.length>0&&i.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${b?"opacity-50 pointer-events-none":"opacity-100"}`,children:h.map(L=>{const E=H8(L.icon);return i.jsxs("div",{onClick:()=>$(L),className:"group flex items-center gap-4 px-4 py-3.5 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all cursor-pointer",children:[i.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-bg-secondary flex items-center justify-center group-hover:bg-accent-brand/10 transition-colors",children:i.jsx(E,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:L.title}),i.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:L.description})]})]},L.id)})})]})]})})}function H8(e){switch(e){case"Newspaper":return my;case"MessageSquare":return my;case"GitBranch":return gs;case"Package":return EE;case"FileText":return an;case"Zap":return pi;case"Clock":return ps;default:return ps}}function Lu({node:e,path:t}){const r=De(a=>a.setRatio),n=Ei(a=>a.cwd),s=C.useCallback(a=>{r(t,a)},[r,t]);return e.type==="leaf"?i.jsx(Pl,{paneId:e.paneId,initialCwd:n}):i.jsxs(lh,{direction:e.direction,ratio:e.ratio,onRatioChange:s,children:[i.jsx(Lu,{node:e.children[0],path:[...t,0]}),i.jsx(Lu,{node:e.children[1],path:[...t,1]})]})}function L1(){const e=De(t=>t.layout);return i.jsx("div",{className:"flex-1 w-full h-full min-h-0 overflow-hidden",children:i.jsx(Lu,{node:e,path:[]})})}function G8({isOpen:e,onClose:t,onImageSelect:r,onFileSelect:n,onNewChat:s,onHistory:a,mainView:l}){const{t:o,tryT:c}=de(),d=C.useRef(null),[u,h]=C.useState(null),[p,m]=C.useState(0),{sessionId:v,modes:x,currentMode:f,models:b,currentModel:g,thinkingEnabled:_,setCurrentMode:y,setCurrentModel:S,setThinkingEnabled:w}=er(),k=C.useCallback((T,D)=>c(`mode.${T}`)||D||T,[c]),A=C.useCallback((T,D)=>c(`mode.${T}.desc`)||D,[c]),N=C.useCallback(async()=>{if(!v)return;const T=!_;w(T);try{await ze().setConfigOption(v,"thought_level",T?"enabled":"disabled")}catch(D){w(!T),console.error("[BottomSheet] toggle thinking failed:",D)}},[v,_,w]),j=C.useCallback(async T=>{if(!v||T===f)return;const D=f;y(T);try{await ze().setMode(v,T)}catch(R){y(D),console.error("[BottomSheet] setMode failed:",R)}},[v,f,y]),$=C.useCallback(async T=>{const D=T.target.value;if(!v||D===g)return;const R=g;S(D);try{await ze().setModel(v,D)}catch(G){S(R),console.error("[BottomSheet] setModel failed:",G)}},[v,g,S]),L=C.useCallback(()=>{r(),t()},[r,t]),E=C.useCallback(()=>{n(),t()},[n,t]),M=[{type:"attachment",icon:i.jsx(Wv,{size:22}),label:o("input.menu.image"),action:L},{type:"attachment",icon:i.jsx(an,{size:22}),label:o("input.menu.file"),action:E},{type:"action",icon:i.jsx(Ot,{size:20}),label:o("chat.newChat"),action:s},{type:"action",icon:i.jsx(Gv,{size:20}),label:o("sidebar.chatHistory"),action:a},{type:"nav",view:"changes",icon:i.jsx(Ll,{size:20}),label:o("sidebar.changes")},{type:"nav",view:"tasks",icon:i.jsx(Gu,{size:20}),label:o("sidebar.nav.tasks")},{type:"nav",view:"terminal",icon:i.jsx(qs,{size:20}),label:o("sidebar.terminalMode")},{type:"nav",view:"plugins",icon:i.jsx(Fs,{size:20}),label:o("sidebar.nav.plugins")},{type:"nav",view:"settings",icon:i.jsx(Dl,{size:20}),label:o("sidebar.preferences")}].filter(T=>!(T.type==="action"&&!T.action)),O=8,z=Math.ceil(M.length/O),U=[];for(let T=0;T<z;T++)U.push(M.slice(T*O,(T+1)*O));C.useEffect(()=>{const T=d.current;if(!T)return;const D=()=>{const R=T.clientWidth;if(R>0){const G=Math.round(T.scrollLeft/R);m(G)}};return T.addEventListener("scroll",D,{passive:!0}),()=>T.removeEventListener("scroll",D)},[]);const Q=C.useCallback(T=>{const D=d.current;D&&D.scrollTo({left:T*D.clientWidth,behavior:"smooth"})},[]),I=C.useCallback(()=>{h(null)},[]);return e?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"bottom-sheet-inline",children:[(x.length>0||b.length>0)&&i.jsxs("div",{className:"bottom-sheet-selectors",children:[x.length>0&&i.jsxs("div",{className:"bottom-sheet-selector-row",children:[i.jsx("label",{className:"bottom-sheet-selector-label",children:o("input.modeSelector")}),i.jsx("div",{className:"bottom-sheet-selector-chips",children:x.map(T=>{const D=k(T.id,T.name),R=A(T.id,T.description);return i.jsx("button",{type:"button",onClick:()=>j(T.id),className:`bottom-sheet-chip ${f===T.id?"active":""}`,title:R,children:D},T.id)})})]}),b.length>0&&i.jsxs("div",{className:"bottom-sheet-selector-row bottom-sheet-model-row",children:[i.jsxs("button",{type:"button",onClick:N,className:"bottom-sheet-thinking-toggle",title:o("input.deepThinkingDesc"),children:[i.jsx("span",{className:"bottom-sheet-thinking-icon",children:"∞"}),i.jsx("span",{className:"bottom-sheet-thinking-label",children:o("input.deepThinking")}),i.jsx("span",{className:`bottom-sheet-switch ${_?"on":""}`,children:i.jsx("span",{className:"bottom-sheet-switch-knob"})})]}),i.jsxs("div",{className:"bottom-sheet-model-line",children:[i.jsx("label",{className:"bottom-sheet-selector-label",htmlFor:"bottom-sheet-model-select",children:o("input.modelSelector")}),i.jsx("select",{id:"bottom-sheet-model-select",className:"bottom-sheet-model-select",value:g,onChange:$,children:b.map(T=>i.jsx("option",{value:T.id,children:T.name},T.id))})]})]})]}),i.jsx("div",{ref:d,className:"bottom-sheet-scroll",children:U.map((T,D)=>i.jsx("div",{className:"bottom-sheet-page",children:i.jsx("div",{className:"bottom-sheet-grid",children:T.map((R,G)=>i.jsxs("button",{className:R.type==="nav"&&l===R.view?"active":"",onClick:()=>{var P;R.type==="attachment"||R.type==="action"?(P=R.action)==null||P.call(R):R.type==="nav"&&R.view&&h(R.view)},children:[R.icon,i.jsx("span",{children:R.label})]},G))})},D))}),z>1&&i.jsx("div",{className:"bottom-sheet-pagination",children:Array.from({length:z}).map((T,D)=>i.jsx("button",{className:`pagination-dot ${D===p?"active":""}`,onClick:()=>Q(D)},D))})]}),u&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"floating-panel-overlay",onClick:I}),i.jsxs("div",{className:"floating-panel-container",children:[i.jsx("div",{className:"floating-panel-header",children:i.jsx("button",{onClick:I,className:"floating-panel-close-btn",title:o("common.close"),children:i.jsx(at,{size:24})})}),i.jsxs("div",{className:"floating-panel-content",children:[u==="changes"&&i.jsx(V0,{}),u==="tasks"&&i.jsx(R1,{}),u==="terminal"&&i.jsx(L1,{}),u==="plugins"&&i.jsx(T1,{}),u==="settings"&&i.jsx(N1,{})]})]})]})]}):null}const lv=5,D1=10*1024*1024,ya=["image/jpeg","image/png","image/gif","image/webp"];let M1=0;function W8(e){return!ya.includes(e.type)||e.size>D1?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const n=r.result,s=n.split(",")[1]||"";t({id:`img-${++M1}`,dataUrl:n,data:s,mimeType:e.type})},r.onerror=()=>t(null),r.readAsDataURL(e)})}const q8=10,Q8=1*1024*1024,V8=new Set([".txt",".md",".markdown",".json",".jsonl",".yaml",".yml",".toml",".xml",".html",".htm",".css",".scss",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".cpp",".h",".hpp",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".gql",".env",".ini",".cfg",".conf",".properties",".csv",".tsv",".log",".dockerfile",".makefile",".cmake",".gitignore",".gitattributes",".editorconfig",".vue",".svelte",".astro"]);let K8=0;function $1(e){if(e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||e.type==="application/javascript")return!0;const t=e.name.toLowerCase(),r=t.lastIndexOf(".");if(r!==-1){const s=t.slice(r);if(V8.has(s))return!0}const n=t.split("/").pop()||t;return!!["makefile","dockerfile","cmakelists.txt","gemfile","rakefile","procfile"].includes(n)}function Y8(e){return!$1(e)||e.size>Q8?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const n=r.result;t({id:`file-${++K8}`,name:e.name,size:e.size,text:n,mimeType:e.type||"text/plain"})},r.onerror=()=>t(null),r.readAsText(e)})}function Z8(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function X8({onNavigate:e,onNewChat:t,onHistory:r,mainView:n,showBottomSheet:s=!1,setShowBottomSheet:a}){const l=C.useCallback(Y=>{a&&a(typeof Y=="function"?Y(s):Y)},[a,s]),[o,c]=C.useState(()=>window.innerWidth<=768),[d,u]=C.useState(""),[h,p]=C.useState([]),[m,v]=C.useState([]),[x,f]=C.useState(0),[b,g]=C.useState(!1),[_,y]=C.useState(null),[S,w]=C.useState(0),[k,A]=C.useState([]),[N,j]=C.useState(0),[$,L]=C.useState(null),E=C.useRef(null),M=C.useRef(null),O=C.useRef(null),z=C.useRef(null),U=C.useRef(null),Q=C.useRef(null),I=C.useRef(null),T=C.useRef(null),D=C.useRef(null),R=C.useRef(null),G=C.useRef(0),P=C.useRef(!1),H=C.useRef(!1),{sessionId:q,commands:B,thinkingEnabled:F,setThinkingEnabled:Z,promptSuggestion:J,setPromptSuggestion:te,externalInput:ne,setExternalInput:re,modes:me,currentMode:he,models:pe,currentModel:ae,setCurrentMode:ye,setCurrentModel:be}=er(),[le,_e]=C.useState(!1),[Te,$e]=C.useState(!1),{isAgentRunning:Ze,hasPendingInterruption:ce,timeline:Ce,addUserMessage:Le,addQueuedUserMessage:lt,setSessionEnd:jt,resolveInterruption:Qt}=$t(),{t:xe,tryT:Ne}=de();C.useEffect(()=>{if(ne!==null){if(typeof ne.text=="string"&&u(ne.text),ne.images!==void 0){const Y=ne.images.slice(0,lv).map(oe=>({id:`img-${++M1}`,dataUrl:oe.dataUrl,data:oe.data,mimeType:oe.mimeType}));p(Y)}re(null),te(null),requestAnimationFrame(()=>{var Y;(Y=E.current)==null||Y.focus()})}},[ne,re,te]);const ir=C.useCallback(async Y=>{const oe=Array.from(Y).filter(Be=>ya.includes(Be.type)&&Be.size<=D1);if(oe.length===0)return;f(Be=>Be+oe.length);const Xe=(await Promise.all(oe.map(W8))).filter(Be=>Be!==null);f(Be=>Math.max(0,Be-oe.length)),Xe.length>0&&p(Be=>{const Vt=lv-Be.length;return[...Be,...Xe.slice(0,Vt)]})},[]),Ys=C.useCallback(Y=>{p(oe=>oe.filter(Se=>Se.id!==Y))},[]),zr=C.useCallback(async Y=>{const oe=Array.from(Y),Xe=(await Promise.all(oe.map(Y8))).filter(Be=>Be!==null);Xe.length!==0&&v(Be=>{const Vt=q8-Be.length;return[...Be,...Xe.slice(0,Vt)]})},[]),vn=C.useCallback(Y=>{v(oe=>oe.filter(Se=>Se.id!==Y))},[]),_s=C.useCallback(Y=>{var oe;Y.preventDefault(),Y.stopPropagation(),G.current++,(oe=Y.dataTransfer)!=null&&oe.types.includes("Files")&&g(!0)},[]),so=C.useCallback(Y=>{Y.preventDefault(),Y.stopPropagation(),G.current--,G.current===0&&g(!1)},[]),io=C.useCallback(Y=>{Y.preventDefault(),Y.stopPropagation()},[]),Ur=C.useCallback(Y=>{var oe;if(Y.preventDefault(),Y.stopPropagation(),G.current=0,g(!1),(oe=Y.dataTransfer)!=null&&oe.files){const Se=Array.from(Y.dataTransfer.files),Xe=Se.filter(Vt=>ya.includes(Vt.type)),Be=Se.filter(Vt=>!ya.includes(Vt.type)&&$1(Vt));Xe.length>0&&ir(Xe),Be.length>0&&zr(Be)}},[ir,zr]),Zi=C.useCallback(Y=>{var Se;const oe=(Se=Y.clipboardData)==null?void 0:Se.files;oe&&oe.length>0&&Array.from(oe).some(Be=>ya.includes(Be.type))&&(Y.preventDefault(),ir(oe))},[ir]),Xi=C.useCallback(()=>{var Y;(Y=M.current)==null||Y.click()},[]),oc=C.useCallback(()=>{var Y;(Y=O.current)==null||Y.click()},[]),Gn=C.useCallback(Y=>{Y.target.files&&ir(Y.target.files),Y.target.value=""},[ir]),lc=C.useCallback(Y=>{Y.target.files&&zr(Y.target.files),Y.target.value=""},[zr]),ln=C.useMemo(()=>{const Y=d.trimStart();if(!Y.startsWith("/")||Y.includes(" "))return[];const oe=Y.substring(1).toLowerCase();return B.filter(Se=>{const Xe=Ne(`command.${Se.name}.description`)??Se.description;return Se.name.toLowerCase().includes(oe)||Se.description.toLowerCase().includes(oe)||Xe.toLowerCase().includes(oe)}).slice(0,8)},[d,B,Ne]),Wn=ln.length>0;C.useEffect(()=>{w(0)},[ln.length]),C.useEffect(()=>{if(Wn&&z.current){const Y=z.current.children[S];Y==null||Y.scrollIntoView({block:"nearest"})}},[S,Wn]);const Ji=C.useMemo(()=>{if($===null)return null;const Y=d.substring($+1),oe=Y.search(/\s/),Se=oe===-1?Y:Y.substring(0,oe);return oe===0?null:Se},[d,$]),qn=Ji!==null&&k.length>0,ea=C.useRef(null);C.useEffect(()=>{if(Ji===null){A([]);return}return ea.current&&clearTimeout(ea.current),ea.current=setTimeout(async()=>{try{const Y=new URLSearchParams;Ji&&Y.set("query",Ji),Y.set("limit","15");const oe=await fetch(`/api/v1/fs/search?${Y.toString()}`,{headers:ve()});if(oe.ok){const Se=await oe.json();A(Se.items||[]),j(0)}else A([])}catch{A([])}},150),()=>{ea.current&&clearTimeout(ea.current)}},[Ji]),C.useEffect(()=>{if(qn&&U.current){const Y=U.current.children[N];Y==null||Y.scrollIntoView({block:"nearest"})}},[N,qn]);const cc=C.useRef(!1),dc=C.useCallback(Y=>{if($===null)return;const oe=d.substring(0,$),Se=d.substring($+1),Xe=Se.search(/\s/),Be=Xe===-1?"":Se.substring(Xe),cn=Be.length===0||!/^\s/.test(Be)?" ":"",vs=`${oe}@${Y.path}${cn}${Be}`,ta=oe.length+1+Y.path.length+cn.length;u(vs),A([]),L(null),cc.current=!0,requestAnimationFrame(()=>{const Zs=E.current;Zs&&(Zs.focus(),Zs.setSelectionRange(ta,ta))})},[d,$]);C.useEffect(()=>{const Y=()=>c(window.innerWidth<=768);return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),C.useEffect(()=>{var Y;!o&&!Ze&&((Y=E.current)==null||Y.focus())},[o,Ze]),C.useEffect(()=>{const Y=E.current;if(Y){Y.style.height="auto";const oe=window.innerHeight*.2,Se=Math.min(Y.scrollHeight,oe);Y.style.height=`${Se}px`,Y.style.overflowY=Y.scrollHeight>oe?"auto":"hidden"}},[d]);const uc=C.useCallback(Y=>{var oe;u(`/${Y.name} `),(oe=E.current)==null||oe.focus()},[]),xs=C.useCallback(async Y=>{var Jb;const oe=(Y??d).trim(),Se=h.length>0,Xe=m.length>0;if(!oe&&!(Se||Xe)||!q||ce)return;u(""),te(null);const Vt=[...h],cn=[...m];p([]),v([]);const vs=Vt.length>0?Vt.map(ft=>({data:ft.data,mimeType:ft.mimeType})):void 0,ta=cn.length>0?cn.map(ft=>({name:ft.name,text:ft.text,mimeType:ft.mimeType})):void 0,Zs=cn.length>0?cn.map(ft=>({name:ft.name,size:ft.size,mimeType:ft.mimeType})):void 0;if((Jb=E.current)==null||Jb.blur(),Ze)lt(oe,vs,Zs),ze().prompt(q,oe,vs,ta).catch(ft=>{console.error("Queued prompt failed:",ft)});else{if(H.current)return;H.current=!0,Le(oe,vs,Zs);try{const ft=await ze().prompt(q,oe,vs,ta);jt(ft.stopReason,ft.errorMessage,ft.errorCategory)}catch(ft){console.error("Prompt failed:",ft),jt("error",ft instanceof Error?ft.message:xe("input.promptFailed"))}finally{H.current=!1}}},[d,h,m,q,Ze,ce,Le,lt,jt,te,xe]),F1=C.useCallback(async()=>{if(q)try{const Y=ze(),oe=Ce.filter(Se=>Se.type==="interruption"&&!Se.resolved);for(const Se of oe)if(Se.type==="interruption")try{await Y.respondToInterruption(q,Se.id,"deny",Se.toolCallId),Qt(Se.id,"deny")}catch{}await Y.cancel(q)}catch(Y){console.error("Cancel failed:",Y)}},[q,Ce,Qt]),z1=C.useCallback(()=>{P.current=!0},[]),U1=C.useCallback(()=>{P.current=!1},[]),H1=C.useCallback(Y=>{Y.preventDefault(),y({x:Y.clientX,y:Y.clientY})},[]),G1=C.useCallback(()=>{const Y=E.current;if(!Y)return;const oe=Y.selectionStart??d.length,Se=Y.selectionEnd??oe,Xe=d.slice(0,oe)+`
1031
1031
  `+d.slice(Se);u(Xe),y(null),requestAnimationFrame(()=>{Y.selectionStart=Y.selectionEnd=oe+1,Y.focus()})},[d]),W1=C.useCallback(()=>{y(null),xs()},[xs]);C.useEffect(()=>{if(!_)return;const Y=()=>y(null),oe=()=>y(null);return document.addEventListener("mousedown",Y),document.addEventListener("scroll",oe,!0),()=>{document.removeEventListener("mousedown",Y),document.removeEventListener("scroll",oe,!0)}},[_]),C.useEffect(()=>{if(!Wn)return;const Y=oe=>{z.current&&!z.current.contains(oe.target)&&u("")};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[Wn]),C.useEffect(()=>{if(!s)return;const Y=oe=>{const Se=oe.target;I.current&&!I.current.contains(Se)&&T.current&&!T.current.contains(Se)&&l(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[s,l]),C.useEffect(()=>{if(!qn)return;const Y=oe=>{U.current&&!U.current.contains(oe.target)&&(L(null),A([]))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[qn]);const q1=C.useCallback(Y=>{if(Wn){if(Y.key==="ArrowUp"){Y.preventDefault(),w(oe=>oe>0?oe-1:ln.length-1);return}if(Y.key==="ArrowDown"){Y.preventDefault(),w(oe=>oe<ln.length-1?oe+1:0);return}if(Y.key==="Tab"||Y.key==="Enter"&&!Y.shiftKey&&!P.current&&!Y.nativeEvent.isComposing){Y.preventDefault(),uc(ln[S]);return}if(Y.key==="Escape"){Y.preventDefault(),u("");return}}if(qn){if(Y.key==="ArrowUp"){Y.preventDefault(),j(oe=>oe>0?oe-1:k.length-1);return}if(Y.key==="ArrowDown"){Y.preventDefault(),j(oe=>oe<k.length-1?oe+1:0);return}if(Y.key==="Tab"||Y.key==="Enter"&&!Y.shiftKey&&!P.current&&!Y.nativeEvent.isComposing){Y.preventDefault(),dc(k[N]);return}if(Y.key==="Escape"){Y.preventDefault(),L(null),A([]);return}}if(Y.key==="Tab"&&!Wn&&!qn&&J&&!d){Y.preventDefault(),u(J),te(null);return}if(Y.key==="Enter"&&!Y.shiftKey&&!P.current&&!Y.nativeEvent.isComposing){if(Y.preventDefault(),!d&&J&&!Ze&&!ce){xs(J);return}xs()}},[xs,Wn,ln,S,uc,qn,k,N,dc,J,d,te,Ze,ce]),Q1=C.useCallback(async()=>{if(!q)return;const Y=!F;Z(Y);try{await ze().setConfigOption(q,"thought_level",Y?"enabled":"disabled")}catch(oe){Z(!Y),console.error("Toggle thinking failed:",oe)}},[q,F,Z]),V1=C.useCallback(async Y=>{if(_e(!1),!q||Y===he)return;const oe=he;ye(Y);try{await ze().setMode(q,Y)}catch(Se){ye(oe),console.error("[InputBox] setMode failed:",Se)}},[q,he,ye]),K1=C.useCallback(async Y=>{if($e(!1),!q||Y===ae)return;const oe=ae;be(Y);try{await ze().setModel(q,Y)}catch(Se){be(oe),console.error("[InputBox] setModel failed:",Se)}},[q,ae,be]);C.useEffect(()=>{if(!le&&!Te)return;const Y=oe=>{D.current&&!D.current.contains(oe.target)&&_e(!1),R.current&&!R.current.contains(oe.target)&&$e(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[le,Te]);const hc=C.useCallback((Y,oe)=>Ne(`mode.${Y}`)||oe||Y,[Ne]),Y1=C.useCallback((Y,oe)=>Ne(`mode.${Y}.desc`)||oe,[Ne]),Z1=C.useMemo(()=>{const Y=me.find(oe=>oe.id===he);return hc(he,Y==null?void 0:Y.name)||"Mode"},[me,he,hc]),X1=C.useMemo(()=>{const Y=pe.find(oe=>oe.id===ae);return(Y==null?void 0:Y.name)||ae||"Model"},[pe,ae]),Xb=!ce&&(d.trim().length>0||h.length>0||m.length>0||!!J&&!d&&!Ze),J1=h.length>0||m.length>0||x>0;return i.jsx("div",{className:"px-0 pb-[env(safe-area-inset-bottom)] pt-0 md:px-4 md:pb-6 md:pt-2",children:i.jsxs("div",{className:"max-w-3xl mx-auto",children:[e&&n!==void 0&&i.jsx("div",{ref:I,children:i.jsx(G8,{isOpen:s,onClose:()=>l(!1),onImageSelect:Xi,onFileSelect:oc,onNewChat:t,onHistory:r,mainView:n,onNavigate:e})}),i.jsxs("div",{className:`relative bg-bg-secondary rounded-none md:rounded-2xl shadow-sm transition-all focus-within:shadow-md border-t md:border ${b?"border-accent-brand border-dashed bg-accent-brand/5":"border-border-default"}`,onDragEnter:_s,onDragLeave:so,onDragOver:io,onDrop:Ur,children:[b&&i.jsx("div",{className:"absolute inset-0 z-20 rounded-2xl flex items-center justify-center bg-accent-brand/5 pointer-events-none",children:i.jsx("span",{className:"text-accent-brand text-[14px] font-medium",children:xe("input.dropHint")})}),Wn&&i.jsx("div",{ref:z,className:"absolute bottom-full left-3 right-3 mb-2 bg-bg-secondary rounded-xl border border-border-default shadow-lg max-h-[280px] overflow-y-auto z-10 py-1",children:ln.map((Y,oe)=>i.jsxs("button",{className:`w-full text-left px-3 py-2 flex items-baseline gap-3 transition-colors ${oe===S?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>w(oe),onMouseDown:Se=>{Se.preventDefault(),uc(Y)},children:[i.jsxs("span",{className:"font-mono text-[13px] font-medium shrink-0",children:["/",Y.name]}),Y.type==="skill"&&i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-accent-brand/15 text-accent-brand font-medium shrink-0",children:"Skill"}),i.jsx("span",{className:"text-text-tertiary text-[12px] truncate",children:Ne(`command.${Y.name}.description`)??Y.description})]},Y.name))}),qn&&i.jsx("div",{ref:U,className:"absolute bottom-full left-3 right-3 mb-2 bg-bg-secondary rounded-xl border border-border-default shadow-lg max-h-[280px] overflow-y-auto z-10 py-1",children:k.map((Y,oe)=>i.jsxs("button",{className:`w-full text-left px-3 py-2 flex items-center gap-3 transition-colors ${oe===N?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>j(oe),onMouseDown:Se=>{Se.preventDefault(),dc(Y)},children:[Y.type==="directory"?i.jsx(Uu,{size:14,className:"shrink-0 text-accent-brand"}):i.jsx(an,{size:14,className:"shrink-0 text-text-tertiary"}),i.jsx("span",{className:"font-mono text-[13px] truncate",children:Y.name}),i.jsx("span",{className:"text-text-tertiary text-[11px] truncate ml-auto",children:Y.path})]},Y.path))}),J1&&i.jsxs("div",{className:"px-4 pt-3 pb-1 flex flex-wrap gap-2",children:[h.map(Y=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:Y.dataUrl,alt:"",className:"w-16 h-16 rounded-lg object-cover border border-border-default"}),i.jsx("button",{onClick:()=>Ys(Y.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-bg-tertiary border border-border-default flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-accent-red hover:border-accent-red hover:text-white",children:i.jsx(at,{size:12})})]},Y.id)),Array.from({length:x}).map((Y,oe)=>i.jsx("div",{className:"w-16 h-16 rounded-lg border border-border-default skeleton-shimmer"},`skeleton-${oe}`)),m.map(Y=>i.jsxs("div",{className:"relative group flex items-center gap-2 px-3 py-2 rounded-lg border border-border-default bg-bg-primary max-w-[200px]",children:[i.jsx(an,{size:16,className:"shrink-0 text-text-tertiary"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"text-[12px] text-text-primary truncate",title:Y.name,children:Y.name}),i.jsx("div",{className:"text-[11px] text-text-tertiary",children:Z8(Y.size)})]}),i.jsx("button",{onClick:()=>vn(Y.id),className:"shrink-0 w-4 h-4 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-text-tertiary hover:text-accent-red",children:i.jsx(at,{size:12})})]},Y.id))]}),i.jsxs("div",{className:"relative",children:[i.jsx("textarea",{ref:E,value:d,onChange:Y=>{const oe=Y.target.value,Se=Y.target.selectionStart??oe.length;if(u(oe),cc.current){cc.current=!1;return}let Xe=null;for(let Be=Se-1;Be>=0;Be--){const Vt=oe[Be];if(Vt==="@"){const cn=Be>0?oe[Be-1]:" ";(cn===" "||cn===`
1032
1032
  `||Be===0)&&(oe.substring(Be+1,Se).includes(" ")||(Xe=Be));break}if(Vt===" "||Vt===`
1033
1033
  `)break}Xe!==null?$!==Xe&&(L(Xe),j(0)):$!==null&&(L(null),A([]))},onCompositionStart:z1,onCompositionEnd:U1,onKeyDown:q1,onPaste:Zi,onContextMenu:H1,onFocus:()=>l(!1),placeholder:ce?xe("input.placeholderPending"):Ze?xe("input.placeholderRunning"):J?"":xe("input.placeholder"),enterKeyHint:"send",rows:1,"aria-label":"Message input",className:["w-full bg-transparent text-text-primary text-chat px-5 pt-4 pb-2","resize-none outline-none placeholder:text-text-tertiary"].join(" ")}),J&&!d&&!Ze&&!ce&&i.jsx("div",{className:"absolute inset-0 flex items-start px-5 pt-4 pb-2 pointer-events-none overflow-hidden",children:i.jsx("span",{className:"text-chat text-text-tertiary truncate max-w-full",children:J})})]}),_&&i.jsxs("div",{ref:Q,className:"fixed z-50 bg-bg-secondary rounded-xl border border-border-default shadow-lg overflow-hidden min-w-[120px]",style:{left:_.x,top:_.y},onMouseDown:Y=>Y.stopPropagation(),children:[i.jsxs("button",{className:"w-full text-left px-4 py-2.5 flex items-center gap-2.5 text-text-primary hover:bg-bg-primary transition-colors text-[13px]",onMouseDown:Y=>{Y.preventDefault(),Y.stopPropagation(),G1()},children:[i.jsx(hy,{size:14,className:"text-text-tertiary"}),xe("input.contextMenu.newline")]}),Xb&&i.jsxs("button",{className:"w-full text-left px-4 py-2.5 flex items-center gap-2.5 text-text-primary hover:bg-bg-primary transition-colors text-[13px]",onMouseDown:Y=>{Y.preventDefault(),Y.stopPropagation(),W1()},children:[i.jsx(Jo,{size:14,className:"text-text-tertiary"}),xe("input.contextMenu.send")]})]}),i.jsx("input",{ref:M,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:Gn}),i.jsx("input",{ref:O,type:"file",accept:".txt,.md,.json,.yaml,.yml,.toml,.xml,.html,.css,.scss,.js,.jsx,.ts,.tsx,.py,.rb,.go,.rs,.java,.kt,.swift,.c,.cpp,.h,.hpp,.sh,.bash,.sql,.csv,.tsv,.log,.env,.ini,.cfg,.conf,.vue,.svelte,.astro,.graphql,.gql,.makefile,.dockerfile,.gitignore,.editorconfig",multiple:!0,className:"hidden",onChange:lc}),i.jsxs("div",{className:"flex items-center justify-between px-3 py-2",onClick:Y=>{var oe;Y.target===Y.currentTarget&&((oe=E.current)==null||oe.focus())},children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[me.length>0&&i.jsxs("div",{className:"relative flex-shrink min-w-0",ref:D,children:[i.jsxs("button",{type:"button",onClick:()=>{_e(Y=>!Y),$e(!1)},className:"flex items-center gap-1 px-2.5 py-1 rounded-full border border-border-default bg-bg-primary text-text-secondary hover:text-text-primary transition-colors max-w-[140px]",title:xe("input.modeSelector"),children:[i.jsx("span",{className:"text-[13px] truncate",children:Z1}),i.jsx(rt,{size:12,className:"flex-shrink-0"})]}),le&&i.jsx("div",{className:"absolute bottom-full left-0 mb-2 bg-bg-secondary border border-border-default rounded-lg shadow-lg z-50 min-w-[200px] max-h-[280px] overflow-y-auto py-1",children:me.map(Y=>{const oe=hc(Y.id,Y.name),Se=Y1(Y.id,Y.description);return i.jsxs("button",{onClick:()=>V1(Y.id),className:`w-full text-left px-3 py-1.5 text-[13px] transition-colors ${he===Y.id?"bg-bg-primary text-text-primary font-medium":"text-text-secondary hover:bg-bg-primary hover:text-text-primary"}`,title:Se,children:[i.jsx("div",{className:"truncate",children:oe}),Se&&i.jsx("div",{className:"text-[11px] text-text-tertiary mt-0.5 truncate",children:Se})]},Y.id)})})]}),pe.length>0&&i.jsxs("div",{className:"relative flex-shrink min-w-0",ref:R,children:[i.jsxs("button",{type:"button",onClick:()=>{$e(Y=>!Y),_e(!1)},className:"flex items-center gap-1 px-2.5 py-1 rounded-full border border-border-default bg-bg-primary text-text-secondary hover:text-text-primary transition-colors max-w-[180px]",title:F?`${xe("input.modelSelector")} · ${xe("input.deepThinking")}`:xe("input.modelSelector"),children:[F&&i.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center text-[12px] font-semibold flex-shrink-0",children:"∞"}),i.jsx("span",{className:"text-[13px] truncate",children:X1}),i.jsx(rt,{size:12,className:"flex-shrink-0"})]}),Te&&i.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-bg-secondary border border-border-default rounded-lg shadow-lg z-50 min-w-[240px] max-h-[320px] overflow-hidden flex flex-col",children:[i.jsxs("button",{type:"button",onClick:Q1,className:"flex items-center gap-2 px-3 py-2 border-b border-border-default bg-bg-primary hover:bg-bg-secondary transition-colors flex-shrink-0",title:xe("input.deepThinkingDesc"),children:[i.jsx("span",{className:"w-4 h-4 flex items-center justify-center text-[12px] font-semibold flex-shrink-0",children:"∞"}),i.jsx("span",{className:"flex-1 text-left text-[13px] font-medium text-text-primary truncate",children:xe("input.deepThinking")}),i.jsx("span",{className:`relative inline-flex w-7 h-4 rounded-full transition-colors flex-shrink-0 ${F?"bg-text-primary":"bg-border-default"}`,children:i.jsx("span",{className:`absolute top-0.5 w-3 h-3 rounded-full bg-bg-primary transition-transform ${F?"translate-x-3.5":"translate-x-0.5"}`})})]}),i.jsx("div",{className:"overflow-y-auto py-1",children:pe.map(Y=>i.jsx("button",{onClick:()=>K1(Y.id),className:`w-full text-left px-3 py-1.5 text-[13px] transition-colors ${ae===Y.id?"bg-bg-primary text-text-primary font-medium":"text-text-secondary hover:bg-bg-primary hover:text-text-primary"}`,children:i.jsx("span",{className:"truncate block",children:Y.name})},Y.id))})]})]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[!Ze&&i.jsx("button",{ref:T,onClick:()=>l(Y=>!Y),className:"flex items-center justify-center w-8 h-8 rounded-full text-text-tertiary hover:text-text-primary hover:bg-bg-primary transition-colors",title:xe("input.addFile"),children:i.jsx(Ot,{size:18})}),o&&i.jsx("button",{onClick:()=>{const Y=E.current;if(!Y)return;const oe=Y.selectionStart??d.length,Se=Y.selectionEnd??oe,Xe=d.slice(0,oe)+`