ai-cli-online 2.9.7 → 2.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -6,7 +6,7 @@ var jn=Object.defineProperty;var In=(n,e,t)=>e in n?jn(n,e,{enumerable:!0,config
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var Ln=a,Mn=Symbol.for("react.element"),An=Symbol.for("react.fragment")
|
|
9
|
+
*/var Ln=a,Mn=Symbol.for("react.element"),An=Symbol.for("react.fragment"),zn=Object.prototype.hasOwnProperty,$n=Ln.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,_n={key:!0,ref:!0,__self:!0,__source:!0};function nn(n,e,t){var o,s={},l=null,i=null;t!==void 0&&(l=""+t),e.key!==void 0&&(l=""+e.key),e.ref!==void 0&&(i=e.ref);for(o in e)zn.call(e,o)&&!_n.hasOwnProperty(o)&&(s[o]=e[o]);if(n&&n.defaultProps)for(o in e=n.defaultProps,e)s[o]===void 0&&(s[o]=e[o]);return{$$typeof:Mn,type:n,key:l,ref:i,props:s,_owner:$n.current}}st.Fragment=An;st.jsx=nn;st.jsxs=nn;tn.exports=st;var r=tn.exports,gt={},Dt=Rn;gt.createRoot=Dt.createRoot,gt.hydrateRoot=Dt.hydrateRoot;const On={},Lt=n=>{let e;const t=new Set,o=(h,p)=>{const m=typeof h=="function"?h(e):h;if(!Object.is(m,e)){const x=e;e=p??(typeof m!="object"||m===null)?m:Object.assign({},e,m),t.forEach(C=>C(e,x))}},s=()=>e,u={setState:o,getState:s,getInitialState:()=>c,subscribe:h=>(t.add(h),()=>t.delete(h)),destroy:()=>{t.clear()}},c=e=n(o,s,u);return u},Fn=n=>n?Lt(n):Lt;var rn={exports:{}},on={},sn={exports:{}},an={};/**
|
|
10
10
|
* @license React
|
|
11
11
|
* use-sync-external-store-shim.production.js
|
|
12
12
|
*
|
|
@@ -22,11 +22,11 @@ var jn=Object.defineProperty;var In=(n,e,t)=>e in n?jn(n,e,{enumerable:!0,config
|
|
|
22
22
|
*
|
|
23
23
|
* This source code is licensed under the MIT license found in the
|
|
24
24
|
* LICENSE file in the root directory of this source tree.
|
|
25
|
-
*/var at=a,Gn=Yn;function Xn(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var Zn=typeof Object.is=="function"?Object.is:Xn,Qn=Gn.useSyncExternalStore,er=at.useRef,tr=at.useEffect,nr=at.useMemo,rr=at.useDebugValue;on.useSyncExternalStoreWithSelector=function(n,e,t,o,s){var l=er(null);if(l.current===null){var i={hasValue:!1,value:null};l.current=i}else i=l.current;l=nr(function(){function u(x){if(!c){if(c=!0,h=x,x=o(x),s!==void 0&&i.hasValue){var C=i.value;if(s(C,x))return p=C}return p=x}if(C=p,Zn(h,x))return C;var z=o(x);return s!==void 0&&s(C,z)?(h=x,C):(h=x,p=z)}var c=!1,h,p,m=t===void 0?null:t;return[function(){return u(e())},m===null?void 0:function(){return u(m())}]},[e,t,o,s]);var d=Qn(n,l[0],l[1]);return tr(function(){i.hasValue=!0,i.value=d},[d]),rr(d),d};rn.exports=on;var or=rn.exports;const sr=Nn(or),ln={},{useDebugValue:ar}=St,{useSyncExternalStoreWithSelector:ir}=sr;let Mt=!1;const lr=n=>n;function cr(n,e=lr,t){(ln?"production":void 0)!=="production"&&t&&!Mt&&(Mt=!0);const o=ir(n.subscribe,n.getState,n.getServerState||n.getInitialState,e,t);return ar(o),o}const At=n=>{const e=typeof n=="function"?Fn(n):n,t=(o,s)=>cr(e,o,s);return Object.assign(t,e),t},dr=n=>n?At(n):At,se="";function ie(n){return{Authorization:`Bearer ${n}`}}async function ur(n){try{const e=await fetch(`${se}/api/settings/font-size`,{headers:ie(n)});return e.ok?(await e.json()).fontSize:14}catch{return 14}}async function fr(n,e){try{await fetch(`${se}/api/settings/font-size`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({fontSize:e})})}catch{}}async function pr(n){try{const e=await fetch(`${se}/api/settings/tabs-layout`,{headers:ie(n)});return e.ok?(await e.json()).layout:null}catch{return null}}async function mr(n,e){try{await fetch(`${se}/api/settings/tabs-layout`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({layout:e})})}catch{}}function $t(n,e){try{const t=`${se}/api/settings/tabs-layout`,o=JSON.stringify({layout:e,token:n});navigator.sendBeacon(t,new Blob([o],{type:"application/json"}))}catch{}}const tt="ai-cli-online-tabs",zt="ai-cli-online-layout",_t="ai-cli-online-session-names";function nt(n,e){if(n.type==="leaf")return n.terminalId===e?null:n;const t=[],o=[];for(let i=0;i<n.children.length;i++){const d=nt(n.children[i],e);d!==null&&(t.push(d),o.push(n.sizes[i]))}if(t.length===0)return null;if(t.length===1)return t[0];const s=o.reduce((i,d)=>i+d,0),l=o.map(i=>i/s*100);return{...n,children:t,sizes:l}}function cn(n,e,t,o,s){return n.type==="leaf"?n.terminalId===e?{id:s,type:"split",direction:t,children:[n,o],sizes:[50,50]}:n:{...n,children:n.children.map(l=>cn(l,e,t,o,s))}}function dn(n,e,t){return n.type==="leaf"?n:n.id===e?{...n,sizes:t}:{...n,children:n.children.map(o=>dn(o,e,t))}}function ft(n){return n.tabs.find(e=>e.id===n.activeTabId)}function Le(n,e,t){return n.map(o=>o.id===e?t(o):o)}function pe(n){const e={version:2,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId,tabs:n.tabs};try{localStorage.setItem(tt,JSON.stringify(e))}catch{}hr(e)}let Ge=null,Xe=null,Oe=null,qe=null;function hr(n){qe=n,Oe&&clearTimeout(Oe),Oe=setTimeout(()=>{Oe=null,qe=null;const e=M.getState().token;e&&mr(e,n)},2e3)}function br(n){Ge&&clearTimeout(Ge),Ge=setTimeout(()=>{Ge=null,pe(n)},500)}function xr(){try{const n=localStorage.getItem(tt);if(n){const e=JSON.parse(n);if(e.version===2)return e}}catch{}try{const n=localStorage.getItem(zt);if(n){const e=JSON.parse(n);let t="Default";try{const l=localStorage.getItem(_t);if(l){const i=JSON.parse(l),d=Object.values(i)[0];d&&(t=d)}}catch{}const o={id:"tab1",name:t,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},s={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[o]};try{localStorage.setItem(tt,JSON.stringify(s))}catch{}return localStorage.removeItem(zt),localStorage.removeItem(_t),s}}catch{}return null}function ue(n){return{tabs:n.tabs,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId}}function gr(n,e){const t=new Set(e.map(i=>i.sessionId)),o=[];for(const i of n.tabs){if(i.status!=="open"){const c=i.terminalIds.filter(h=>t.has(h));if(c.length>0){let h=i.layout;for(const p of i.terminalIds)!t.has(p)&&h&&(h=nt(h,p));o.push({...i,terminalIds:c,layout:h})}continue}const d=i.terminalIds.filter(c=>t.has(c));if(d.length===0)continue;let u=i.layout;for(const c of i.terminalIds)!t.has(c)&&u&&(u=nt(u,c));o.push({...i,terminalIds:d,layout:u})}if(o.filter(i=>i.status==="open").length===0)return null;let s=n.activeTabId;if(!o.find(i=>i.id===s&&i.status==="open")){const i=o.find(d=>d.status==="open");s=(i==null?void 0:i.id)||""}return{...n,activeTabId:s,tabs:o}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var e,t;const n=(t=(e=M==null?void 0:M.getState)==null?void 0:e.call(M))==null?void 0:t.token;if(n)if(qe)Oe&&(clearTimeout(Oe),Oe=null),$t(n,qe),qe=null;else{const o=M.getState();o.tabs.length>0&&$t(n,ue(o))}});function Ot(n,e){const t=n.tabs.find(c=>c.terminalIds.includes(e));if(!t){const{[e]:c,...h}=n.terminalsMap;return{terminalsMap:h}}const o=t.terminalIds.filter(c=>c!==e),s=t.layout?nt(t.layout,e):null,l=Le(n.tabs,t.id,c=>({...c,terminalIds:o,layout:s})),{[e]:i,...d}=n.terminalsMap,u={terminalsMap:d,tabs:l};return t.id===n.activeTabId&&(u.terminalIds=o,u.layout=s),u}const M=dr((n,e)=>({token:null,tabsLoading:!1,setToken:t=>{var o;if(t){try{localStorage.setItem("ai-cli-online-token",t)}catch{}ur(t).then(l=>{e().token===t&&n({fontSize:l})});const s=xr();if(s&&s.tabs.length>0){const l={};for(const u of s.tabs)if(u.status==="open")for(const c of u.terminalIds)l[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((o=u.panelStates)==null?void 0:o[c])||{chatOpen:!1,planOpen:!1}};const i=s.tabs.find(u=>u.id===s.activeTabId&&u.status==="open")||s.tabs.find(u=>u.status==="open"),d=(i==null?void 0:i.id)||"";n({token:t,tabsLoading:!0,terminalsMap:l,tabs:s.tabs,activeTabId:d,nextId:s.nextId,nextSplitId:s.nextSplitId,nextTabId:s.nextTabId,terminalIds:(i==null?void 0:i.terminalIds)||[],layout:(i==null?void 0:i.layout)||null})}else n({token:t,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});yr(t,s);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(tt),n({token:t,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:t=>{const o=e(),s=`tab${o.nextTabId}`,l=`t${o.nextId}`,i={id:l,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},d={type:"leaf",terminalId:l},u={id:s,name:t||`Tab ${o.nextTabId}`,status:"open",terminalIds:[l],layout:d,createdAt:Date.now()};return n({tabs:[...o.tabs,u],activeTabId:s,nextTabId:o.nextTabId+1,nextId:o.nextId+1,terminalsMap:{...o.terminalsMap,[l]:i},terminalIds:u.terminalIds,layout:u.layout}),pe(ue(e())),s},switchTab:t=>{const s=e().tabs.find(l=>l.id===t);!s||s.status!=="open"||(n({activeTabId:t,terminalIds:s.terminalIds,layout:s.layout}),pe(ue(e())))},closeTab:t=>{const o=e(),s=o.tabs.find(p=>p.id===t);if(!s||s.status!=="open"||o.tabs.filter(p=>p.status==="open").length<=1)return;const i={...o.terminalsMap};for(const p of s.terminalIds)delete i[p];const d=Le(o.tabs,t,p=>({...p,status:"closed"}));let u=o.activeTabId,c=o.terminalIds,h=o.layout;if(o.activeTabId===t){const p=o.tabs.findIndex(C=>C.id===t),m=d.filter(C=>C.status==="open"),x=m.find(C=>d.findIndex(N=>N.id===C.id)>p)||m[m.length-1];x&&(u=x.id,c=x.terminalIds,h=x.layout)}n({tabs:d,activeTabId:u,terminalsMap:i,terminalIds:c,layout:h}),pe(ue(e()))},reopenTab:t=>{var d;const o=e(),s=o.tabs.find(u=>u.id===t);if(!s||s.status!=="closed")return;const l={...o.terminalsMap};for(const u of s.terminalIds)l[u]={id:u,connected:!1,sessionResumed:!1,error:null,panels:((d=s.panelStates)==null?void 0:d[u])||{chatOpen:!1,planOpen:!1}};const i=Le(o.tabs,t,u=>({...u,status:"open"}));n({tabs:i,activeTabId:t,terminalsMap:l,terminalIds:s.terminalIds,layout:s.layout}),pe(ue(e()))},deleteTab:async t=>{const o=e(),s=o.tabs.find(x=>x.id===t);if(!s)return;const l=o.token;l&&await Promise.all(s.terminalIds.map(x=>fetch(`${se}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:ie(l)}).catch(()=>{})));const i=e(),d=i.tabs.find(x=>x.id===t);if(!d)return;const u={...i.terminalsMap};for(const x of d.terminalIds)delete u[x];const c=i.tabs.filter(x=>x.id!==t);let h=i.activeTabId,p=i.terminalIds,m=i.layout;if(i.activeTabId===t){const x=c.find(C=>C.status==="open");x?(h=x.id,p=x.terminalIds,m=x.layout):(h="",p=[],m=null)}n({tabs:c,activeTabId:h,terminalsMap:u,terminalIds:p,layout:m}),pe(ue(e())),setTimeout(()=>e().fetchSessions(),500)},renameTab:(t,o)=>{const s=Le(e().tabs,t,l=>({...l,name:o}));n({tabs:s}),pe(ue(e()))},addTerminal:(t,o)=>{const s=e();if(o&&s.terminalsMap[o])return o;const l=ft(s);if(!l){const U=`tab${s.nextTabId}`,L=o||`t${s.nextId}`;let B=s.nextId;const W=L.match(/^t(\d+)$/);W&&(B=Math.max(B,parseInt(W[1],10)+1));const O=o?B:B+1,V={id:L,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},T={type:"leaf",terminalId:L},w={id:U,name:`Tab ${s.nextTabId}`,status:"open",terminalIds:[L],layout:T,createdAt:Date.now()};return n({tabs:[...s.tabs,w],activeTabId:U,nextTabId:s.nextTabId+1,nextId:O,terminalsMap:{...s.terminalsMap,[L]:V},terminalIds:[L],layout:T}),pe(ue(e())),L}const{nextId:i,nextSplitId:d,terminalsMap:u}=s,{terminalIds:c,layout:h}=l,p=o||`t${i}`;let m=i;const x=p.match(/^t(\d+)$/);x&&(m=Math.max(m,parseInt(x[1],10)+1));const C={id:p,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},z={type:"leaf",terminalId:p};let N,E=d;if(!h)N=z;else if(h.type==="leaf"){const U=t||"horizontal";N={id:`s${E}`,type:"split",direction:U,children:[h,z],sizes:[50,50]},E++}else if(h.direction===(t||"horizontal")){const L=100/(h.children.length+1),B=(100-L)/100,W=[...h.sizes.map(O=>O*B),L];N={...h,children:[...h.children,z],sizes:W}}else{const U=t||"horizontal";N={id:`s${E}`,type:"split",direction:U,children:[h,z],sizes:[50,50]},E++}const v=[...c,p],A=o?m:m+1,I=Le(s.tabs,l.id,U=>({...U,terminalIds:v,layout:N}));return n({terminalsMap:{...u,[p]:C},terminalIds:v,layout:N,tabs:I,nextId:A,nextSplitId:E}),pe(ue(e())),p},splitTerminal:(t,o,s)=>{const l=e(),i=ft(l);if(!i||!i.layout)return"";const{nextId:d,nextSplitId:u,terminalsMap:c}=l,h=`t${d}`,p={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1},...s?{startCwd:s}:{}},m={type:"leaf",terminalId:h},x=`s${u}`,C=cn(i.layout,t,o,m,x),z=[...i.terminalIds,h],N=d+1,E=u+1,v=Le(l.tabs,i.id,A=>({...A,terminalIds:z,layout:C}));return n({terminalsMap:{...c,[h]:p},terminalIds:z,layout:C,tabs:v,nextId:N,nextSplitId:E}),pe(ue(e())),h},removeTerminal:t=>{const o=Ot(e(),t);o&&(n(o),pe(ue(e())))},disconnectTerminal:t=>{const o=e();if(!o.terminalsMap[t])return;const{[t]:l,...i}=o.terminalsMap;n({terminalsMap:i})},reconnectTerminal:t=>{var d;const o=e();if(o.terminalsMap[t])return;const s=o.tabs.find(u=>u.terminalIds.includes(t)),l=((d=s==null?void 0:s.panelStates)==null?void 0:d[t])||{chatOpen:!1,planOpen:!1},i={id:t,connected:!1,sessionResumed:!1,error:null,panels:l};n({terminalsMap:{...o.terminalsMap,[t]:i}})},setTerminalConnected:(t,o)=>{n(s=>{const l=s.terminalsMap[t];return!l||l.connected===o?s:{terminalsMap:{...s.terminalsMap,[t]:{...l,connected:o}}}})},setTerminalResumed:(t,o)=>{n(s=>{const l=s.terminalsMap[t];return!l||l.sessionResumed===o?s:{terminalsMap:{...s.terminalsMap,[t]:{...l,sessionResumed:o}}}})},setTerminalError:(t,o)=>{n(s=>{const l=s.terminalsMap[t];return!l||l.error===o?s:{terminalsMap:{...s.terminalsMap,[t]:{...l,error:o}}}})},toggleChat:t=>{const o=e(),s=o.terminalsMap[t];if(!s)return;const l={...s.panels,chatOpen:!s.panels.chatOpen},i={...o.terminalsMap,[t]:{...s,panels:l}},d=o.tabs.find(c=>c.terminalIds.includes(t));let u=o.tabs;if(d){const c={...d.panelStates,[t]:l};u=Le(o.tabs,d.id,h=>({...h,panelStates:c}))}n({terminalsMap:i,tabs:u}),pe(ue(e()))},togglePlan:t=>{const o=e(),s=o.terminalsMap[t];if(!s)return;const l={...s.panels,planOpen:!s.panels.planOpen},i={...o.terminalsMap,[t]:{...s,panels:l}},d=o.tabs.find(c=>c.terminalIds.includes(t));let u=o.tabs;if(d){const c={...d.panelStates,[t]:l};u=Le(o.tabs,d.id,h=>({...h,panelStates:c}))}n({terminalsMap:i,tabs:u}),pe(ue(e()))},setSplitSizes:(t,o)=>{const s=e(),l=ft(s);if(!l||!l.layout)return;const i=dn(l.layout,t,o),d=Le(s.tabs,l.id,u=>({...u,layout:i}));n({layout:i,tabs:d}),br(ue(e()))},fontSize:14,setFontSize:t=>{const o=Math.max(10,Math.min(24,t));n({fontSize:o}),Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{Xe=null;const s=e().token;s&&fr(s,o)},500)},latency:null,setLatency:t=>n({latency:t}),theme:(()=>{try{const t=localStorage.getItem("ai-cli-online-theme");if(t==="light"||t==="dark")return t}catch{}return"dark"})(),setTheme:t=>{n({theme:t});try{localStorage.setItem("ai-cli-online-theme",t)}catch{}document.documentElement.setAttribute("data-theme",t)},toggleTheme:()=>{const t=e().theme==="dark"?"light":"dark";e().setTheme(t)},sidebarOpen:!1,toggleSidebar:()=>n(t=>({sidebarOpen:!t.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const t=e().token;if(t)try{const o=await fetch(`${se}/api/sessions`,{headers:ie(t)});if(!o.ok)return;const s=await o.json();n({serverSessions:s})}catch{}},killServerSession:async t=>{const o=e().token;if(!o)return;try{await fetch(`${se}/api/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:ie(o)})}catch{}const s=Ot(e(),t);s&&(n(s),pe(ue(e()))),setTimeout(()=>e().fetchSessions(),500)}}));typeof document<"u"&&document.documentElement.setAttribute("data-theme",M.getState().theme);async function yr(n,e){var s,l;const{setState:t,getState:o}=M;try{const[i,d]=await Promise.all([pr(n),fetch(`${se}/api/sessions`,{headers:ie(n)}).then(C=>C.ok?C.json():[]).catch(()=>[])]);if(o().token!==n)return;const u=i&&((s=i.tabs)==null?void 0:s.length)>0?i:e;if(!u||u.tabs.length===0){t({tabsLoading:!1});return}const c=gr(u,d);if(!c){t({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:u.nextId,nextSplitId:u.nextSplitId,nextTabId:u.nextTabId,terminalIds:[],layout:null});return}const h=o().terminalsMap,p={};for(const C of c.tabs)if(C.status==="open")for(const z of C.terminalIds)p[z]=h[z]||{id:z,connected:!1,sessionResumed:!1,error:null,panels:((l=C.panelStates)==null?void 0:l[z])||{chatOpen:!1,planOpen:!1}};const m=c.tabs.find(C=>C.id===c.activeTabId&&C.status==="open")||c.tabs.find(C=>C.status==="open"),x=(m==null?void 0:m.id)||"";t({tabsLoading:!1,terminalsMap:p,tabs:c.tabs,activeTabId:x,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(m==null?void 0:m.terminalIds)||[],layout:(m==null?void 0:m.layout)||null}),pe(ue(o()))}catch{o().token===n&&t({tabsLoading:!1})}}function vr(){const[n,e]=a.useState(""),t=M(s=>s.setToken),o=s=>{s.preventDefault(),n.trim()&&t(n.trim())};return r.jsx("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, var(--bg-primary) 70%)"},children:r.jsxs("div",{className:"login-card",style:{backgroundColor:"var(--bg-tertiary)",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid var(--border)"},children:[r.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[r.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"var(--bg-primary)",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),r.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),r.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),r.jsxs("form",{onSubmit:o,children:[r.jsxs("div",{style:{marginBottom:"20px"},children:[r.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"var(--accent-blue)",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),r.jsx("input",{type:"password",id:"token",className:"login-input",value:n,onChange:s=>e(s.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"var(--bg-primary)",color:"var(--text-bright)",border:"1px solid var(--border)",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),r.jsx("button",{type:"submit",className:"login-submit",disabled:!n.trim(),style:{width:"100%",padding:"11px",background:n.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:n.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:n.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),r.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:r.jsxs("p",{children:["Token is configured in"," ",r.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const it=new Map;function wr(n,e,t){it.set(n,{onChunk:e,onControl:t})}function Sr(n){it.delete(n)}function kr(n,e){var t;(t=it.get(n))==null||t.onChunk(e)}function Cr(n,e){var t;(t=it.get(n))==null||t.onControl(e)}const Tr=1,Ft=2,Er=3,jr=4,Ir=5,Rr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,Ze=500,Nr=8e3,Dr=1e4,Pt=4e3,Lr=5e3,Mr=10,Ar=64*1024,$r=new TextDecoder,zr=new TextEncoder;function Bt(n,e){const t=zr.encode(e),o=new Uint8Array(1+t.length);return o[0]=n,o.set(t,1),o.buffer}function _r(n,e,t){const o=a.useRef(null),s=a.useRef(Ze),l=a.useRef(null),i=a.useRef(null),d=a.useRef(null),u=a.useRef(null),c=a.useRef(!1),h=a.useRef(t),p=a.useRef(!1),m=a.useRef(0),x=a.useRef(!0),C=a.useRef(!navigator.onLine),z=a.useRef(""),N=a.useRef(null),E=a.useRef("");h.current=t;const v=a.useCallback(()=>{i.current&&(clearInterval(i.current),i.current=null),d.current&&(clearTimeout(d.current),d.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(clearTimeout(u.current),u.current=null),N.current&&(clearTimeout(N.current),N.current=null)},[]),A=a.useCallback(()=>{var Y;const{token:O,setTerminalError:V}=M.getState();if(!O||c.current)return;if(o.current){const q=o.current.readyState;if(q===WebSocket.OPEN||q===WebSocket.CONNECTING)return}p.current=!1;const T=(Y=M.getState().terminalsMap[e])==null?void 0:Y.startCwd;let w=`${Rr}?sessionId=${encodeURIComponent(e)}`;T&&(w+=`&cwd=${encodeURIComponent(T)}`);const S=new WebSocket(w);S.binaryType="arraybuffer",u.current=window.setTimeout(()=>{S.readyState===WebSocket.CONNECTING&&S.close()},Lr);const G=()=>{S.readyState===WebSocket.OPEN&&(m.current=performance.now(),S.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{m.current>0&&(m.current=0,S.close())},Pt))};S.onopen=()=>{u.current&&(clearTimeout(u.current),u.current=null),S.send(JSON.stringify({type:"auth",token:O})),V(e,null),s.current=Ze,x.current=!0},S.onclose=q=>{const{setTerminalConnected:$,setTerminalError:P,setToken:X}=M.getState();if($(e,!1),v(),p.current)return;if(q.code===4001){c.current=!0,P(e,"Authentication failed"),X(null),localStorage.removeItem("ai-cli-online-token");return}if(q.code===4002)return;if(q.code===4005){P(e,"Connection limit reached");return}if(!navigator.onLine){C.current=!0;return}if(x.current){x.current=!1,l.current=window.setTimeout(()=>A(),50);return}const _=s.current;s.current=Math.min(_*2,Nr);const H=Math.round(_*(.5+Math.random()));l.current=window.setTimeout(()=>{A()},H)},S.onerror=()=>{},S.onmessage=q=>{var $;try{const P=n.current;if(q.data instanceof ArrayBuffer){const _=new Uint8Array(q.data);if(_.length<1)return;const H=_[0],oe=_.subarray(1);switch(H){case Tr:P==null||P.write(oe);break;case Er:P==null||P.write(oe);break;case jr:{($=h.current)==null||$.call(h,$r.decode(oe));break}case Ir:{kr(e,oe);break}}return}const X=JSON.parse(q.data);switch(X.type){case"connected":{const _=M.getState();_.setTerminalConnected(e,!0),_.setTerminalResumed(e,X.resumed);const H=n.current;H&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:H.cols,rows:H.rows})),E.current&&(S.send(Bt(Ft,E.current)),E.current=""),G(),i.current=window.setInterval(G,Dr);break}case"error":M.getState().setTerminalError(e,X.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),m.current>0){const _=Math.round(performance.now()-m.current),H=M.getState();(H.terminalIds.length===0||H.terminalIds[0]===e)&&H.setLatency(_),m.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Cr(e,X);break}}catch{}},o.current=S},[e,n,v]),I=a.useCallback(O=>{const V=o.current;if(!V||V.readyState!==WebSocket.OPEN){E.current.length<Ar&&(E.current+=O);return}z.current+=O,N.current||(N.current=window.setTimeout(()=>{const T=z.current;z.current="",N.current=null,T&&V.readyState===WebSocket.OPEN&&V.send(Bt(Ft,T))},Mr))},[]),U=a.useCallback((O,V)=>{var T;((T=o.current)==null?void 0:T.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"resize",cols:O,rows:V}))},[]),L=a.useCallback(()=>{var O;((O=o.current)==null?void 0:O.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),B=a.useCallback(O=>{var V;((V=o.current)==null?void 0:V.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"stream-file",path:O}))},[]),W=a.useCallback(()=>{var O;((O=o.current)==null?void 0:O.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return a.useEffect(()=>{M.getState().token&&(c.current=!1,A());const V=()=>{C.current=!1,s.current=Ze,x.current=!0;const S=o.current;(!S||S.readyState===WebSocket.CLOSED||S.readyState===WebSocket.CLOSING)&&A()},T=()=>{C.current=!0},w=()=>{if(document.visibilityState!=="visible")return;const S=o.current;if(!S||S.readyState!==WebSocket.OPEN){!C.current&&!p.current&&(s.current=Ze,x.current=!0,A());return}m.current=performance.now(),S.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{m.current>0&&(m.current=0,S.close())},Pt)};return window.addEventListener("online",V),window.addEventListener("offline",T),document.addEventListener("visibilitychange",w),()=>{p.current=!0,v(),window.removeEventListener("online",V),window.removeEventListener("offline",T),document.removeEventListener("visibilitychange",w),o.current&&(o.current.close(),o.current=null)}},[A,v,e]),{sendInput:I,sendResize:U,requestScrollback:L,requestFileStream:B,cancelFileStream:W}}function Or(n){const e=a.useRef(null),t=a.useRef(null),o=a.useRef(n);o.current=n;const s=a.useCallback(()=>{t.current&&(clearTimeout(t.current),t.current=null),e.current&&(e.current.remove(),e.current=null)},[]),l=a.useCallback((i,d)=>{s();const u=document.createElement("div");u.style.cssText=`position:fixed;left:${i}px;top:${d}px;z-index:1000;display:flex;align-items:center;gap:4px;padding:4px 6px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.4);font-family:inherit;`;const c=document.createElement("textarea");c.style.cssText="width:90px;height:22px;resize:none;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-size:11px;font-family:inherit;padding:2px 4px;outline:none;",c.placeholder="Ctrl+V",c.addEventListener("paste",h=>{var m;h.preventDefault();const p=(m=h.clipboardData)==null?void 0:m.getData("text/plain");p&&o.current(p),s()}),c.addEventListener("keydown",h=>{h.key==="Escape"&&s()}),u.appendChild(c),document.body.appendChild(u),e.current=u,requestAnimationFrame(()=>{const h=u.getBoundingClientRect();h.right>window.innerWidth&&(u.style.left=`${window.innerWidth-h.width-8}px`),h.bottom>window.innerHeight&&(u.style.top=`${window.innerHeight-h.height-8}px`),c.focus()}),t.current=setTimeout(s,8e3)},[s]);return a.useEffect(()=>{const i=()=>{e.current&&s()};return document.addEventListener("click",i),()=>{document.removeEventListener("click",i),s()}},[s]),{showPasteFloat:l,removePasteFloat:s}}const rt={background:"#000000",foreground:"#cccccc",cursor:"#aeafad",selectionBackground:"rgba(38, 79, 120, 0.5)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5"},ot={background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"rgba(9, 105, 218, 0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#2da44e",brightYellow:"#bf8803",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"},un="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",Fr=a.forwardRef(function({sessionId:e},t){const o=a.useRef(null),s=a.useRef(null),l=a.useRef(null),[i,d]=a.useState(!1),[u,c]=a.useState(""),h=M(L=>L.fontSize),p=M(L=>L.theme),m=a.useCallback(L=>{c(L),d(!0)},[]),{sendInput:x,sendResize:C,requestScrollback:z,requestFileStream:N,cancelFileStream:E}=_r(s,e,m);a.useImperativeHandle(t,()=>({sendInput:x,requestFileStream:N,cancelFileStream:E}),[x,N,E]);const v=a.useRef(x),A=a.useRef(C);v.current=x,A.current=C;const{showPasteFloat:I,removePasteFloat:U}=Or(L=>v.current(L));return a.useEffect(()=>{if(!o.current)return;let L=!1,B=null,W=null,O=null,V=null;if(L||!o.current)return;const T=new Xt({cursorBlink:!0,scrollback:1e4,fontSize:M.getState().fontSize,fontFamily:un,theme:M.getState().theme==="dark"?rt:ot,allowProposedApi:!0}),w=new Zt;T.loadAddon(w),T.loadAddon(new Dn((_,H)=>{window.open(H,"_blank","noopener,noreferrer")})),T.open(o.current);try{const _=new Qt;_.onContextLoss(()=>{_.dispose()}),T.loadAddon(_)}catch{}s.current=T,l.current=w,T.onSelectionChange(()=>{const _=T.getSelection();_&&navigator.clipboard.writeText(_).catch(()=>{})});const S=T.element,G=_=>{var H;if(_.preventDefault(),U(),!((H=navigator.clipboard)!=null&&H.readText)){I(_.clientX,_.clientY);return}navigator.clipboard.readText().then(oe=>{oe&&v.current(oe)}).catch(()=>{I(_.clientX,_.clientY)})};S&&S.addEventListener("contextmenu",G);const Y=()=>{try{const _=o.current;if(_&&_.clientWidth>0&&_.clientHeight>0)return w.fit(),A.current(T.cols,T.rows),!0}catch{}return!1};requestAnimationFrame(()=>Y());let q=0;B=setInterval(()=>{q++,(Y()||q>=10)&&(clearInterval(B),B=null)},100),document.fonts.ready.then(()=>{if(!L)try{w.fit(),A.current(T.cols,T.rows)}catch{}});let $=null;const P=()=>{L||($&&clearTimeout($),$=setTimeout(()=>{if(!L)try{w.fit(),A.current(T.cols,T.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",P),T.onData(_=>{v.current(_)});let X=!1;return V=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!X){X=!0;const H=()=>{document.removeEventListener("mouseup",H),X=!1,requestAnimationFrame(()=>{try{w.fit(),A.current(T.cols,T.rows)}catch{}})};document.addEventListener("mouseup",H)}return}W||(W=requestAnimationFrame(()=>{W=null;try{w.fit(),O&&clearTimeout(O),O=setTimeout(()=>{O=null,A.current(T.cols,T.rows)},50)}catch{}}))}),V.observe(o.current),()=>{L=!0,B&&clearInterval(B),W&&cancelAnimationFrame(W),O&&clearTimeout(O),$&&clearTimeout($),document.fonts.removeEventListener("loadingdone",P),V&&V.disconnect(),U(),S&&S.removeEventListener("contextmenu",G),s.current&&(s.current.dispose(),s.current=null),l.current=null}},[e]),a.useEffect(()=>{const L=s.current,B=l.current;if(!(!L||!B)&&L.options.fontSize!==h){L.options.fontSize=h;try{B.fit()}catch{}A.current(L.cols,L.rows)}},[h]),a.useEffect(()=>{s.current&&(s.current.options.theme=p==="dark"?rt:ot)},[p]),r.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[r.jsx("div",{ref:o,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),r.jsx("button",{tabIndex:-1,onClick:L=>{L.currentTarget.blur(),i?(d(!1),c("")):z()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:i?"var(--accent-blue)":"var(--bg-hover)",color:"var(--text-bright)",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:L=>{L.currentTarget.style.opacity="1"},onMouseLeave:L=>{L.currentTarget.style.opacity="0.8"},children:i?"✕":r.jsx("span",{style:{fontSize:14},children:"👁"})}),i&&r.jsx(Pr,{data:u,onClose:()=>{d(!1),c("")}})]})});function Pr({data:n,onClose:e}){const t=a.useRef(null),o=a.useRef(e);o.current=e;const s=M(c=>c.fontSize),l=M(c=>c.theme),i=a.useRef(null),d=a.useRef(null);a.useEffect(()=>{if(!t.current)return;const c=new Xt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:s,fontFamily:un,theme:l==="dark"?rt:ot});i.current=c;const h=new Zt;d.current=h,c.loadAddon(h),c.open(t.current);let p=null;try{p=new Qt,p.onContextLoss(()=>{p==null||p.dispose(),p=null}),c.loadAddon(p)}catch{p=null}c.onSelectionChange(()=>{const E=c.getSelection();E&&navigator.clipboard.writeText(E).catch(()=>{})}),c.attachCustomKeyEventHandler(E=>(E.key==="Escape"&&o.current(),!1)),c.write(n);let m=null;const x=()=>{const E=t.current;if(!E||E.clientWidth<=0||E.clientHeight<=0)return!1;try{return h.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!x()){let E=0;m=setInterval(()=>{E++,(x()||E>=30)&&(clearInterval(m),m=null)},50)}});let C=null;const z=new ResizeObserver(()=>{C||(C=requestAnimationFrame(()=>{C=null,x()}))});z.observe(t.current);const N=E=>{E.key==="Escape"&&o.current()};return document.addEventListener("keydown",N),()=>{if(m&&clearInterval(m),C&&cancelAnimationFrame(C),document.removeEventListener("keydown",N),z.disconnect(),p){try{p.dispose()}catch{}p=null}c.dispose(),i.current=null,d.current=null}},[n]),a.useEffect(()=>{var c;if(i.current){i.current.options.fontSize=s;try{(c=d.current)==null||c.fit()}catch{}}},[s]),a.useEffect(()=>{i.current&&(i.current.options.theme=l==="dark"?rt:ot)},[l]);const u=28;return r.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[r.jsx("div",{style:{height:u,boxSizing:"border-box",padding:"0 12px",background:"var(--bg-tertiary)",color:"var(--accent-blue)",fontSize:12,borderBottom:"1px solid var(--scrollbar-thumb-hover)",display:"flex",alignItems:"center"},children:r.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),r.jsx("div",{ref:t,style:{position:"absolute",top:u,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const Br=50;function yt(){const n=a.useRef([]),e=a.useCallback(s=>{n.current.push(s),n.current.length>Br&&n.current.shift()},[]),t=a.useCallback(()=>n.current.pop(),[]),o=a.useCallback(()=>{n.current=[]},[]);return a.useMemo(()=>({pushUndo:e,popUndo:t,clearUndo:o}),[e,t,o])}function vt(n,e,t){n.preventDefault();const o=n.currentTarget,s=o.selectionStart,l=o.selectionEnd,i=o.value;t==null||t(i);const d=i.slice(0,s)+" "+i.slice(l);e(d),requestAnimationFrame(()=>{o.selectionStart=o.selectionEnd=s+2})}function We(n,e=10){var t;return Math.min(e,Math.max(1,(((t=n.match(/\n/g))==null?void 0:t.length)??0)+1))}let Be=null,fn="dark";const Ur=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],Wr={primaryColor:"#7aa2f7",primaryTextColor:"#c0caf5",primaryBorderColor:"#414868",lineColor:"#565f89",secondaryColor:"#bb9af7",tertiaryColor:"#24283b",background:"#1a1b26",mainBkg:"#24283b",nodeBorder:"#414868",clusterBkg:"#1e2030",titleColor:"#c0caf5",edgeLabelBackground:"#1e2030",gridColor:"#292e42",doneTaskBkgColor:"#9ece6a",doneTaskBorderColor:"#73a942",activeTaskBkgColor:"#7aa2f7",activeTaskBorderColor:"#5d87d6",critBkgColor:"#f7768e",critBorderColor:"#d35d72",taskBkgColor:"#414868",taskBorderColor:"#565f89",taskTextColor:"#c0caf5",taskTextDarkColor:"#1a1b26",sectionBkgColor:"#1e2030",sectionBkgColor2:"#24283b",altSectionBkgColor:"#1e2030",todayLineColor:"#e0af68"},Hr={primaryColor:"#2e59a8",primaryTextColor:"#343b58",primaryBorderColor:"#9aa5ce",lineColor:"#8c8fa1",secondaryColor:"#7847bd",tertiaryColor:"#d5d6db",background:"#f5f5f5",mainBkg:"#e8e8ed",nodeBorder:"#9aa5ce",clusterBkg:"#ebebf0",titleColor:"#343b58",edgeLabelBackground:"#ebebf0",gridColor:"#d5d6db",doneTaskBkgColor:"#4e8a2f",doneTaskBorderColor:"#3d6e25",activeTaskBkgColor:"#2e59a8",activeTaskBorderColor:"#24478a",critBkgColor:"#c4384b",critBorderColor:"#a02e3e",taskBkgColor:"#c0c1c9",taskBorderColor:"#9aa5ce",taskTextColor:"#343b58",taskTextDarkColor:"#f5f5f5",sectionBkgColor:"#e8e8ed",sectionBkgColor2:"#d5d6db",altSectionBkgColor:"#e8e8ed",todayLineColor:"#b68d28"},Kr={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function Ut(n,e){return fn=e,n.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?Wr:Hr,gantt:Kr}),n}function qr(n="dark"){return Be?fn!==n?Be.then(e=>Ut(e,n)):Be:(Be=(async()=>{for(const e of Ur)try{const t=await import(e);return Ut(t.default,n)}catch{}throw Be=null,new Error("All mermaid CDN sources failed")})(),Be)}let Wt=0;function Jr(n,e,t="dark"){const o=a.useRef(t);a.useEffect(()=>{const s=n.current;if(!s)return;const l=o.current!==t;o.current=t;const i=s.querySelectorAll("code.language-mermaid, code.language-gantt"),d=l?s.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(i.length===0&&d.length===0)return;let u=!1;return(async()=>{let c;try{c=await qr(t)}catch{if(u)return;for(const p of i){const m=p.parentElement;if(!m||m.tagName!=="PRE")continue;m.classList.add("mermaid-error");const x=document.createElement("div");x.className="mermaid-error__msg",x.textContent="Failed to load Mermaid library",m.appendChild(x)}return}if(!u){for(const h of d){if(u)break;const p=h.getAttribute("data-mermaid-source");if(!p)continue;const m=`mermaid-${++Wt}`;try{const{svg:x}=await c.render(m,p);if(u)break;h.innerHTML=xt.sanitize(x,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const h of i){if(u)break;const p=h.parentElement;if(!p||p.tagName!=="PRE")continue;const m=h.textContent||"";if(!m.trim())continue;const x=`mermaid-${++Wt}`;try{const{svg:C}=await c.render(x,m);if(u)break;const z=document.createElement("div");z.className="mermaid-diagram",z.setAttribute("data-mermaid-source",m),z.innerHTML=xt.sanitize(C,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),p.replaceWith(z)}catch{if(u)break;p.classList.add("mermaid-error");const C=document.createElement("div");C.className="mermaid-error__msg",C.textContent="Mermaid syntax error",p.appendChild(C)}}}})(),()=>{u=!0}},[e,t])}async function Vr(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/annotations?path=${encodeURIComponent(t)}`,{headers:ie(n)});if(!o.ok)throw new Error("Failed to fetch annotation");const s=await o.json();return s.content?{content:s.content,updatedAt:s.updatedAt}:null}async function Yr(n,e,t,o,s){if(!(await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/annotations`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({path:t,content:o,updatedAt:s})})).ok)throw new Error("Failed to save annotation")}function pn(n,e){let t=n.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");t||(t="heading");const o=e.get(t)||0;return o>0&&(t=`${t}-${o}`),e.set(t,o+1),t}function mn(n){return n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function Gr(n){if(!n)return[];const e=[],t=new Map,o=n.split(`
|
|
26
|
-
`);let s=!1;for(const l of o){if(/^```/.test(l.trim())){s=!s;continue}if(s)continue;const i=l.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(i){const d=i[1].length,u=mn(i[2]),c=pn(u,t);e.push({id:c,text:u,level:d})}}return e}const Xr=160,Zr=22;function Qr({headings:n,scrollRef:e}){const[t,o]=a.useState(null),[s,l]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),i=a.useRef(null),d=a.useRef(!1),u=a.useMemo(()=>Math.min(...n.map(p=>p.level)),[n]),c=a.useCallback(()=>{l(p=>{const m=!p;try{localStorage.setItem("md-toc-collapsed",String(m))}catch{}return m})},[]);a.useEffect(()=>{const p=e.current;if(!p||n.length===0)return;const m=()=>{d.current=!1;const C=p.scrollTop
|
|
25
|
+
*/var at=a,Gn=Yn;function Xn(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var Zn=typeof Object.is=="function"?Object.is:Xn,Qn=Gn.useSyncExternalStore,er=at.useRef,tr=at.useEffect,nr=at.useMemo,rr=at.useDebugValue;on.useSyncExternalStoreWithSelector=function(n,e,t,o,s){var l=er(null);if(l.current===null){var i={hasValue:!1,value:null};l.current=i}else i=l.current;l=nr(function(){function u(x){if(!c){if(c=!0,h=x,x=o(x),s!==void 0&&i.hasValue){var C=i.value;if(s(C,x))return p=C}return p=x}if(C=p,Zn(h,x))return C;var $=o(x);return s!==void 0&&s(C,$)?(h=x,C):(h=x,p=$)}var c=!1,h,p,m=t===void 0?null:t;return[function(){return u(e())},m===null?void 0:function(){return u(m())}]},[e,t,o,s]);var d=Qn(n,l[0],l[1]);return tr(function(){i.hasValue=!0,i.value=d},[d]),rr(d),d};rn.exports=on;var or=rn.exports;const sr=Nn(or),ln={},{useDebugValue:ar}=St,{useSyncExternalStoreWithSelector:ir}=sr;let Mt=!1;const lr=n=>n;function cr(n,e=lr,t){(ln?"production":void 0)!=="production"&&t&&!Mt&&(Mt=!0);const o=ir(n.subscribe,n.getState,n.getServerState||n.getInitialState,e,t);return ar(o),o}const At=n=>{const e=typeof n=="function"?Fn(n):n,t=(o,s)=>cr(e,o,s);return Object.assign(t,e),t},dr=n=>n?At(n):At,se="";function ie(n){return{Authorization:`Bearer ${n}`}}async function ur(n){try{const e=await fetch(`${se}/api/settings/font-size`,{headers:ie(n)});return e.ok?(await e.json()).fontSize:14}catch{return 14}}async function fr(n,e){try{await fetch(`${se}/api/settings/font-size`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({fontSize:e})})}catch{}}async function pr(n){try{const e=await fetch(`${se}/api/settings/tabs-layout`,{headers:ie(n)});return e.ok?(await e.json()).layout:null}catch{return null}}async function mr(n,e){try{await fetch(`${se}/api/settings/tabs-layout`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({layout:e})})}catch{}}function zt(n,e){try{const t=`${se}/api/settings/tabs-layout`,o=JSON.stringify({layout:e,token:n});navigator.sendBeacon(t,new Blob([o],{type:"application/json"}))}catch{}}const tt="ai-cli-online-tabs",$t="ai-cli-online-layout",_t="ai-cli-online-session-names";function nt(n,e){if(n.type==="leaf")return n.terminalId===e?null:n;const t=[],o=[];for(let i=0;i<n.children.length;i++){const d=nt(n.children[i],e);d!==null&&(t.push(d),o.push(n.sizes[i]))}if(t.length===0)return null;if(t.length===1)return t[0];const s=o.reduce((i,d)=>i+d,0),l=o.map(i=>i/s*100);return{...n,children:t,sizes:l}}function cn(n,e,t,o,s){return n.type==="leaf"?n.terminalId===e?{id:s,type:"split",direction:t,children:[n,o],sizes:[50,50]}:n:{...n,children:n.children.map(l=>cn(l,e,t,o,s))}}function dn(n,e,t){return n.type==="leaf"?n:n.id===e?{...n,sizes:t}:{...n,children:n.children.map(o=>dn(o,e,t))}}function ft(n){return n.tabs.find(e=>e.id===n.activeTabId)}function Le(n,e,t){return n.map(o=>o.id===e?t(o):o)}function pe(n){const e={version:2,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId,tabs:n.tabs};try{localStorage.setItem(tt,JSON.stringify(e))}catch{}hr(e)}let Ge=null,Xe=null,Oe=null,qe=null;function hr(n){qe=n,Oe&&clearTimeout(Oe),Oe=setTimeout(()=>{Oe=null,qe=null;const e=M.getState().token;e&&mr(e,n)},2e3)}function br(n){Ge&&clearTimeout(Ge),Ge=setTimeout(()=>{Ge=null,pe(n)},500)}function xr(){try{const n=localStorage.getItem(tt);if(n){const e=JSON.parse(n);if(e.version===2)return e}}catch{}try{const n=localStorage.getItem($t);if(n){const e=JSON.parse(n);let t="Default";try{const l=localStorage.getItem(_t);if(l){const i=JSON.parse(l),d=Object.values(i)[0];d&&(t=d)}}catch{}const o={id:"tab1",name:t,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},s={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[o]};try{localStorage.setItem(tt,JSON.stringify(s))}catch{}return localStorage.removeItem($t),localStorage.removeItem(_t),s}}catch{}return null}function ue(n){return{tabs:n.tabs,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId}}function gr(n,e){const t=new Set(e.map(i=>i.sessionId)),o=[];for(const i of n.tabs){if(i.status!=="open"){const c=i.terminalIds.filter(h=>t.has(h));if(c.length>0){let h=i.layout;for(const p of i.terminalIds)!t.has(p)&&h&&(h=nt(h,p));o.push({...i,terminalIds:c,layout:h})}continue}const d=i.terminalIds.filter(c=>t.has(c));if(d.length===0)continue;let u=i.layout;for(const c of i.terminalIds)!t.has(c)&&u&&(u=nt(u,c));o.push({...i,terminalIds:d,layout:u})}if(o.filter(i=>i.status==="open").length===0)return null;let s=n.activeTabId;if(!o.find(i=>i.id===s&&i.status==="open")){const i=o.find(d=>d.status==="open");s=(i==null?void 0:i.id)||""}return{...n,activeTabId:s,tabs:o}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var e,t;const n=(t=(e=M==null?void 0:M.getState)==null?void 0:e.call(M))==null?void 0:t.token;if(n)if(qe)Oe&&(clearTimeout(Oe),Oe=null),zt(n,qe),qe=null;else{const o=M.getState();o.tabs.length>0&&zt(n,ue(o))}});function Ot(n,e){const t=n.tabs.find(c=>c.terminalIds.includes(e));if(!t){const{[e]:c,...h}=n.terminalsMap;return{terminalsMap:h}}const o=t.terminalIds.filter(c=>c!==e),s=t.layout?nt(t.layout,e):null,l=Le(n.tabs,t.id,c=>({...c,terminalIds:o,layout:s})),{[e]:i,...d}=n.terminalsMap,u={terminalsMap:d,tabs:l};return t.id===n.activeTabId&&(u.terminalIds=o,u.layout=s),u}const M=dr((n,e)=>({token:null,tabsLoading:!1,setToken:t=>{var o;if(t){try{localStorage.setItem("ai-cli-online-token",t)}catch{}ur(t).then(l=>{e().token===t&&n({fontSize:l})});const s=xr();if(s&&s.tabs.length>0){const l={};for(const u of s.tabs)if(u.status==="open")for(const c of u.terminalIds)l[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((o=u.panelStates)==null?void 0:o[c])||{chatOpen:!1,planOpen:!1}};const i=s.tabs.find(u=>u.id===s.activeTabId&&u.status==="open")||s.tabs.find(u=>u.status==="open"),d=(i==null?void 0:i.id)||"";n({token:t,tabsLoading:!0,terminalsMap:l,tabs:s.tabs,activeTabId:d,nextId:s.nextId,nextSplitId:s.nextSplitId,nextTabId:s.nextTabId,terminalIds:(i==null?void 0:i.terminalIds)||[],layout:(i==null?void 0:i.layout)||null})}else n({token:t,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});yr(t,s);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(tt),n({token:t,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:t=>{const o=e(),s=`tab${o.nextTabId}`,l=`t${o.nextId}`,i={id:l,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},d={type:"leaf",terminalId:l},u={id:s,name:t||`Tab ${o.nextTabId}`,status:"open",terminalIds:[l],layout:d,createdAt:Date.now()};return n({tabs:[...o.tabs,u],activeTabId:s,nextTabId:o.nextTabId+1,nextId:o.nextId+1,terminalsMap:{...o.terminalsMap,[l]:i},terminalIds:u.terminalIds,layout:u.layout}),pe(ue(e())),s},switchTab:t=>{const s=e().tabs.find(l=>l.id===t);!s||s.status!=="open"||(n({activeTabId:t,terminalIds:s.terminalIds,layout:s.layout}),pe(ue(e())))},closeTab:t=>{const o=e(),s=o.tabs.find(p=>p.id===t);if(!s||s.status!=="open"||o.tabs.filter(p=>p.status==="open").length<=1)return;const i={...o.terminalsMap};for(const p of s.terminalIds)delete i[p];const d=Le(o.tabs,t,p=>({...p,status:"closed"}));let u=o.activeTabId,c=o.terminalIds,h=o.layout;if(o.activeTabId===t){const p=o.tabs.findIndex(C=>C.id===t),m=d.filter(C=>C.status==="open"),x=m.find(C=>d.findIndex(N=>N.id===C.id)>p)||m[m.length-1];x&&(u=x.id,c=x.terminalIds,h=x.layout)}n({tabs:d,activeTabId:u,terminalsMap:i,terminalIds:c,layout:h}),pe(ue(e()))},reopenTab:t=>{var d;const o=e(),s=o.tabs.find(u=>u.id===t);if(!s||s.status!=="closed")return;const l={...o.terminalsMap};for(const u of s.terminalIds)l[u]={id:u,connected:!1,sessionResumed:!1,error:null,panels:((d=s.panelStates)==null?void 0:d[u])||{chatOpen:!1,planOpen:!1}};const i=Le(o.tabs,t,u=>({...u,status:"open"}));n({tabs:i,activeTabId:t,terminalsMap:l,terminalIds:s.terminalIds,layout:s.layout}),pe(ue(e()))},deleteTab:async t=>{const o=e(),s=o.tabs.find(x=>x.id===t);if(!s)return;const l=o.token;l&&await Promise.all(s.terminalIds.map(x=>fetch(`${se}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:ie(l)}).catch(()=>{})));const i=e(),d=i.tabs.find(x=>x.id===t);if(!d)return;const u={...i.terminalsMap};for(const x of d.terminalIds)delete u[x];const c=i.tabs.filter(x=>x.id!==t);let h=i.activeTabId,p=i.terminalIds,m=i.layout;if(i.activeTabId===t){const x=c.find(C=>C.status==="open");x?(h=x.id,p=x.terminalIds,m=x.layout):(h="",p=[],m=null)}n({tabs:c,activeTabId:h,terminalsMap:u,terminalIds:p,layout:m}),pe(ue(e())),setTimeout(()=>e().fetchSessions(),500)},renameTab:(t,o)=>{const s=Le(e().tabs,t,l=>({...l,name:o}));n({tabs:s}),pe(ue(e()))},addTerminal:(t,o)=>{const s=e();if(o&&s.terminalsMap[o])return o;const l=ft(s);if(!l){const U=`tab${s.nextTabId}`,L=o||`t${s.nextId}`;let B=s.nextId;const W=L.match(/^t(\d+)$/);W&&(B=Math.max(B,parseInt(W[1],10)+1));const O=o?B:B+1,V={id:L,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},T={type:"leaf",terminalId:L},w={id:U,name:`Tab ${s.nextTabId}`,status:"open",terminalIds:[L],layout:T,createdAt:Date.now()};return n({tabs:[...s.tabs,w],activeTabId:U,nextTabId:s.nextTabId+1,nextId:O,terminalsMap:{...s.terminalsMap,[L]:V},terminalIds:[L],layout:T}),pe(ue(e())),L}const{nextId:i,nextSplitId:d,terminalsMap:u}=s,{terminalIds:c,layout:h}=l,p=o||`t${i}`;let m=i;const x=p.match(/^t(\d+)$/);x&&(m=Math.max(m,parseInt(x[1],10)+1));const C={id:p,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},$={type:"leaf",terminalId:p};let N,E=d;if(!h)N=$;else if(h.type==="leaf"){const U=t||"horizontal";N={id:`s${E}`,type:"split",direction:U,children:[h,$],sizes:[50,50]},E++}else if(h.direction===(t||"horizontal")){const L=100/(h.children.length+1),B=(100-L)/100,W=[...h.sizes.map(O=>O*B),L];N={...h,children:[...h.children,$],sizes:W}}else{const U=t||"horizontal";N={id:`s${E}`,type:"split",direction:U,children:[h,$],sizes:[50,50]},E++}const v=[...c,p],A=o?m:m+1,I=Le(s.tabs,l.id,U=>({...U,terminalIds:v,layout:N}));return n({terminalsMap:{...u,[p]:C},terminalIds:v,layout:N,tabs:I,nextId:A,nextSplitId:E}),pe(ue(e())),p},splitTerminal:(t,o,s)=>{const l=e(),i=ft(l);if(!i||!i.layout)return"";const{nextId:d,nextSplitId:u,terminalsMap:c}=l,h=`t${d}`,p={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1},...s?{startCwd:s}:{}},m={type:"leaf",terminalId:h},x=`s${u}`,C=cn(i.layout,t,o,m,x),$=[...i.terminalIds,h],N=d+1,E=u+1,v=Le(l.tabs,i.id,A=>({...A,terminalIds:$,layout:C}));return n({terminalsMap:{...c,[h]:p},terminalIds:$,layout:C,tabs:v,nextId:N,nextSplitId:E}),pe(ue(e())),h},removeTerminal:t=>{const o=Ot(e(),t);o&&(n(o),pe(ue(e())))},disconnectTerminal:t=>{const o=e();if(!o.terminalsMap[t])return;const{[t]:l,...i}=o.terminalsMap;n({terminalsMap:i})},reconnectTerminal:t=>{var d;const o=e();if(o.terminalsMap[t])return;const s=o.tabs.find(u=>u.terminalIds.includes(t)),l=((d=s==null?void 0:s.panelStates)==null?void 0:d[t])||{chatOpen:!1,planOpen:!1},i={id:t,connected:!1,sessionResumed:!1,error:null,panels:l};n({terminalsMap:{...o.terminalsMap,[t]:i}})},setTerminalConnected:(t,o)=>{n(s=>{const l=s.terminalsMap[t];return!l||l.connected===o?s:{terminalsMap:{...s.terminalsMap,[t]:{...l,connected:o}}}})},setTerminalResumed:(t,o)=>{n(s=>{const l=s.terminalsMap[t];return!l||l.sessionResumed===o?s:{terminalsMap:{...s.terminalsMap,[t]:{...l,sessionResumed:o}}}})},setTerminalError:(t,o)=>{n(s=>{const l=s.terminalsMap[t];return!l||l.error===o?s:{terminalsMap:{...s.terminalsMap,[t]:{...l,error:o}}}})},toggleChat:t=>{const o=e(),s=o.terminalsMap[t];if(!s)return;const l={...s.panels,chatOpen:!s.panels.chatOpen},i={...o.terminalsMap,[t]:{...s,panels:l}},d=o.tabs.find(c=>c.terminalIds.includes(t));let u=o.tabs;if(d){const c={...d.panelStates,[t]:l};u=Le(o.tabs,d.id,h=>({...h,panelStates:c}))}n({terminalsMap:i,tabs:u}),pe(ue(e()))},togglePlan:t=>{const o=e(),s=o.terminalsMap[t];if(!s)return;const l={...s.panels,planOpen:!s.panels.planOpen},i={...o.terminalsMap,[t]:{...s,panels:l}},d=o.tabs.find(c=>c.terminalIds.includes(t));let u=o.tabs;if(d){const c={...d.panelStates,[t]:l};u=Le(o.tabs,d.id,h=>({...h,panelStates:c}))}n({terminalsMap:i,tabs:u}),pe(ue(e()))},setSplitSizes:(t,o)=>{const s=e(),l=ft(s);if(!l||!l.layout)return;const i=dn(l.layout,t,o),d=Le(s.tabs,l.id,u=>({...u,layout:i}));n({layout:i,tabs:d}),br(ue(e()))},fontSize:14,setFontSize:t=>{const o=Math.max(10,Math.min(24,t));n({fontSize:o}),Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{Xe=null;const s=e().token;s&&fr(s,o)},500)},latency:null,setLatency:t=>n({latency:t}),theme:(()=>{try{const t=localStorage.getItem("ai-cli-online-theme");if(t==="light"||t==="dark")return t}catch{}return"dark"})(),setTheme:t=>{n({theme:t});try{localStorage.setItem("ai-cli-online-theme",t)}catch{}document.documentElement.setAttribute("data-theme",t)},toggleTheme:()=>{const t=e().theme==="dark"?"light":"dark";e().setTheme(t)},sidebarOpen:!1,toggleSidebar:()=>n(t=>({sidebarOpen:!t.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const t=e().token;if(t)try{const o=await fetch(`${se}/api/sessions`,{headers:ie(t)});if(!o.ok)return;const s=await o.json();n({serverSessions:s})}catch{}},killServerSession:async t=>{const o=e().token;if(!o)return;try{await fetch(`${se}/api/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:ie(o)})}catch{}const s=Ot(e(),t);s&&(n(s),pe(ue(e()))),setTimeout(()=>e().fetchSessions(),500)}}));typeof document<"u"&&document.documentElement.setAttribute("data-theme",M.getState().theme);async function yr(n,e){var s,l;const{setState:t,getState:o}=M;try{const[i,d]=await Promise.all([pr(n),fetch(`${se}/api/sessions`,{headers:ie(n)}).then(C=>C.ok?C.json():[]).catch(()=>[])]);if(o().token!==n)return;const u=i&&((s=i.tabs)==null?void 0:s.length)>0?i:e;if(!u||u.tabs.length===0){t({tabsLoading:!1});return}const c=gr(u,d);if(!c){t({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:u.nextId,nextSplitId:u.nextSplitId,nextTabId:u.nextTabId,terminalIds:[],layout:null});return}const h=o().terminalsMap,p={};for(const C of c.tabs)if(C.status==="open")for(const $ of C.terminalIds)p[$]=h[$]||{id:$,connected:!1,sessionResumed:!1,error:null,panels:((l=C.panelStates)==null?void 0:l[$])||{chatOpen:!1,planOpen:!1}};const m=c.tabs.find(C=>C.id===c.activeTabId&&C.status==="open")||c.tabs.find(C=>C.status==="open"),x=(m==null?void 0:m.id)||"";t({tabsLoading:!1,terminalsMap:p,tabs:c.tabs,activeTabId:x,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(m==null?void 0:m.terminalIds)||[],layout:(m==null?void 0:m.layout)||null}),pe(ue(o()))}catch{o().token===n&&t({tabsLoading:!1})}}function vr(){const[n,e]=a.useState(""),t=M(s=>s.setToken),o=s=>{s.preventDefault(),n.trim()&&t(n.trim())};return r.jsx("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, var(--bg-primary) 70%)"},children:r.jsxs("div",{className:"login-card",style:{backgroundColor:"var(--bg-tertiary)",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid var(--border)"},children:[r.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[r.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"var(--bg-primary)",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),r.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),r.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),r.jsxs("form",{onSubmit:o,children:[r.jsxs("div",{style:{marginBottom:"20px"},children:[r.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"var(--accent-blue)",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),r.jsx("input",{type:"password",id:"token",className:"login-input",value:n,onChange:s=>e(s.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"var(--bg-primary)",color:"var(--text-bright)",border:"1px solid var(--border)",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),r.jsx("button",{type:"submit",className:"login-submit",disabled:!n.trim(),style:{width:"100%",padding:"11px",background:n.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:n.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:n.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),r.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:r.jsxs("p",{children:["Token is configured in"," ",r.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const it=new Map;function wr(n,e,t){it.set(n,{onChunk:e,onControl:t})}function Sr(n){it.delete(n)}function kr(n,e){var t;(t=it.get(n))==null||t.onChunk(e)}function Cr(n,e){var t;(t=it.get(n))==null||t.onControl(e)}const Tr=1,Ft=2,Er=3,jr=4,Ir=5,Rr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,Ze=500,Nr=8e3,Dr=1e4,Pt=4e3,Lr=5e3,Mr=10,Ar=64*1024,zr=new TextDecoder,$r=new TextEncoder;function Bt(n,e){const t=$r.encode(e),o=new Uint8Array(1+t.length);return o[0]=n,o.set(t,1),o.buffer}function _r(n,e,t){const o=a.useRef(null),s=a.useRef(Ze),l=a.useRef(null),i=a.useRef(null),d=a.useRef(null),u=a.useRef(null),c=a.useRef(!1),h=a.useRef(t),p=a.useRef(!1),m=a.useRef(0),x=a.useRef(!0),C=a.useRef(!navigator.onLine),$=a.useRef(""),N=a.useRef(null),E=a.useRef("");h.current=t;const v=a.useCallback(()=>{i.current&&(clearInterval(i.current),i.current=null),d.current&&(clearTimeout(d.current),d.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(clearTimeout(u.current),u.current=null),N.current&&(clearTimeout(N.current),N.current=null)},[]),A=a.useCallback(()=>{var Y;const{token:O,setTerminalError:V}=M.getState();if(!O||c.current)return;if(o.current){const q=o.current.readyState;if(q===WebSocket.OPEN||q===WebSocket.CONNECTING)return}p.current=!1;const T=(Y=M.getState().terminalsMap[e])==null?void 0:Y.startCwd;let w=`${Rr}?sessionId=${encodeURIComponent(e)}`;T&&(w+=`&cwd=${encodeURIComponent(T)}`);const S=new WebSocket(w);S.binaryType="arraybuffer",u.current=window.setTimeout(()=>{S.readyState===WebSocket.CONNECTING&&S.close()},Lr);const G=()=>{S.readyState===WebSocket.OPEN&&(m.current=performance.now(),S.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{m.current>0&&(m.current=0,S.close())},Pt))};S.onopen=()=>{u.current&&(clearTimeout(u.current),u.current=null),S.send(JSON.stringify({type:"auth",token:O})),V(e,null),s.current=Ze,x.current=!0},S.onclose=q=>{const{setTerminalConnected:z,setTerminalError:P,setToken:X}=M.getState();if(z(e,!1),v(),p.current)return;if(q.code===4001){c.current=!0,P(e,"Authentication failed"),X(null),localStorage.removeItem("ai-cli-online-token");return}if(q.code===4002)return;if(q.code===4005){P(e,"Connection limit reached");return}if(!navigator.onLine){C.current=!0;return}if(x.current){x.current=!1,l.current=window.setTimeout(()=>A(),50);return}const _=s.current;s.current=Math.min(_*2,Nr);const H=Math.round(_*(.5+Math.random()));l.current=window.setTimeout(()=>{A()},H)},S.onerror=()=>{},S.onmessage=q=>{var z;try{const P=n.current;if(q.data instanceof ArrayBuffer){const _=new Uint8Array(q.data);if(_.length<1)return;const H=_[0],oe=_.subarray(1);switch(H){case Tr:P==null||P.write(oe);break;case Er:P==null||P.write(oe);break;case jr:{(z=h.current)==null||z.call(h,zr.decode(oe));break}case Ir:{kr(e,oe);break}}return}const X=JSON.parse(q.data);switch(X.type){case"connected":{const _=M.getState();_.setTerminalConnected(e,!0),_.setTerminalResumed(e,X.resumed);const H=n.current;H&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:H.cols,rows:H.rows})),E.current&&(S.send(Bt(Ft,E.current)),E.current=""),G(),i.current=window.setInterval(G,Dr);break}case"error":M.getState().setTerminalError(e,X.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),m.current>0){const _=Math.round(performance.now()-m.current),H=M.getState();(H.terminalIds.length===0||H.terminalIds[0]===e)&&H.setLatency(_),m.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Cr(e,X);break}}catch{}},o.current=S},[e,n,v]),I=a.useCallback(O=>{const V=o.current;if(!V||V.readyState!==WebSocket.OPEN){E.current.length<Ar&&(E.current+=O);return}$.current+=O,N.current||(N.current=window.setTimeout(()=>{const T=$.current;$.current="",N.current=null,T&&V.readyState===WebSocket.OPEN&&V.send(Bt(Ft,T))},Mr))},[]),U=a.useCallback((O,V)=>{var T;((T=o.current)==null?void 0:T.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"resize",cols:O,rows:V}))},[]),L=a.useCallback(()=>{var O;((O=o.current)==null?void 0:O.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),B=a.useCallback(O=>{var V;((V=o.current)==null?void 0:V.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"stream-file",path:O}))},[]),W=a.useCallback(()=>{var O;((O=o.current)==null?void 0:O.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return a.useEffect(()=>{M.getState().token&&(c.current=!1,A());const V=()=>{C.current=!1,s.current=Ze,x.current=!0;const S=o.current;(!S||S.readyState===WebSocket.CLOSED||S.readyState===WebSocket.CLOSING)&&A()},T=()=>{C.current=!0},w=()=>{if(document.visibilityState!=="visible")return;const S=o.current;if(!S||S.readyState!==WebSocket.OPEN){!C.current&&!p.current&&(s.current=Ze,x.current=!0,A());return}m.current=performance.now(),S.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{m.current>0&&(m.current=0,S.close())},Pt)};return window.addEventListener("online",V),window.addEventListener("offline",T),document.addEventListener("visibilitychange",w),()=>{p.current=!0,v(),window.removeEventListener("online",V),window.removeEventListener("offline",T),document.removeEventListener("visibilitychange",w),o.current&&(o.current.close(),o.current=null)}},[A,v,e]),{sendInput:I,sendResize:U,requestScrollback:L,requestFileStream:B,cancelFileStream:W}}function Or(n){const e=a.useRef(null),t=a.useRef(null),o=a.useRef(n);o.current=n;const s=a.useCallback(()=>{t.current&&(clearTimeout(t.current),t.current=null),e.current&&(e.current.remove(),e.current=null)},[]),l=a.useCallback((i,d)=>{s();const u=document.createElement("div");u.style.cssText=`position:fixed;left:${i}px;top:${d}px;z-index:1000;display:flex;align-items:center;gap:4px;padding:4px 6px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.4);font-family:inherit;`;const c=document.createElement("textarea");c.style.cssText="width:90px;height:22px;resize:none;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-size:11px;font-family:inherit;padding:2px 4px;outline:none;",c.placeholder="Ctrl+V",c.addEventListener("paste",h=>{var m;h.preventDefault();const p=(m=h.clipboardData)==null?void 0:m.getData("text/plain");p&&o.current(p),s()}),c.addEventListener("keydown",h=>{h.key==="Escape"&&s()}),u.appendChild(c),document.body.appendChild(u),e.current=u,requestAnimationFrame(()=>{const h=u.getBoundingClientRect();h.right>window.innerWidth&&(u.style.left=`${window.innerWidth-h.width-8}px`),h.bottom>window.innerHeight&&(u.style.top=`${window.innerHeight-h.height-8}px`),c.focus()}),t.current=setTimeout(s,8e3)},[s]);return a.useEffect(()=>{const i=()=>{e.current&&s()};return document.addEventListener("click",i),()=>{document.removeEventListener("click",i),s()}},[s]),{showPasteFloat:l,removePasteFloat:s}}const rt={background:"#000000",foreground:"#cccccc",cursor:"#aeafad",selectionBackground:"rgba(38, 79, 120, 0.5)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5"},ot={background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"rgba(9, 105, 218, 0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#2da44e",brightYellow:"#bf8803",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"},un="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",Fr=a.forwardRef(function({sessionId:e},t){const o=a.useRef(null),s=a.useRef(null),l=a.useRef(null),[i,d]=a.useState(!1),[u,c]=a.useState(""),h=M(L=>L.fontSize),p=M(L=>L.theme),m=a.useCallback(L=>{c(L),d(!0)},[]),{sendInput:x,sendResize:C,requestScrollback:$,requestFileStream:N,cancelFileStream:E}=_r(s,e,m);a.useImperativeHandle(t,()=>({sendInput:x,requestFileStream:N,cancelFileStream:E}),[x,N,E]);const v=a.useRef(x),A=a.useRef(C);v.current=x,A.current=C;const{showPasteFloat:I,removePasteFloat:U}=Or(L=>v.current(L));return a.useEffect(()=>{if(!o.current)return;let L=!1,B=null,W=null,O=null,V=null;if(L||!o.current)return;const T=new Xt({cursorBlink:!0,scrollback:1e4,fontSize:M.getState().fontSize,fontFamily:un,theme:M.getState().theme==="dark"?rt:ot,allowProposedApi:!0}),w=new Zt;T.loadAddon(w),T.loadAddon(new Dn((_,H)=>{window.open(H,"_blank","noopener,noreferrer")})),T.open(o.current);try{const _=new Qt;_.onContextLoss(()=>{_.dispose()}),T.loadAddon(_)}catch{}s.current=T,l.current=w,T.onSelectionChange(()=>{const _=T.getSelection();_&&navigator.clipboard.writeText(_).catch(()=>{})});const S=T.element,G=_=>{var H;if(_.preventDefault(),U(),!((H=navigator.clipboard)!=null&&H.readText)){I(_.clientX,_.clientY);return}navigator.clipboard.readText().then(oe=>{oe&&v.current(oe)}).catch(()=>{I(_.clientX,_.clientY)})};S&&S.addEventListener("contextmenu",G);const Y=()=>{try{const _=o.current;if(_&&_.clientWidth>0&&_.clientHeight>0)return w.fit(),A.current(T.cols,T.rows),!0}catch{}return!1};requestAnimationFrame(()=>Y());let q=0;B=setInterval(()=>{q++,(Y()||q>=10)&&(clearInterval(B),B=null)},100),document.fonts.ready.then(()=>{if(!L)try{w.fit(),A.current(T.cols,T.rows)}catch{}});let z=null;const P=()=>{L||(z&&clearTimeout(z),z=setTimeout(()=>{if(!L)try{w.fit(),A.current(T.cols,T.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",P),T.onData(_=>{v.current(_)});let X=!1;return V=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!X){X=!0;const H=()=>{document.removeEventListener("mouseup",H),X=!1,requestAnimationFrame(()=>{try{w.fit(),A.current(T.cols,T.rows)}catch{}})};document.addEventListener("mouseup",H)}return}W||(W=requestAnimationFrame(()=>{W=null;try{w.fit(),O&&clearTimeout(O),O=setTimeout(()=>{O=null,A.current(T.cols,T.rows)},50)}catch{}}))}),V.observe(o.current),()=>{L=!0,B&&clearInterval(B),W&&cancelAnimationFrame(W),O&&clearTimeout(O),z&&clearTimeout(z),document.fonts.removeEventListener("loadingdone",P),V&&V.disconnect(),U(),S&&S.removeEventListener("contextmenu",G),s.current&&(s.current.dispose(),s.current=null),l.current=null}},[e]),a.useEffect(()=>{const L=s.current,B=l.current;if(!(!L||!B)&&L.options.fontSize!==h){L.options.fontSize=h;try{B.fit()}catch{}A.current(L.cols,L.rows)}},[h]),a.useEffect(()=>{s.current&&(s.current.options.theme=p==="dark"?rt:ot)},[p]),r.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[r.jsx("div",{ref:o,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),r.jsx("button",{tabIndex:-1,onClick:L=>{L.currentTarget.blur(),i?(d(!1),c("")):$()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:i?"var(--accent-blue)":"var(--bg-hover)",color:"var(--text-bright)",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:L=>{L.currentTarget.style.opacity="1"},onMouseLeave:L=>{L.currentTarget.style.opacity="0.8"},children:i?"✕":r.jsx("span",{style:{fontSize:14},children:"👁"})}),i&&r.jsx(Pr,{data:u,onClose:()=>{d(!1),c("")}})]})});function Pr({data:n,onClose:e}){const t=a.useRef(null),o=a.useRef(e);o.current=e;const s=M(c=>c.fontSize),l=M(c=>c.theme),i=a.useRef(null),d=a.useRef(null);a.useEffect(()=>{if(!t.current)return;const c=new Xt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:s,fontFamily:un,theme:l==="dark"?rt:ot});i.current=c;const h=new Zt;d.current=h,c.loadAddon(h),c.open(t.current);let p=null;try{p=new Qt,p.onContextLoss(()=>{p==null||p.dispose(),p=null}),c.loadAddon(p)}catch{p=null}c.onSelectionChange(()=>{const E=c.getSelection();E&&navigator.clipboard.writeText(E).catch(()=>{})}),c.attachCustomKeyEventHandler(E=>(E.key==="Escape"&&o.current(),!1)),c.write(n);let m=null;const x=()=>{const E=t.current;if(!E||E.clientWidth<=0||E.clientHeight<=0)return!1;try{return h.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!x()){let E=0;m=setInterval(()=>{E++,(x()||E>=30)&&(clearInterval(m),m=null)},50)}});let C=null;const $=new ResizeObserver(()=>{C||(C=requestAnimationFrame(()=>{C=null,x()}))});$.observe(t.current);const N=E=>{E.key==="Escape"&&o.current()};return document.addEventListener("keydown",N),()=>{if(m&&clearInterval(m),C&&cancelAnimationFrame(C),document.removeEventListener("keydown",N),$.disconnect(),p){try{p.dispose()}catch{}p=null}c.dispose(),i.current=null,d.current=null}},[n]),a.useEffect(()=>{var c;if(i.current){i.current.options.fontSize=s;try{(c=d.current)==null||c.fit()}catch{}}},[s]),a.useEffect(()=>{i.current&&(i.current.options.theme=l==="dark"?rt:ot)},[l]);const u=28;return r.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[r.jsx("div",{style:{height:u,boxSizing:"border-box",padding:"0 12px",background:"var(--bg-tertiary)",color:"var(--accent-blue)",fontSize:12,borderBottom:"1px solid var(--scrollbar-thumb-hover)",display:"flex",alignItems:"center"},children:r.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),r.jsx("div",{ref:t,style:{position:"absolute",top:u,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const Br=50;function yt(){const n=a.useRef([]),e=a.useCallback(s=>{n.current.push(s),n.current.length>Br&&n.current.shift()},[]),t=a.useCallback(()=>n.current.pop(),[]),o=a.useCallback(()=>{n.current=[]},[]);return a.useMemo(()=>({pushUndo:e,popUndo:t,clearUndo:o}),[e,t,o])}function vt(n,e,t){n.preventDefault();const o=n.currentTarget,s=o.selectionStart,l=o.selectionEnd,i=o.value;t==null||t(i);const d=i.slice(0,s)+" "+i.slice(l);e(d),requestAnimationFrame(()=>{o.selectionStart=o.selectionEnd=s+2})}function We(n,e=10){var t;return Math.min(e,Math.max(1,(((t=n.match(/\n/g))==null?void 0:t.length)??0)+1))}let Be=null,fn="dark";const Ur=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],Wr={primaryColor:"#7aa2f7",primaryTextColor:"#c0caf5",primaryBorderColor:"#414868",lineColor:"#565f89",secondaryColor:"#bb9af7",tertiaryColor:"#24283b",background:"#1a1b26",mainBkg:"#24283b",nodeBorder:"#414868",clusterBkg:"#1e2030",titleColor:"#c0caf5",edgeLabelBackground:"#1e2030",gridColor:"#292e42",doneTaskBkgColor:"#9ece6a",doneTaskBorderColor:"#73a942",activeTaskBkgColor:"#7aa2f7",activeTaskBorderColor:"#5d87d6",critBkgColor:"#f7768e",critBorderColor:"#d35d72",taskBkgColor:"#414868",taskBorderColor:"#565f89",taskTextColor:"#c0caf5",taskTextDarkColor:"#1a1b26",sectionBkgColor:"#1e2030",sectionBkgColor2:"#24283b",altSectionBkgColor:"#1e2030",todayLineColor:"#e0af68"},Hr={primaryColor:"#2e59a8",primaryTextColor:"#343b58",primaryBorderColor:"#9aa5ce",lineColor:"#8c8fa1",secondaryColor:"#7847bd",tertiaryColor:"#d5d6db",background:"#f5f5f5",mainBkg:"#e8e8ed",nodeBorder:"#9aa5ce",clusterBkg:"#ebebf0",titleColor:"#343b58",edgeLabelBackground:"#ebebf0",gridColor:"#d5d6db",doneTaskBkgColor:"#4e8a2f",doneTaskBorderColor:"#3d6e25",activeTaskBkgColor:"#2e59a8",activeTaskBorderColor:"#24478a",critBkgColor:"#c4384b",critBorderColor:"#a02e3e",taskBkgColor:"#c0c1c9",taskBorderColor:"#9aa5ce",taskTextColor:"#343b58",taskTextDarkColor:"#f5f5f5",sectionBkgColor:"#e8e8ed",sectionBkgColor2:"#d5d6db",altSectionBkgColor:"#e8e8ed",todayLineColor:"#b68d28"},Kr={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function Ut(n,e){return fn=e,n.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?Wr:Hr,gantt:Kr}),n}function qr(n="dark"){return Be?fn!==n?Be.then(e=>Ut(e,n)):Be:(Be=(async()=>{for(const e of Ur)try{const t=await import(e);return Ut(t.default,n)}catch{}throw Be=null,new Error("All mermaid CDN sources failed")})(),Be)}let Wt=0;function Jr(n,e,t="dark"){const o=a.useRef(t);a.useEffect(()=>{const s=n.current;if(!s)return;const l=o.current!==t;o.current=t;const i=s.querySelectorAll("code.language-mermaid, code.language-gantt"),d=l?s.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(i.length===0&&d.length===0)return;let u=!1;return(async()=>{let c;try{c=await qr(t)}catch{if(u)return;for(const p of i){const m=p.parentElement;if(!m||m.tagName!=="PRE")continue;m.classList.add("mermaid-error");const x=document.createElement("div");x.className="mermaid-error__msg",x.textContent="Failed to load Mermaid library",m.appendChild(x)}return}if(!u){for(const h of d){if(u)break;const p=h.getAttribute("data-mermaid-source");if(!p)continue;const m=`mermaid-${++Wt}`;try{const{svg:x}=await c.render(m,p);if(u)break;h.innerHTML=xt.sanitize(x,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const h of i){if(u)break;const p=h.parentElement;if(!p||p.tagName!=="PRE")continue;const m=h.textContent||"";if(!m.trim())continue;const x=`mermaid-${++Wt}`;try{const{svg:C}=await c.render(x,m);if(u)break;const $=document.createElement("div");$.className="mermaid-diagram",$.setAttribute("data-mermaid-source",m),$.innerHTML=xt.sanitize(C,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),p.replaceWith($)}catch{if(u)break;p.classList.add("mermaid-error");const C=document.createElement("div");C.className="mermaid-error__msg",C.textContent="Mermaid syntax error",p.appendChild(C)}}}})(),()=>{u=!0}},[e,t])}async function Vr(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/annotations?path=${encodeURIComponent(t)}`,{headers:ie(n)});if(!o.ok)throw new Error("Failed to fetch annotation");const s=await o.json();return s.content?{content:s.content,updatedAt:s.updatedAt}:null}async function Yr(n,e,t,o,s){if(!(await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/annotations`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({path:t,content:o,updatedAt:s})})).ok)throw new Error("Failed to save annotation")}function pn(n,e){let t=n.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");t||(t="heading");const o=e.get(t)||0;return o>0&&(t=`${t}-${o}`),e.set(t,o+1),t}function mn(n){return n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function Gr(n){if(!n)return[];const e=[],t=new Map,o=n.split(`
|
|
26
|
+
`);let s=!1;for(const l of o){if(/^```/.test(l.trim())){s=!s;continue}if(s)continue;const i=l.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(i){const d=i[1].length,u=mn(i[2]),c=pn(u,t);e.push({id:c,text:u,level:d})}}return e}const Xr=160,Zr=22;function Qr({headings:n,scrollRef:e}){const[t,o]=a.useState(null),[s,l]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),i=a.useRef(null),d=a.useRef(!1),u=a.useMemo(()=>Math.min(...n.map(p=>p.level)),[n]),c=a.useCallback(()=>{l(p=>{const m=!p;try{localStorage.setItem("md-toc-collapsed",String(m))}catch{}return m})},[]);a.useEffect(()=>{const p=e.current;if(!p||n.length===0)return;const m=()=>{d.current=!1;const C=p.scrollTop,$=50;let N=null;for(const E of n){const v=p.querySelector(`[id="${CSS.escape(E.id)}"]`);v&&v.offsetTop<=C+$&&(N=E.id)}o(N)},x=()=>{d.current||(d.current=!0,requestAnimationFrame(m))};return m(),p.addEventListener("scroll",x,{passive:!0}),()=>p.removeEventListener("scroll",x)},[n,e]);const h=a.useCallback(p=>{const m=e.current;if(!m)return;const x=m.querySelector(`[id="${CSS.escape(p)}"]`);x&&(x.scrollIntoView({behavior:"smooth",block:"start"}),o(p))},[e]);return a.useEffect(()=>{if(!t||s)return;const p=i.current;if(!p)return;const m=p.querySelector(`[data-toc-id="${CSS.escape(t)}"]`);if(m){const x=m.offsetTop-p.offsetTop,C=x+m.offsetHeight;(x<p.scrollTop||C>p.scrollTop+p.clientHeight)&&m.scrollIntoView({block:"nearest"})}},[t,s]),n.length<2?null:s?r.jsx("div",{style:{width:Zr,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:r.jsx("button",{onClick:c,title:"Show table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:13,cursor:"pointer",padding:"2px",lineHeight:1},onMouseEnter:p=>{p.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:p=>{p.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):r.jsxs("div",{ref:i,style:{width:Xr,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[r.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),r.jsx("button",{onClick:c,title:"Hide table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:"0 2px",lineHeight:1},onMouseEnter:p=>{p.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:p=>{p.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),r.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:n.map((p,m)=>r.jsx("div",{"data-toc-id":p.id,onClick:()=>h(p.id),style:{padding:`2px 6px 2px ${(p.level-u)*10+6}px`,fontSize:11,lineHeight:1.5,color:t===p.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:t===p.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:p.level<=2?500:400,transition:"color 0.1s"},title:p.text,onMouseEnter:x=>{t!==p.id&&(x.currentTarget.style.color="var(--text-primary)"),x.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:x=>{t!==p.id&&(x.currentTarget.style.color="var(--text-secondary)"),x.currentTarget.style.backgroundColor="transparent"},children:p.text},`${p.id}-${m}`))})]})}const pt={additions:[],deletions:[],replacements:[],comments:[]};let eo=0;function ze(){return`ann_${++eo}_${Date.now()}`}function Qe(n,e){return`plan-annotations-${n}-${e}`}function Ht(n,e){return`plan-scroll-${n}-${e}`}function to(n){const e=String(en.parser([n],{async:!1}));return xt.sanitize(e,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function mt(n,e){let t=1;for(let o=0;o<e&&o<n.length;o++){const s=n[o].raw??"";for(const l of s)l===`
|
|
27
27
|
`&&t++}return t}function et(n,e,t,o){const s=n.join(`
|
|
28
|
-
`);let l=0;for(let x=0;x<e-1&&x<n.length;x++)l+=n[x].length+1;let i=0;for(let x=0;x<t&&x<n.length;x++)i+=n[x].length+1;let d=l,u=Math.min(s.length,i);if(o){const x=Math.max(0,l-10),C=Math.min(s.length,i+10),N=s.slice(x,C).indexOf(o);N>=0&&(d=x+N,u=d+o.length)}const c=Math.max(0,d-20),h=s.slice(c,d).replace(/\n/g,"↵"),p=Math.min(s.length,u+20),m=s.slice(u,p).replace(/\n/g,"↵");return{before:h,after:m}}function no(n,e){const t=[],o=[],s=[],l=[];for(const i of n.additions){const{before:d,after:u}=et(e,i.sourceLine,i.sourceLine);t.push(`Line${i.sourceLine}
|
|
29
|
-
`),[e]),z=a.useMemo(()=>Gr(e),[e]),N=a.useMemo(()=>{const f=new Map,b=new Map;return x.forEach((R,k)=>{if(R.type==="heading"){const y=mn(R.text||""),Z=pn(y,b);f.set(k,Z)}}),f},[x]),E=a.useRef(new Set),[v,A]=a.useState(()=>{try{const f=localStorage.getItem(Qe(o,t)),b=f?JSON.parse(f):pt,R=new Set;return b.additions.forEach(k=>R.add(k.id)),b.deletions.forEach(k=>R.add(k.id)),(b.replacements??[]).forEach(k=>R.add(k.id)),(b.comments??[]).forEach(k=>R.add(k.id)),E.current=R,b.replacements||(b.replacements=[]),b.comments||(b.comments=[]),b}catch{return pt}}),I=M(f=>f.latency),U=a.useRef(void 0),L=a.useRef(void 0),B=a.useRef(!1),W=a.useRef(!1);a.useEffect(()=>{if(!W.current)return;const f=Qe(o,t),b=JSON.stringify(v);U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{try{localStorage.setItem(f,b)}catch{}},50),L.current&&clearTimeout(L.current);const R=Math.max(200,(I??30)*3);return L.current=setTimeout(()=>{B.current||(B.current=!0,Yr(s,o,t,b,Date.now()).catch(()=>{}).finally(()=>{B.current=!1}))},R),()=>{U.current&&clearTimeout(U.current),L.current&&clearTimeout(L.current)}},[v,o,t,s,I]),a.useEffect(()=>{W.current=!1;let f=pt,b=0;try{const y=localStorage.getItem(Qe(o,t));y&&(f=JSON.parse(y),b=Date.now())}catch{}f.replacements||(f.replacements=[]),f.comments||(f.comments=[]),A(f);const R=new Set;f.additions.forEach(y=>R.add(y.id)),f.deletions.forEach(y=>R.add(y.id)),f.replacements.forEach(y=>R.add(y.id)),f.comments.forEach(y=>R.add(y.id)),E.current=R;let k=!1;return Vr(s,o,t).then(y=>{if(!k&&y&&y.updatedAt>b)try{const Z=JSON.parse(y.content);Z.replacements||(Z.replacements=[]),Z.comments||(Z.comments=[]),A(Z);try{localStorage.setItem(Qe(o,t),y.content)}catch{}const je=new Set;Z.additions.forEach(Ie=>je.add(Ie.id)),Z.deletions.forEach(Ie=>je.add(Ie.id)),Z.replacements.forEach(Ie=>je.add(Ie.id)),Z.comments.forEach(Ie=>je.add(Ie.id)),E.current=je}catch{}}).catch(()=>{}).finally(()=>{W.current=!0}),W.current=!0,()=>{k=!0}},[o,t,s]);const[O,V]=a.useState(0),T=a.useMemo(()=>{const f=E.current,b=v.additions.length+v.deletions.length+v.replacements.length+v.comments.length;let R=0;return v.additions.forEach(k=>{f.has(k.id)&&R++}),v.deletions.forEach(k=>{f.has(k.id)&&R++}),v.replacements.forEach(k=>{f.has(k.id)&&R++}),v.comments.forEach(k=>{f.has(k.id)&&R++}),{total:b,sent:R,unsent:b-R}},[v,O]),[w,S]=a.useState(null),[G,Y]=a.useState(""),q=a.useRef(null),[$,P]=a.useState(null),[X,_]=a.useState(""),H=a.useRef(null),[oe,ne]=a.useState(null),[be,Ce]=a.useState(""),Te=a.useRef(null),[Fe,ve]=a.useState(null),[xe,Re]=a.useState(""),me=a.useRef(null),[Q,Me]=a.useState(null),[he,D]=a.useState(""),F=a.useRef(null),[J,ae]=a.useState(null),te=a.useRef(null),Ee=a.useRef(0),Ne=a.useRef(null);a.useEffect(()=>()=>{const f=te.current;f&&f.scrollTop>0&&localStorage.setItem(Ht(o,t),String(f.scrollTop))},[o,t]),a.useEffect(()=>{if(!x.length)return;const f=localStorage.getItem(Ht(o,t));f&&requestAnimationFrame(()=>{const b=te.current;b&&(b.scrollTop=Number(f))})},[o,t,x.length]),a.useEffect(()=>{w!=null&&requestAnimationFrame(()=>{var f;return(f=q.current)==null?void 0:f.focus()})},[w]),a.useEffect(()=>{Q&&requestAnimationFrame(()=>{var f;return(f=F.current)==null?void 0:f.focus()})},[Q]);const we=a.useCallback(f=>{if(!G.trim()){S(null),Y("");return}const b=mt(x,f+1);A(R=>({...R,additions:[...R.additions,{id:$e(),afterTokenIndex:f,sourceLine:b,content:G.trim()}]})),S(null),Y("")},[G,x]),ge=a.useCallback(f=>{A(b=>({...b,additions:b.additions.filter(R=>R.id!==f)}))},[]),Ae=a.useCallback((f,b)=>{A(R=>({...R,additions:R.additions.map(k=>k.id===f?{...k,id:$e(),content:b}:k)}))},[]),Ke=a.useCallback(()=>{var f;J&&(A(b=>({...b,deletions:[...b.deletions,{id:$e(),tokenIndices:J.tokenIndices,startLine:J.startLine,endLine:J.endLine,selectedText:J.text.slice(0,80)}]})),ae(null),(f=window.getSelection())==null||f.removeAllRanges())},[J]),Je=a.useCallback(f=>{var b;J&&(Me({type:f,tokenIndices:J.tokenIndices,startLine:J.startLine,endLine:J.endLine,text:J.text.slice(0,80)}),D(""),ae(null),(b=window.getSelection())==null||b.removeAllRanges())},[J]),ze=a.useCallback(()=>{if(!Q)return;const f=he.trim();if(!f){Me(null),D("");return}Q.type==="replace"?A(b=>({...b,replacements:[...b.replacements,{id:$e(),tokenIndices:Q.tokenIndices,startLine:Q.startLine,endLine:Q.endLine,selectedText:Q.text,content:f}]})):A(b=>({...b,comments:[...b.comments,{id:$e(),tokenIndices:Q.tokenIndices,startLine:Q.startLine,endLine:Q.endLine,selectedText:Q.text,content:f}]})),Me(null),D("")},[Q,he]),g=a.useCallback(f=>{A(b=>({...b,replacements:b.replacements.filter(R=>R.id!==f)}))},[]),j=a.useCallback((f,b)=>{A(R=>({...R,replacements:R.replacements.map(k=>k.id===f?{...k,id:$e(),content:b}:k)}))},[]),K=a.useCallback(f=>{A(b=>({...b,comments:b.comments.filter(R=>R.id!==f)}))},[]),ee=a.useCallback((f,b)=>{A(R=>({...R,comments:R.comments.map(k=>k.id===f?{...k,id:$e(),content:b}:k)}))},[]),re=a.useCallback(f=>{A(b=>({...b,deletions:b.deletions.filter(R=>R.id!==f)}))},[]),ye=a.useCallback((f,b)=>{A(R=>({...R,deletions:R.deletions.map(k=>k.id===f?{...k,id:$e(),selectedText:b}:k)}))},[]),le=a.useCallback(f=>{let b=f instanceof Element?f:f.parentElement;for(;b&&b!==te.current;){if(b.hasAttribute("data-token-index"))return b;b=b.parentElement}return null},[]),de=a.useCallback(()=>{const f=window.getSelection();if(!f||f.isCollapsed||!te.current){ae(null);return}const b=f.toString().trim();if(!b){ae(null);return}const R=f.getRangeAt(0);if(!te.current.contains(R.commonAncestorContainer)){ae(null);return}const k=le(R.startContainer),y=le(R.endContainer);if(!k||!y){ae(null);return}const Z=parseInt(k.getAttribute("data-token-index")||"0",10),je=parseInt(y.getAttribute("data-token-index")||"0",10),Ie=[];for(let dt=Math.min(Z,je);dt<=Math.max(Z,je);dt++)Ie.push(dt);const Tn=mt(x,Math.min(Z,je)),En=mt(x,Math.max(Z,je)+1),jt=R.getBoundingClientRect(),ct=te.current,It=ct.getBoundingClientRect();navigator.clipboard.writeText(b).catch(()=>{});const Ye=Ne.current,Rt=Ye&&Date.now()-Ye.time<500;Ee.current=Date.now(),ae({x:(Rt?Ye.x:jt.right)-It.left+ct.scrollLeft+6,y:(Rt?Ye.y:jt.top)-It.top+ct.scrollTop-44,tokenIndices:Ie,startLine:Tn,endLine:En,text:b})},[x,le]),ce=a.useRef(void 0);a.useEffect(()=>{const f=()=>{ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{const b=window.getSelection();if(!b||b.isCollapsed||!te.current){if(Date.now()-Ee.current<300)return;ae(null);return}const R=b.anchorNode;R&&te.current.contains(R)&&de()},120)};return document.addEventListener("selectionchange",f),()=>{document.removeEventListener("selectionchange",f),ce.current&&clearTimeout(ce.current)}},[de]);const fe=M(f=>f.theme);Jr(te,x,fe);const Se=a.useCallback(()=>{const f=E.current;return{additions:v.additions.filter(b=>!f.has(b.id)),deletions:v.deletions.filter(b=>!f.has(b.id)),replacements:v.replacements.filter(b=>!f.has(b.id)),comments:v.comments.filter(b=>!f.has(b.id))}},[v]),_e=a.useCallback(()=>{const f=ht(t,Se(),C);if(f){l(f);const b=new Set;v.additions.forEach(R=>b.add(R.id)),v.deletions.forEach(R=>b.add(R.id)),v.replacements.forEach(R=>b.add(R.id)),v.comments.forEach(R=>b.add(R.id)),E.current=b,V(R=>R+1)}},[Se,v,C,l,t]);a.useImperativeHandle(p,()=>({getSummary:()=>ht(t,Se(),C),handleEscape:()=>Q?(ze(),!0):w!=null?(we(w),!0):!1,getScrollTop:()=>{var f;return((f=te.current)==null?void 0:f.scrollTop)??0},setScrollTop:f=>{requestAnimationFrame(()=>{te.current&&(te.current.scrollTop=f)})}}),[Se,C,t,w,we,Q,ze]);const[Pe,Ct]=a.useState(!1),lt=a.useRef(null);a.useEffect(()=>{if(!Pe)return;const f=b=>{lt.current&&!lt.current.contains(b.target)&&Ct(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[Pe]);const De=a.useCallback((f,b)=>{if(!i)return;const R={additions:[],deletions:[],replacements:[],comments:[]};if(b==="add"){const y=v.additions.find(Z=>Z.id===f);if(!y)return;R.additions.push(y)}else if(b==="del"){const y=v.deletions.find(Z=>Z.id===f);if(!y)return;R.deletions.push(y)}else if(b==="rep"){const y=v.replacements.find(Z=>Z.id===f);if(!y)return;R.replacements.push(y)}else{const y=v.comments.find(Z=>Z.id===f);if(!y)return;R.comments.push(y)}const k=ht(t,R,C);k&&i(k),E.current.add(f),V(y=>y+1)},[i,t,v,C]),Ve=a.useCallback((f,b)=>{b==="add"?ge(f):b==="del"?re(f):b==="rep"?g(f):K(f)},[ge,re,g,K]),Sn=a.useMemo(()=>{const f=new Set;return v.deletions.forEach(b=>b.tokenIndices.forEach(R=>f.add(R))),f},[v.deletions]),kn=a.useMemo(()=>{const f=new Set;return v.replacements.forEach(b=>b.tokenIndices.forEach(R=>f.add(R))),f},[v.replacements]),Cn=a.useMemo(()=>{const f=new Set;return v.comments.forEach(b=>b.tokenIndices.forEach(R=>f.add(R))),f},[v.comments]),Tt=a.useMemo(()=>{const f=new Map;return v.additions.forEach(b=>{const R=f.get(b.afterTokenIndex)||[];R.push(b),f.set(b.afterTokenIndex,R)}),f},[v.additions]),Et=v.additions.length>0||v.deletions.length>0||v.replacements.length>0||v.comments.length>0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[r.jsxs("div",{className:"plan-anno-toolbar",children:[r.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:t,children:t.split("/").pop()||t}),d&&r.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),r.jsx("button",{className:"pane-btn",onClick:_e,disabled:!Et,title:"Send all annotations to Chat editor",style:Et?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),r.jsxs("div",{ref:lt,style:{position:"relative",flex:1,minWidth:0},children:[r.jsxs("div",{className:`plan-anno-dropdown-trigger${Pe?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>Ct(f=>!f),title:T.total>0?`${T.total} annotations (${T.unsent} unsent)`:"No annotations",children:[r.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:(()=>{const f=v.additions[0],b=v.deletions[0],R=v.replacements[0],k=v.comments[0],y=f?f.content:b?b.selectedText:R?R.content:k?k.content:"";return y?y.slice(0,40)+(y.length>40?"...":""):""})()}),r.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),Pe&&r.jsxs("div",{className:"plan-anno-dropdown",children:[T.unsent>0&&r.jsx("div",{className:"plan-anno-dropdown__header",children:r.jsxs("button",{className:"pane-btn",onClick:_e,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",T.unsent,")"]})}),r.jsxs("div",{className:"plan-anno-dropdown__list",children:[v.additions.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--add",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-yellow)"},children:"+"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.content.slice(0,60),f.content.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"add"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"add"),title:"Delete",children:"×"})]},f.id)}),v.deletions.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--del",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-red)"},children:"−"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.selectedText.slice(0,60),f.selectedText.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"del"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"del"),title:"Delete",children:"×"})]},f.id)}),v.replacements.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--rep",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-blue)"},children:"⇄"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.content.slice(0,60),f.content.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"rep"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"rep"),title:"Delete",children:"×"})]},f.id)}),v.comments.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--com",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-green)"},children:"?"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.content.slice(0,60),f.content.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"com"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"com"),title:"Delete",children:"×"})]},f.id)}),T.total===0&&r.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]}),u&&r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{_e(),u()},title:"Send annotations & close file",children:"×"})]}),r.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[r.jsxs("div",{ref:te,className:`plan-anno-content md-preview${w!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${m}px`,minWidth:0},onMouseUp:f=>{Ne.current={x:f.clientX,y:f.clientY,time:Date.now()},de()},children:[!h&&r.jsx(Kt,{index:-1,active:w===-1,additions:Tt.get(-1),onOpen:()=>{S(-1),Y("")},onSubmit:()=>we(-1),onRemoveAddition:ge,onEditAddition:Ae,onSendSingle:i?f=>De(f,"add"):void 0,isSent:f=>E.current.has(f),insertText:G,setInsertText:Y,textareaRef:w===-1?q:void 0,expanded:c,alwaysShow:x.length===0,fontSize:m}),x.map((f,b)=>{const R=to(f);return r.jsxs("div",{children:[r.jsx("div",{"data-token-index":b,id:N.get(b),className:Sn.has(b)?"plan-block--deleted":kn.has(b)?"plan-block--replaced":Cn.has(b)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:R}}),v.deletions.filter(k=>k.tokenIndices.includes(b)&&k.tokenIndices[0]===b).map(k=>r.jsx("div",{className:"plan-deletion-card",children:$===k.id?r.jsx("textarea",{ref:H,className:"plan-annotation-textarea",value:X,onChange:y=>_(y.target.value),onKeyDown:y=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)){y.preventDefault();const Z=X.trim();Z?ye(k.id,Z):re(k.id),P(null)}y.key==="Escape"&&(y.preventDefault(),P(null))},onBlur:()=>{const y=X.trim();y?ye(k.id,y):re(k.id),P(null)},rows:We(X),style:{fontSize:`${m}px`,flex:1}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{flex:1,fontSize:`${m}px`,color:"var(--accent-red)",textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{P(k.id),_(k.selectedText),requestAnimationFrame(()=>{const y=H.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},title:"Double-click to edit",children:k.selectedText}),i&&(()=>{const y=E.current.has(k.id);return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!y&&De(k.id,"del"),disabled:y,title:y?"Already sent":"Send to terminal",style:y?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{P(k.id),_(k.selectedText),requestAnimationFrame(()=>{const y=H.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},style:{color:"var(--accent-blue)"},title:"Edit deletion annotation",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>re(k.id),title:"Remove deletion",children:"×"})]})},k.id)),v.replacements.filter(k=>k.tokenIndices.includes(b)&&k.tokenIndices[0]===b).map(k=>r.jsx("div",{className:"plan-replace-card",children:oe===k.id?r.jsx("textarea",{ref:Te,className:"plan-annotation-textarea",value:be,onChange:y=>Ce(y.target.value),onKeyDown:y=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)){y.preventDefault();const Z=be.trim();Z?j(k.id,Z):g(k.id),ne(null)}y.key==="Escape"&&(y.preventDefault(),ne(null))},onBlur:()=>{const y=be.trim();y?j(k.id,y):g(k.id),ne(null)},rows:We(be),style:{fontSize:`${m}px`,flex:1}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{color:"var(--accent-blue)",flexShrink:0},children:"⇄"}),r.jsxs("span",{style:{flex:1,fontSize:`${m}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{ne(k.id),Ce(k.content),requestAnimationFrame(()=>{const y=Te.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},title:"Double-click to edit",children:[r.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:k.selectedText}),r.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),r.jsx("span",{style:{color:"var(--accent-blue)"},children:k.content})]}),i&&(()=>{const y=E.current.has(k.id);return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!y&&De(k.id,"rep"),disabled:y,title:y?"Already sent":"Send to terminal",style:y?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{ne(k.id),Ce(k.content),requestAnimationFrame(()=>{const y=Te.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},style:{color:"var(--accent-blue)"},title:"Edit replacement",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>g(k.id),title:"Remove replacement",children:"×"})]})},k.id)),v.comments.filter(k=>k.tokenIndices.includes(b)&&k.tokenIndices[0]===b).map(k=>r.jsx("div",{className:"plan-comment-card",children:Fe===k.id?r.jsx("textarea",{ref:me,className:"plan-annotation-textarea",value:xe,onChange:y=>Re(y.target.value),onKeyDown:y=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)){y.preventDefault();const Z=xe.trim();Z?ee(k.id,Z):K(k.id),ve(null)}y.key==="Escape"&&(y.preventDefault(),ve(null))},onBlur:()=>{const y=xe.trim();y?ee(k.id,y):K(k.id),ve(null)},rows:We(xe),style:{fontSize:`${m}px`,flex:1}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{color:"var(--accent-green)",flexShrink:0},children:"?"}),r.jsxs("span",{style:{flex:1,fontSize:`${m}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{ve(k.id),Re(k.content),requestAnimationFrame(()=>{const y=me.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},title:"Double-click to edit",children:[r.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',k.selectedText,'"']}),r.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),r.jsx("span",{style:{color:"var(--accent-green)"},children:k.content})]}),i&&(()=>{const y=E.current.has(k.id);return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!y&&De(k.id,"com"),disabled:y,title:y?"Already sent":"Send to terminal",style:y?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{ve(k.id),Re(k.content),requestAnimationFrame(()=>{const y=me.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},style:{color:"var(--accent-blue)"},title:"Edit comment",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>K(k.id),title:"Remove comment",children:"×"})]})},k.id)),Q&&Q.tokenIndices[0]===b&&r.jsxs("div",{className:Q.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[r.jsx("span",{style:{color:Q.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:Q.type==="replace"?"⇄":"?"}),r.jsx("textarea",{ref:F,className:"plan-annotation-textarea",value:he,onChange:k=>D(k.target.value),onKeyDown:k=>{if(k.key==="Enter"&&(k.ctrlKey||k.metaKey)){k.preventDefault(),ze();return}if(k.key==="Escape"){k.preventDefault(),ze();return}},onBlur:ze,placeholder:Q.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:We(he),style:{fontSize:`${m}px`,flex:1}})]}),!h&&r.jsx(Kt,{index:b,active:w===b,additions:Tt.get(b),onOpen:()=>{S(b),Y("")},onSubmit:()=>we(b),onRemoveAddition:ge,onEditAddition:Ae,onSendSingle:i?k=>De(k,"add"):void 0,isSent:k=>E.current.has(k),insertText:G,setInsertText:Y,textareaRef:w===b?q:void 0,expanded:c,fontSize:m})]},b)}),!h&&J&&r.jsxs("div",{className:"plan-selection-float",style:{top:J.y,left:J.x},children:[r.jsx("button",{className:"plan-selection-float__delete",onMouseDown:f=>{f.preventDefault(),Ke()},title:"Delete selection",children:"−"}),r.jsx("button",{className:"plan-selection-float__replace",onMouseDown:f=>{f.preventDefault(),Je("replace")},title:"Replace selection",children:"⇄"}),r.jsx("button",{className:"plan-selection-float__comment",onMouseDown:f=>{f.preventDefault(),Je("comment")},title:"Comment on selection",children:"?"})]})]}),r.jsx(Qr,{headings:z,scrollRef:te})]})]})});function Kt({index:n,active:e,additions:t,onOpen:o,onSubmit:s,onRemoveAddition:l,onEditAddition:i,onSendSingle:d,isSent:u,insertText:c,setInsertText:h,textareaRef:p,expanded:m,alwaysShow:x,fontSize:C=14}){const[z,N]=a.useState(null),[E,v]=a.useState(""),A=a.useRef(null),I=yt(),U=yt();a.useEffect(()=>{z&&(I.clearUndo(),requestAnimationFrame(()=>{const T=A.current;T&&(T.focus(),T.selectionStart=T.selectionEnd=T.value.length)}))},[z]),a.useEffect(()=>{e&&U.clearUndo()},[e]);const L=a.useCallback(T=>{v(w=>(I.pushUndo(w),T))},[I]),B=a.useCallback(T=>{U.pushUndo(c),h(T)},[c,h,U]),W=a.useCallback(T=>{N(T.id),v(T.content)},[]),O=a.useCallback(()=>{if(!z)return;const T=E.trim();T?i(z,T):l(z),N(null),v("")},[z,E,i,l]),V=a.useCallback(()=>{N(null),v("")},[]);return r.jsxs("div",{className:`plan-insert-zone${x?" plan-insert-zone--empty":""}`,"data-zone-index":n,children:[t==null?void 0:t.map(T=>r.jsx("div",{className:"plan-annotation-card",children:z===T.id?r.jsx("textarea",{ref:A,className:"plan-annotation-textarea",value:E,onChange:w=>L(w.target.value),onKeyDown:w=>{if(w.key==="Enter"&&(w.ctrlKey||w.metaKey)){w.preventDefault(),O();return}if(w.key==="Escape"){w.preventDefault(),V();return}if(w.key==="Tab"){vt(w,L);return}},onBlur:O,rows:We(E),style:{fontSize:`${C}px`,flex:1,...m?{minWidth:300}:void 0}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{flex:1,fontSize:`${C}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>W(T),title:"Double-click to edit",children:T.content}),d&&(()=>{const w=(u==null?void 0:u(T.id))??!1;return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!w&&d(T.id),disabled:w,title:w?"Already sent":"Send to terminal",style:w?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>W(T),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(T.id),children:"×"})]})},T.id)),e?r.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:r.jsx("textarea",{ref:p,className:"plan-annotation-textarea",value:c,onChange:T=>B(T.target.value),onKeyDown:T=>{if(T.key==="Enter"&&(T.ctrlKey||T.metaKey)){T.preventDefault(),s();return}if(T.key==="Escape"){T.preventDefault(),s();return}if(T.key==="Tab"){vt(T,B);return}},placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:We(c),style:{fontSize:`${C}px`,...m?{minWidth:300}:void 0}})}):x&&!(t!=null&&t.length)?r.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:o,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):r.jsx("button",{className:"plan-insert-btn",onClick:o,title:"Add annotation here",children:"+"})]})}async function ke(n,e,t){const o=t?`?path=${encodeURIComponent(t)}`:"",s=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/files${o}`,{headers:ie(n)});if(!s.ok)throw new Error("Failed to list files");return s.json()}function oo(n,e,t,o){return new Promise((s,l)=>{const i=new FormData;for(const u of t)i.append("files",u);const d=new XMLHttpRequest;d.open("POST",`${se}/api/sessions/${encodeURIComponent(e)}/upload`),d.setRequestHeader("Authorization",`Bearer ${n}`),d.upload.addEventListener("progress",u=>{u.lengthComputable&&o&&o(Math.round(u.loaded/u.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?s():l(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>l(new Error("Upload network error"))),d.addEventListener("abort",()=>l(new Error("Upload aborted"))),d.send(i)})}async function so(n,e){const t=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/cwd`,{headers:ie(n)});if(!t.ok)throw new Error("Failed to fetch cwd");return(await t.json()).cwd}async function wt(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/touch`,{method:"POST",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({name:t})});if(!o.ok)throw new Error("Failed to create file");return o.json()}async function hn(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/mkdir`,{method:"POST",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!o.ok)throw new Error("Failed to create directory");return o.json()}async function ao(n,e,t){if(!(await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/rm`,{method:"DELETE",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({path:t})})).ok)throw new Error("Failed to delete")}async function io(n,e){const t=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/download-cwd`,{headers:ie(n)});if(!t.ok)throw new Error("Download failed");const o=await t.blob(),s=URL.createObjectURL(o),l=document.createElement("a");l.href=s;const i=t.headers.get("Content-Disposition"),d=i==null?void 0:i.match(/filename="(.+)"/);l.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(s)}async function lo(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/download?path=${encodeURIComponent(t)}`,{headers:ie(n)});if(!o.ok)throw new Error("Download failed");const s=await o.blob(),l=URL.createObjectURL(s),i=document.createElement("a");i.href=l,i.download=t.split("/").pop()||"download",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(l)}function bn(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:n<1024*1024*1024?`${(n/(1024*1024)).toFixed(1)} MB`:`${(n/(1024*1024*1024)).toFixed(1)} GB`}function co(n,e){if(e==="directory")return"📁";const t=n.slice(n.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}function xn(n){const e=new Date(n*1e3),t=o=>String(o).padStart(2,"0");return`${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}function uo({sessionId:n,token:e,planDir:t,selectedFile:o,onSelectFile:s,onCreateFile:l,onDeleteFile:i}){const[d,u]=a.useState([]),[c,h]=a.useState(!0),[p,m]=a.useState(""),[x,C]=a.useState(!1),z=a.useRef(null),[N,E]=a.useState(t),v=a.useCallback(async()=>{if(!(!e||!N)){h(!0);try{const G=(await ke(e,n,N)).files.filter(Y=>Y.type==="file"&&Y.name.toLowerCase().endsWith(".md")||Y.type==="directory").sort((Y,q)=>{const $=Y.type==="file"&&Y.name===".index.md",P=q.type==="file"&&q.name===".index.md";return $&&!P?-1:!$&&P?1:Y.type==="directory"&&q.type!=="directory"?-1:Y.type!=="directory"&&q.type==="directory"?1:Y.name.localeCompare(q.name)});u(G)}catch{u([])}finally{h(!1)}}},[e,n,N]);a.useEffect(()=>{v()},[v]),a.useEffect(()=>{const S=setInterval(v,5e3);return()=>clearInterval(S)},[v]);const A=a.useCallback(()=>{const S=t.substring(0,t.lastIndexOf("/")+1);return N.startsWith(S)?N.substring(S.length):N},[t,N]),I=a.useCallback(async()=>{const S=p.trim();if(!S)return;const G=S.endsWith(".md")?S:`${S}.md`;C(!0);try{const Y=await wt(e,n,`${A()}/${G}`);Y.ok&&(m(""),await v(),l(Y.path))}catch{}finally{C(!1)}},[p,e,n,A,v,l]),U=a.useCallback(async()=>{const S=p.trim().replace(/\/+$/,"");if(S){C(!0);try{await hn(e,n,`${A()}/${S}`),m(""),await v()}catch{}finally{C(!1)}}},[p,e,n,A,v]),L=a.useCallback(async S=>{const G=`${N}/${S.name}`,Y=S.type==="directory"?`folder "${S.name}" and all its contents`:`"${S.name}"`;if(window.confirm(`Delete ${Y}?`))try{await ao(e,n,G),i==null||i(G),await v()}catch{}},[e,n,N,v,i]),B=a.useCallback(S=>{E(G=>`${G}/${S}`)},[]),W=a.useCallback(()=>{N!==t&&E(S=>S.substring(0,S.lastIndexOf("/")))},[N,t]),O=t.split("/").pop()||"TASK",V=(()=>{const S=t.split("/");return S.length>=2?S[S.length-2]+"/":""})(),T=N===t?V+O+"/":V+O+"/"+N.substring(t.length+1)+"/",w=o?o.split("/").pop():null;return r.jsxs("div",{className:"plan-file-browser",children:[r.jsxs("div",{className:"plan-file-browser__header",children:[r.jsx("span",{className:"plan-file-browser__title",title:T,children:T}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:v,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),r.jsxs("div",{className:"plan-file-browser__create",children:[r.jsx("input",{ref:z,className:"plan-file-browser__input",value:p,onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),I())},placeholder:"name",disabled:x}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:I,disabled:x||!p.trim(),title:"Create new .md file",style:p.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:U,disabled:x||!p.trim(),title:"Create new folder",style:p.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),r.jsxs("div",{className:"plan-file-browser__list",children:[c&&d.length===0&&r.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&d.length===0&&r.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),N!==t&&r.jsxs("div",{className:"plan-file-browser__item",onClick:W,title:"Go up to parent directory",style:{cursor:"pointer"},children:[r.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),r.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(S=>{const G=`${N}/${S.name}`,Y=S.type==="file"&&S.name===w,q=S.type==="directory";return r.jsxs("div",{className:`plan-file-browser__item${Y?" plan-file-browser__item--active":""}`,onClick:()=>q?B(S.name):s(G),title:q?`Open folder ${S.name}`:S.name,style:{cursor:"pointer"},children:[r.jsx("span",{className:"plan-file-browser__icon",children:q?"📁":S.name===".index.md"?"🔒":"□"}),r.jsxs("span",{className:"plan-file-browser__name",children:[S.name,q?"/":""]}),!q&&r.jsx("span",{className:"plan-file-browser__size",children:bn(S.size)}),S.name!==".index.md"&&r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:$=>{$.stopPropagation(),L(S)},title:`Delete ${S.name}`,children:"×"})]},S.name)})]})]})}const bt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},fo=200;function po(){const[n,e]=a.useState(bt),t=a.useRef("lines"),o=a.useRef([]),s=a.useRef(""),l=a.useRef(""),i=a.useRef([]),d=a.useRef(0),u=a.useRef(0),c=a.useRef(null),h=a.useRef(null),p=a.useCallback(()=>{const E=t.current;e(v=>({...v,receivedBytes:d.current,...E==="lines"?{lines:[...o.current]}:{},...E==="content"?{content:l.current}:{}}))},[]),m=a.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,p()},fo))},[p]),x=a.useCallback(E=>{t.current=E,o.current=[],s.current="",l.current="",i.current=[],d.current=0,u.current=0,h.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...bt,mode:E,status:"streaming"})},[]),C=a.useCallback(E=>{d.current+=E.length;const v=t.current;if(v==="lines"){const I=h.current.decode(E,{stream:!0}).split(`
|
|
30
|
-
`);I[0]=s.current+I[0],s.current=I.pop(),I.length>0&&o.current.push(...I)}else if(v==="content"){const A=h.current.decode(E,{stream:!0});l.current+=A}else i.current.push(new Uint8Array(E));m()},[m]),z=a.useCallback(E=>{switch(E.type){case"file-stream-start":u.current=E.size,e(v=>({...v,totalSize:E.size,mtime:E.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const v=t.current;let A=o.current,I=l.current,U=null;if(v==="lines"){const L=h.current.decode(),B=s.current+L;B&&(A=[...A,B],o.current=A),s.current=""}else if(v==="content"){const L=h.current.decode();I=l.current+L,l.current=I}else{const L=i.current.reduce((W,O)=>W+O.length,0);U=new Uint8Array(L);let B=0;for(const W of i.current)U.set(W,B),B+=W.length;i.current=[]}e({status:"complete",mode:v,lines:v==="lines"?[...A]:[],content:v==="content"?I:"",buffer:v==="binary"?U:null,totalSize:u.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(v=>({...v,status:"error",error:E.error}));break}},[]),N=a.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),o.current=[],s.current="",l.current="",i.current=[],d.current=0,u.current=0,h.current=null,e(bt)},[]);return{state:n,startStream:x,handleChunk:C,handleControl:z,reset:N}}function qt({label:n,percent:e}){return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:n}),e!=null&&r.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[r.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),r.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function mo({sessionId:n,token:e,connected:t,onRequestFileStream:o,onForwardToChat:s,onSendToTerminal:l}){const i=po(),[d,u]=a.useState(!1),c=a.useRef(""),[h,p]=a.useState(null),[m,x]=a.useState(null),[C,z]=a.useState(""),[N,E]=a.useState(!1),v=a.useRef(new Map),A=a.useRef(null),I=a.useRef(null);a.useEffect(()=>{I.current=null;let $=!1;return E(!0),(async()=>{try{const P=await ke(e,n);if($)return;if(P.files.find(_=>_.name==="TASK"&&_.type==="directory")){const _=P.cwd+"/TASK",H=await ke(e,n,_);if($)return;const oe=H.files.find(ne=>ne.name===".index.md");if(oe)p(_),x(_+"/"+oe.name);else try{const ne=await wt(e,n,"TASK/.index.md");if($)return;p(_),ne.ok&&x(ne.path)}catch{p(_)}}else try{const _=await hn(e,n,"TASK");if($)return;p(_.path);const H=await wt(e,n,"TASK/.index.md");if($)return;H.ok&&x(H.path)}catch{p(null),x(null)}}catch{p(null)}finally{$||E(!1)}try{const P=await ke(e,n);if($)return;const X=P.home||"";if(c.current=P.cwd,X){const _=`${X}/.claude/commands`;try{const H=await ke(e,n,_);if($)return;H.files.some(ne=>ne.name==="aicli-task-review.md")||u(!0)}catch{$||u(!0)}}}catch{}})(),()=>{$=!0}},[n,e]),a.useEffect(()=>(wr(n,i.handleChunk,i.handleControl),()=>Sr(n)),[n,i.handleChunk,i.handleControl]),a.useEffect(()=>{!m||!t||I.current===m&&C||(I.current=m,i.reset(),i.startStream("content"),o==null||o(m))},[m,t]),a.useEffect(()=>{i.state.status==="complete"&&m&&(z(i.state.content),v.current.set(m,i.state.content))},[i.state.status,i.state.content,m]);const U=a.useRef(new Map),L=a.useCallback(()=>{var P,X;if(!m)return;const $=((X=(P=A.current)==null?void 0:P.getScrollTop)==null?void 0:X.call(P))??0;$>0&&U.current.set(m,$)},[m]);a.useEffect(()=>{if(!m||!C)return;const $=U.current.get(m);$!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var P,X;(X=(P=A.current)==null?void 0:P.setScrollTop)==null||X.call(P,$)})})},[m,C]);const B=a.useCallback($=>{$!==m&&(L(),m&&C&&v.current.set(m,C),x($),z(""),I.current=null)},[m,C,L]),W=a.useCallback($=>{m&&(m===$||m.startsWith($+"/"))&&(x(null),z(""),I.current=null),v.current.delete($)},[m]),O=a.useCallback($=>{x($),z(""),I.current=null},[]),V=a.useCallback($=>{$&&(s==null||s($))},[s]),T=a.useCallback(()=>{L(),m&&C&&v.current.set(m,C),x(null),z(""),I.current=null},[m,C,L]),w=a.useCallback(()=>{!m||!t||(I.current=null,z(""),i.reset(),i.startStream("content"),o==null||o(m),I.current=m)},[m,t,i,o]),[S,G]=a.useState(()=>{const $=localStorage.getItem(`plan-fb-width-${n}`);if($){const P=Number($);if(Number.isFinite(P)&&P>=60&&P<=300)return P}return 130}),Y=a.useRef(S);if(S!==Y.current){Y.current=S;try{localStorage.setItem(`plan-fb-width-${n}`,String(Math.round(S)))}catch{}}const q=a.useCallback($=>{$.preventDefault();const P=$.clientX,X=S;document.body.classList.add("resizing-panes");const _=oe=>{const ne=oe.clientX-P;G(Math.min(300,Math.max(60,X+ne)))},H=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",H)};document.addEventListener("mousemove",_),document.addEventListener("mouseup",H)},[S]);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[d&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",fontSize:12,flexShrink:0},children:[r.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"/aicli-task-review command not installed"}),r.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{const $=c.current;$&&l&&l(`mkdir -p ~/.claude/commands && cp ${$}/.commands/*.md ~/.claude/commands/`),u(!1)},children:"Install"}),r.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>u(!1),children:"×"})]}),r.jsxs("div",{className:"plan-overlay-body",children:[h&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{width:S,flexShrink:0,overflow:"hidden"},children:r.jsx(uo,{sessionId:n,token:e,planDir:h,selectedFile:m,onSelectFile:B,onCreateFile:O,onDeleteFile:W})}),r.jsx("div",{onMouseDown:q,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:$=>{$.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:$=>{$.currentTarget.style.backgroundColor="var(--border)"}})]}),r.jsx("div",{className:"plan-overlay-center",children:N?r.jsx(qt,{label:"Loading TASK/..."}):m&&!C&&(i.state.status==="streaming"||i.state.status==="idle")?r.jsx(qt,{label:`Loading ${m.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):m?r.jsx(ro,{ref:A,markdown:C,filePath:m,sessionId:n,token:e,onExecute:V,onSend:l,onRefresh:w,onClose:T,readOnly:m.endsWith("/.index.md")}):r.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]})]})}async function ho(n,e){try{const t=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/draft`,{headers:ie(n)});return t.ok?(await t.json()).content??"":""}catch{return""}}async function Jt(n,e,t){try{await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/draft`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({content:t})})}catch{}}const kt="chat-history",Vt=50;function gn(){try{const n=localStorage.getItem(kt);return n?JSON.parse(n):[]}catch{return[]}}function bo(n){const t=gn().filter(o=>o.text!==n);t.unshift({text:n,ts:Date.now()}),t.length>Vt&&(t.length=Vt),localStorage.setItem(kt,JSON.stringify(t))}const Yt=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],xo=a.forwardRef(function({onSend:e,onContentChange:t,sessionId:o,token:s},l){const i=M(g=>g.fontSize),[d,u]=a.useState(""),c=a.useRef(null),h=a.useRef(void 0),p=a.useRef(!1),m=a.useRef(!1),{pushUndo:x,popUndo:C}=yt(),z=a.useRef(d);z.current=d;const N=a.useCallback(()=>x(z.current),[x]),[E,v]=a.useState(!1),[A,I]=a.useState(""),[U,L]=a.useState(0),[B,W]=a.useState(!1),[O,V]=a.useState([]),[T,w]=a.useState(0),[S,G]=a.useState(""),Y=a.useRef(null),q=a.useMemo(()=>{if(!S)return O;const g=S.toLowerCase();return O.filter(j=>j.text.toLowerCase().includes(g))},[O,S]),[$,P]=a.useState(!1),[X,_]=a.useState(""),[H,oe]=a.useState(""),[ne,be]=a.useState(0),[Ce,Te]=a.useState([]),[Fe,ve]=a.useState(!1),xe=a.useRef(""),Re=a.useRef(null),me=a.useMemo(()=>{if(!A)return Yt;const g=A.toLowerCase();return Yt.filter(j=>j.cmd.toLowerCase().includes(g)||j.desc.toLowerCase().includes(g))},[A]),Q=a.useMemo(()=>{let g=Ce;if(X){const j=X.toLowerCase();g=g.filter(K=>K.name.toLowerCase().includes(j))}return[...g].sort((j,K)=>j.type==="directory"&&K.type!=="directory"?-1:j.type!=="directory"&&K.type==="directory"?1:j.name.localeCompare(K.name))},[Ce,X]),Me=M(g=>g.latency),he=`chat-draft-${o}`,D=a.useRef(!1),F=a.useRef(void 0);a.useEffect(()=>{try{const j=localStorage.getItem(he);j&&!m.current&&u(j)}catch{}let g=!1;return ho(s,o).then(j=>{if(g||m.current){p.current=!0;return}if(j){u(j);try{localStorage.setItem(he,j)}catch{}}p.current=!0}).catch(()=>{p.current=!0}),()=>{g=!0}},[s,o,he]),a.useEffect(()=>{if(!p.current)return;h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{try{localStorage.setItem(he,d)}catch{}},50),F.current&&clearTimeout(F.current);const g=Math.max(200,(Me??30)*3);return F.current=setTimeout(()=>{D.current||(D.current=!0,Jt(s,o,d).catch(()=>{}).finally(()=>{D.current=!1}))},g),()=>{h.current&&clearTimeout(h.current),F.current&&clearTimeout(F.current)}},[d,s,o,Me,he]),a.useEffect(()=>{var g;(g=c.current)==null||g.focus()},[]),a.useEffect(()=>{if(!$)return;let g=!1;return ve(!0),(async()=>{try{if(H){if(!xe.current){const ee=await ke(s,o);if(g)return;xe.current=ee.cwd}const j=`${xe.current}/${H.replace(/\/$/,"")}`,K=await ke(s,o,j);if(g)return;Te(K.files)}else{const j=await ke(s,o);if(g)return;xe.current=j.cwd,Te(j.files)}ve(!1)}catch{if(g)return;Te([]),ve(!1)}})(),()=>{g=!0}},[$,H,s,o]),a.useEffect(()=>{if(!$||!Re.current)return;const g=Re.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[ne,$]);const J=a.useCallback(()=>{const g=z.current.trim();if(g){bo(g),e(g),u("");try{localStorage.removeItem(he)}catch{}Jt(s,o,"").catch(()=>{})}},[e,s,o,he]),ae=a.useCallback(g=>{N(),u(g),m.current=!0},[N]),te=a.useCallback(g=>{const j=c.current;N();const K=z.current;if(j){const ee=j.selectionStart,re=j.selectionEnd,ye=K.slice(0,ee)+g+K.slice(re);u(ye);const le=ee+g.length;requestAnimationFrame(()=>{j.selectionStart=j.selectionEnd=le,j.focus()})}else u(K+g)},[N]);a.useImperativeHandle(l,()=>({send:J,fillContent:ae,insertAtCursor:te}),[J,ae,te]),a.useEffect(()=>{t==null||t(d.trim().length>0)},[d,t]);const Ee=a.useCallback(()=>{const g=c.current;if(!g)return;const{selectionStart:j,selectionEnd:K}=g;if(j!==K){const ee=g.value.substring(j,K);ee&&navigator.clipboard.writeText(ee).catch(()=>{})}},[]),Ne=a.useCallback(()=>{const g=gn();v(!1),I("");const j=c.current;if(j){const K=j.selectionStart,ee=d.slice(0,K),re=d.slice(K),ye=ee.match(/(?:^|\s)(\/history)\s*$/);if(ye){const le=ee.length-ye[1].length;u(d.slice(0,le)+re)}}g.length!==0&&(V(g),w(0),G(""),W(!0))},[d]),we=a.useCallback(g=>{N(),u(g.text),W(!1),requestAnimationFrame(()=>{const j=c.current;j&&(j.selectionStart=j.selectionEnd=g.text.length,j.focus())})},[N]),ge=a.useCallback(g=>{const j=q[g];if(!j)return;const K=O.filter(re=>re.ts!==j.ts||re.text!==j.text);V(K),localStorage.setItem(kt,JSON.stringify(K));const ee=S?K.filter(re=>re.text.toLowerCase().includes(S.toLowerCase())):K;T>=ee.length&&w(Math.max(0,ee.length-1))},[q,O,T,S]);a.useEffect(()=>{if(!B||!Y.current)return;const g=Y.current.querySelector(".history-item--active");g==null||g.scrollIntoView({block:"nearest"})},[T,B]);const Ae=a.useCallback(g=>{if(g==="/history"){Ne();return}const j=c.current;if(!j)return;N();const K=j.selectionStart,ee=d.slice(0,K),re=d.slice(K),le=ee.lastIndexOf(`
|
|
28
|
+
`);let l=0;for(let x=0;x<e-1&&x<n.length;x++)l+=n[x].length+1;let i=0;for(let x=0;x<t&&x<n.length;x++)i+=n[x].length+1;let d=l,u=Math.min(s.length,i);if(o){const x=Math.max(0,l-10),C=Math.min(s.length,i+10),N=s.slice(x,C).indexOf(o);N>=0&&(d=x+N,u=d+o.length)}const c=Math.max(0,d-20),h=s.slice(c,d).replace(/\n/g,"↵"),p=Math.min(s.length,u+20),m=s.slice(u,p).replace(/\n/g,"↵");return{before:h,after:m}}function no(n,e){const t=[],o=[],s=[],l=[];for(const i of n.additions){const{before:d,after:u}=et(e,i.sourceLine,i.sourceLine);t.push([`Line${i.sourceLine}:...${d}`,i.content,`${u}...`])}for(const i of n.deletions){const{before:d,after:u}=et(e,i.startLine,i.endLine,i.selectedText);o.push([`Line${i.startLine}:...${d}`,i.selectedText,`${u}...`])}for(const i of n.replacements){const{before:d,after:u}=et(e,i.startLine,i.endLine,i.selectedText);s.push([`Line${i.startLine}:...${d}`,i.selectedText,i.content,`${u}...`])}for(const i of n.comments){const{before:d,after:u}=et(e,i.startLine,i.endLine,i.selectedText);l.push([`Line${i.startLine}:...${d}`,i.selectedText,i.content,`${u}...`])}return{"Insert Annotations":t,"Delete Annotations":o,"Replace Annotations":s,"Comment Annotations":l}}function ht(n,e,t){if(e.additions.length===0&&e.deletions.length===0&&e.replacements.length===0&&e.comments.length===0)return"";const o=JSON.stringify(no(e,t));return`/aicli-task-review ${n} ${o}`}const ro=a.forwardRef(function({markdown:e,filePath:t,sessionId:o,token:s,onExecute:l,onSend:i,onRefresh:d,onClose:u,expanded:c,readOnly:h},p){const m=M(f=>f.fontSize),x=a.useMemo(()=>e?en.lexer(e):[],[e]),C=a.useMemo(()=>e.split(`
|
|
29
|
+
`),[e]),$=a.useMemo(()=>Gr(e),[e]),N=a.useMemo(()=>{const f=new Map,b=new Map;return x.forEach((R,k)=>{if(R.type==="heading"){const y=mn(R.text||""),Z=pn(y,b);f.set(k,Z)}}),f},[x]),E=a.useRef(new Set),[v,A]=a.useState(()=>{try{const f=localStorage.getItem(Qe(o,t)),b=f?JSON.parse(f):pt,R=new Set;return b.additions.forEach(k=>R.add(k.id)),b.deletions.forEach(k=>R.add(k.id)),(b.replacements??[]).forEach(k=>R.add(k.id)),(b.comments??[]).forEach(k=>R.add(k.id)),E.current=R,b.replacements||(b.replacements=[]),b.comments||(b.comments=[]),b}catch{return pt}}),I=M(f=>f.latency),U=a.useRef(void 0),L=a.useRef(void 0),B=a.useRef(!1),W=a.useRef(!1);a.useEffect(()=>{if(!W.current)return;const f=Qe(o,t),b=JSON.stringify(v);U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{try{localStorage.setItem(f,b)}catch{}},50),L.current&&clearTimeout(L.current);const R=Math.max(200,(I??30)*3);return L.current=setTimeout(()=>{B.current||(B.current=!0,Yr(s,o,t,b,Date.now()).catch(()=>{}).finally(()=>{B.current=!1}))},R),()=>{U.current&&clearTimeout(U.current),L.current&&clearTimeout(L.current)}},[v,o,t,s,I]),a.useEffect(()=>{W.current=!1;let f=pt,b=0;try{const y=localStorage.getItem(Qe(o,t));y&&(f=JSON.parse(y),b=Date.now())}catch{}f.replacements||(f.replacements=[]),f.comments||(f.comments=[]),A(f);const R=new Set;f.additions.forEach(y=>R.add(y.id)),f.deletions.forEach(y=>R.add(y.id)),f.replacements.forEach(y=>R.add(y.id)),f.comments.forEach(y=>R.add(y.id)),E.current=R;let k=!1;return Vr(s,o,t).then(y=>{if(!k&&y&&y.updatedAt>b)try{const Z=JSON.parse(y.content);Z.replacements||(Z.replacements=[]),Z.comments||(Z.comments=[]),A(Z);try{localStorage.setItem(Qe(o,t),y.content)}catch{}const je=new Set;Z.additions.forEach(Ie=>je.add(Ie.id)),Z.deletions.forEach(Ie=>je.add(Ie.id)),Z.replacements.forEach(Ie=>je.add(Ie.id)),Z.comments.forEach(Ie=>je.add(Ie.id)),E.current=je}catch{}}).catch(()=>{}).finally(()=>{W.current=!0}),W.current=!0,()=>{k=!0}},[o,t,s]);const[O,V]=a.useState(0),T=a.useMemo(()=>{const f=E.current,b=v.additions.length+v.deletions.length+v.replacements.length+v.comments.length;let R=0;return v.additions.forEach(k=>{f.has(k.id)&&R++}),v.deletions.forEach(k=>{f.has(k.id)&&R++}),v.replacements.forEach(k=>{f.has(k.id)&&R++}),v.comments.forEach(k=>{f.has(k.id)&&R++}),{total:b,sent:R,unsent:b-R}},[v,O]),[w,S]=a.useState(null),[G,Y]=a.useState(""),q=a.useRef(null),[z,P]=a.useState(null),[X,_]=a.useState(""),H=a.useRef(null),[oe,ne]=a.useState(null),[be,Ce]=a.useState(""),Te=a.useRef(null),[Fe,ve]=a.useState(null),[xe,Re]=a.useState(""),me=a.useRef(null),[Q,Me]=a.useState(null),[he,D]=a.useState(""),F=a.useRef(null),[J,ae]=a.useState(null),te=a.useRef(null),Ee=a.useRef(0),Ne=a.useRef(null);a.useEffect(()=>()=>{const f=te.current;f&&f.scrollTop>0&&localStorage.setItem(Ht(o,t),String(f.scrollTop))},[o,t]),a.useEffect(()=>{if(!x.length)return;const f=localStorage.getItem(Ht(o,t));f&&requestAnimationFrame(()=>{const b=te.current;b&&(b.scrollTop=Number(f))})},[o,t,x.length]),a.useEffect(()=>{w!=null&&requestAnimationFrame(()=>{var f;return(f=q.current)==null?void 0:f.focus()})},[w]),a.useEffect(()=>{Q&&requestAnimationFrame(()=>{var f;return(f=F.current)==null?void 0:f.focus()})},[Q]);const we=a.useCallback(f=>{if(!G.trim()){S(null),Y("");return}const b=mt(x,f+1);A(R=>({...R,additions:[...R.additions,{id:ze(),afterTokenIndex:f,sourceLine:b,content:G.trim()}]})),S(null),Y("")},[G,x]),ge=a.useCallback(f=>{A(b=>({...b,additions:b.additions.filter(R=>R.id!==f)}))},[]),Ae=a.useCallback((f,b)=>{A(R=>({...R,additions:R.additions.map(k=>k.id===f?{...k,id:ze(),content:b}:k)}))},[]),Ke=a.useCallback(()=>{var f;J&&(A(b=>({...b,deletions:[...b.deletions,{id:ze(),tokenIndices:J.tokenIndices,startLine:J.startLine,endLine:J.endLine,selectedText:J.text.slice(0,80)}]})),ae(null),(f=window.getSelection())==null||f.removeAllRanges())},[J]),Je=a.useCallback(f=>{var b;J&&(Me({type:f,tokenIndices:J.tokenIndices,startLine:J.startLine,endLine:J.endLine,text:J.text.slice(0,80)}),D(""),ae(null),(b=window.getSelection())==null||b.removeAllRanges())},[J]),$e=a.useCallback(()=>{if(!Q)return;const f=he.trim();if(!f){Me(null),D("");return}Q.type==="replace"?A(b=>({...b,replacements:[...b.replacements,{id:ze(),tokenIndices:Q.tokenIndices,startLine:Q.startLine,endLine:Q.endLine,selectedText:Q.text,content:f}]})):A(b=>({...b,comments:[...b.comments,{id:ze(),tokenIndices:Q.tokenIndices,startLine:Q.startLine,endLine:Q.endLine,selectedText:Q.text,content:f}]})),Me(null),D("")},[Q,he]),g=a.useCallback(f=>{A(b=>({...b,replacements:b.replacements.filter(R=>R.id!==f)}))},[]),j=a.useCallback((f,b)=>{A(R=>({...R,replacements:R.replacements.map(k=>k.id===f?{...k,id:ze(),content:b}:k)}))},[]),K=a.useCallback(f=>{A(b=>({...b,comments:b.comments.filter(R=>R.id!==f)}))},[]),ee=a.useCallback((f,b)=>{A(R=>({...R,comments:R.comments.map(k=>k.id===f?{...k,id:ze(),content:b}:k)}))},[]),re=a.useCallback(f=>{A(b=>({...b,deletions:b.deletions.filter(R=>R.id!==f)}))},[]),ye=a.useCallback((f,b)=>{A(R=>({...R,deletions:R.deletions.map(k=>k.id===f?{...k,id:ze(),selectedText:b}:k)}))},[]),le=a.useCallback(f=>{let b=f instanceof Element?f:f.parentElement;for(;b&&b!==te.current;){if(b.hasAttribute("data-token-index"))return b;b=b.parentElement}return null},[]),de=a.useCallback(()=>{const f=window.getSelection();if(!f||f.isCollapsed||!te.current){ae(null);return}const b=f.toString().trim();if(!b){ae(null);return}const R=f.getRangeAt(0);if(!te.current.contains(R.commonAncestorContainer)){ae(null);return}const k=le(R.startContainer),y=le(R.endContainer);if(!k||!y){ae(null);return}const Z=parseInt(k.getAttribute("data-token-index")||"0",10),je=parseInt(y.getAttribute("data-token-index")||"0",10),Ie=[];for(let dt=Math.min(Z,je);dt<=Math.max(Z,je);dt++)Ie.push(dt);const Tn=mt(x,Math.min(Z,je)),En=mt(x,Math.max(Z,je)+1),jt=R.getBoundingClientRect(),ct=te.current,It=ct.getBoundingClientRect();navigator.clipboard.writeText(b).catch(()=>{});const Ye=Ne.current,Rt=Ye&&Date.now()-Ye.time<500;Ee.current=Date.now(),ae({x:(Rt?Ye.x:jt.right)-It.left+ct.scrollLeft+6,y:(Rt?Ye.y:jt.top)-It.top+ct.scrollTop-44,tokenIndices:Ie,startLine:Tn,endLine:En,text:b})},[x,le]),ce=a.useRef(void 0);a.useEffect(()=>{const f=()=>{ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{const b=window.getSelection();if(!b||b.isCollapsed||!te.current){if(Date.now()-Ee.current<300)return;ae(null);return}const R=b.anchorNode;R&&te.current.contains(R)&&de()},120)};return document.addEventListener("selectionchange",f),()=>{document.removeEventListener("selectionchange",f),ce.current&&clearTimeout(ce.current)}},[de]);const fe=M(f=>f.theme);Jr(te,x,fe);const Se=a.useCallback(()=>{const f=E.current;return{additions:v.additions.filter(b=>!f.has(b.id)),deletions:v.deletions.filter(b=>!f.has(b.id)),replacements:v.replacements.filter(b=>!f.has(b.id)),comments:v.comments.filter(b=>!f.has(b.id))}},[v]),_e=a.useCallback(()=>{const f=ht(t,Se(),C);if(f){l(f);const b=new Set;v.additions.forEach(R=>b.add(R.id)),v.deletions.forEach(R=>b.add(R.id)),v.replacements.forEach(R=>b.add(R.id)),v.comments.forEach(R=>b.add(R.id)),E.current=b,V(R=>R+1)}},[Se,v,C,l,t]);a.useImperativeHandle(p,()=>({getSummary:()=>ht(t,Se(),C),handleEscape:()=>Q?($e(),!0):w!=null?(we(w),!0):!1,getScrollTop:()=>{var f;return((f=te.current)==null?void 0:f.scrollTop)??0},setScrollTop:f=>{requestAnimationFrame(()=>{te.current&&(te.current.scrollTop=f)})}}),[Se,C,t,w,we,Q,$e]);const[Pe,Ct]=a.useState(!1),lt=a.useRef(null);a.useEffect(()=>{if(!Pe)return;const f=b=>{lt.current&&!lt.current.contains(b.target)&&Ct(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[Pe]);const De=a.useCallback((f,b)=>{if(!i)return;const R={additions:[],deletions:[],replacements:[],comments:[]};if(b==="add"){const y=v.additions.find(Z=>Z.id===f);if(!y)return;R.additions.push(y)}else if(b==="del"){const y=v.deletions.find(Z=>Z.id===f);if(!y)return;R.deletions.push(y)}else if(b==="rep"){const y=v.replacements.find(Z=>Z.id===f);if(!y)return;R.replacements.push(y)}else{const y=v.comments.find(Z=>Z.id===f);if(!y)return;R.comments.push(y)}const k=ht(t,R,C);k&&i(k),E.current.add(f),V(y=>y+1)},[i,t,v,C]),Ve=a.useCallback((f,b)=>{b==="add"?ge(f):b==="del"?re(f):b==="rep"?g(f):K(f)},[ge,re,g,K]),Sn=a.useMemo(()=>{const f=new Set;return v.deletions.forEach(b=>b.tokenIndices.forEach(R=>f.add(R))),f},[v.deletions]),kn=a.useMemo(()=>{const f=new Set;return v.replacements.forEach(b=>b.tokenIndices.forEach(R=>f.add(R))),f},[v.replacements]),Cn=a.useMemo(()=>{const f=new Set;return v.comments.forEach(b=>b.tokenIndices.forEach(R=>f.add(R))),f},[v.comments]),Tt=a.useMemo(()=>{const f=new Map;return v.additions.forEach(b=>{const R=f.get(b.afterTokenIndex)||[];R.push(b),f.set(b.afterTokenIndex,R)}),f},[v.additions]),Et=v.additions.length>0||v.deletions.length>0||v.replacements.length>0||v.comments.length>0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[r.jsxs("div",{className:"plan-anno-toolbar",children:[r.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:t,children:t.split("/").pop()||t}),d&&r.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),r.jsx("button",{className:"pane-btn",onClick:_e,disabled:!Et,title:"Send all annotations to Chat editor",style:Et?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),r.jsxs("div",{ref:lt,style:{position:"relative",flex:1,minWidth:0},children:[r.jsxs("div",{className:`plan-anno-dropdown-trigger${Pe?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>Ct(f=>!f),title:T.total>0?`${T.total} annotations (${T.unsent} unsent)`:"No annotations",children:[r.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:(()=>{const f=v.additions[0],b=v.deletions[0],R=v.replacements[0],k=v.comments[0],y=f?f.content:b?b.selectedText:R?R.content:k?k.content:"";return y?y.slice(0,40)+(y.length>40?"...":""):""})()}),r.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),Pe&&r.jsxs("div",{className:"plan-anno-dropdown",children:[T.unsent>0&&r.jsx("div",{className:"plan-anno-dropdown__header",children:r.jsxs("button",{className:"pane-btn",onClick:_e,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",T.unsent,")"]})}),r.jsxs("div",{className:"plan-anno-dropdown__list",children:[v.additions.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--add",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-yellow)"},children:"+"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.content.slice(0,60),f.content.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"add"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"add"),title:"Delete",children:"×"})]},f.id)}),v.deletions.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--del",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-red)"},children:"−"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.selectedText.slice(0,60),f.selectedText.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"del"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"del"),title:"Delete",children:"×"})]},f.id)}),v.replacements.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--rep",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-blue)"},children:"⇄"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.content.slice(0,60),f.content.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"rep"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"rep"),title:"Delete",children:"×"})]},f.id)}),v.comments.map(f=>{const b=E.current.has(f.id);return r.jsxs("div",{className:"plan-anno-dropdown__item plan-anno-dropdown__item--com",children:[r.jsx("span",{className:"plan-anno-dropdown__type",style:{color:"var(--accent-green)"},children:"?"}),r.jsxs("span",{className:"plan-anno-dropdown__text",children:[f.content.slice(0,60),f.content.length>60?"...":""]}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!b&&De(f.id,"com"),disabled:b,title:b?"Already sent":"Send to terminal",style:b?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>Ve(f.id,"com"),title:"Delete",children:"×"})]},f.id)}),T.total===0&&r.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]}),u&&r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{_e(),u()},title:"Send annotations & close file",children:"×"})]}),r.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[r.jsxs("div",{ref:te,className:`plan-anno-content md-preview${w!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${m}px`,minWidth:0},onMouseUp:f=>{Ne.current={x:f.clientX,y:f.clientY,time:Date.now()},de()},children:[!h&&r.jsx(Kt,{index:-1,active:w===-1,additions:Tt.get(-1),onOpen:()=>{S(-1),Y("")},onSubmit:()=>we(-1),onRemoveAddition:ge,onEditAddition:Ae,onSendSingle:i?f=>De(f,"add"):void 0,isSent:f=>E.current.has(f),insertText:G,setInsertText:Y,textareaRef:w===-1?q:void 0,expanded:c,alwaysShow:x.length===0,fontSize:m}),x.map((f,b)=>{const R=to(f);return r.jsxs("div",{children:[r.jsx("div",{"data-token-index":b,id:N.get(b),className:Sn.has(b)?"plan-block--deleted":kn.has(b)?"plan-block--replaced":Cn.has(b)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:R}}),v.deletions.filter(k=>k.tokenIndices.includes(b)&&k.tokenIndices[0]===b).map(k=>r.jsx("div",{className:"plan-deletion-card",children:z===k.id?r.jsx("textarea",{ref:H,className:"plan-annotation-textarea",value:X,onChange:y=>_(y.target.value),onKeyDown:y=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)){y.preventDefault();const Z=X.trim();Z?ye(k.id,Z):re(k.id),P(null)}y.key==="Escape"&&(y.preventDefault(),P(null))},onBlur:()=>{const y=X.trim();y?ye(k.id,y):re(k.id),P(null)},rows:We(X),style:{fontSize:`${m}px`,flex:1}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{flex:1,fontSize:`${m}px`,color:"var(--accent-red)",textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{P(k.id),_(k.selectedText),requestAnimationFrame(()=>{const y=H.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},title:"Double-click to edit",children:k.selectedText}),i&&(()=>{const y=E.current.has(k.id);return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!y&&De(k.id,"del"),disabled:y,title:y?"Already sent":"Send to terminal",style:y?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{P(k.id),_(k.selectedText),requestAnimationFrame(()=>{const y=H.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},style:{color:"var(--accent-blue)"},title:"Edit deletion annotation",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>re(k.id),title:"Remove deletion",children:"×"})]})},k.id)),v.replacements.filter(k=>k.tokenIndices.includes(b)&&k.tokenIndices[0]===b).map(k=>r.jsx("div",{className:"plan-replace-card",children:oe===k.id?r.jsx("textarea",{ref:Te,className:"plan-annotation-textarea",value:be,onChange:y=>Ce(y.target.value),onKeyDown:y=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)){y.preventDefault();const Z=be.trim();Z?j(k.id,Z):g(k.id),ne(null)}y.key==="Escape"&&(y.preventDefault(),ne(null))},onBlur:()=>{const y=be.trim();y?j(k.id,y):g(k.id),ne(null)},rows:We(be),style:{fontSize:`${m}px`,flex:1}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{color:"var(--accent-blue)",flexShrink:0},children:"⇄"}),r.jsxs("span",{style:{flex:1,fontSize:`${m}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{ne(k.id),Ce(k.content),requestAnimationFrame(()=>{const y=Te.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},title:"Double-click to edit",children:[r.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:k.selectedText}),r.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),r.jsx("span",{style:{color:"var(--accent-blue)"},children:k.content})]}),i&&(()=>{const y=E.current.has(k.id);return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!y&&De(k.id,"rep"),disabled:y,title:y?"Already sent":"Send to terminal",style:y?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{ne(k.id),Ce(k.content),requestAnimationFrame(()=>{const y=Te.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},style:{color:"var(--accent-blue)"},title:"Edit replacement",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>g(k.id),title:"Remove replacement",children:"×"})]})},k.id)),v.comments.filter(k=>k.tokenIndices.includes(b)&&k.tokenIndices[0]===b).map(k=>r.jsx("div",{className:"plan-comment-card",children:Fe===k.id?r.jsx("textarea",{ref:me,className:"plan-annotation-textarea",value:xe,onChange:y=>Re(y.target.value),onKeyDown:y=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)){y.preventDefault();const Z=xe.trim();Z?ee(k.id,Z):K(k.id),ve(null)}y.key==="Escape"&&(y.preventDefault(),ve(null))},onBlur:()=>{const y=xe.trim();y?ee(k.id,y):K(k.id),ve(null)},rows:We(xe),style:{fontSize:`${m}px`,flex:1}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{color:"var(--accent-green)",flexShrink:0},children:"?"}),r.jsxs("span",{style:{flex:1,fontSize:`${m}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{ve(k.id),Re(k.content),requestAnimationFrame(()=>{const y=me.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},title:"Double-click to edit",children:[r.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',k.selectedText,'"']}),r.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),r.jsx("span",{style:{color:"var(--accent-green)"},children:k.content})]}),i&&(()=>{const y=E.current.has(k.id);return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!y&&De(k.id,"com"),disabled:y,title:y?"Already sent":"Send to terminal",style:y?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{ve(k.id),Re(k.content),requestAnimationFrame(()=>{const y=me.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=y.value.length)})},style:{color:"var(--accent-blue)"},title:"Edit comment",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>K(k.id),title:"Remove comment",children:"×"})]})},k.id)),Q&&Q.tokenIndices[0]===b&&r.jsxs("div",{className:Q.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[r.jsx("span",{style:{color:Q.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:Q.type==="replace"?"⇄":"?"}),r.jsx("textarea",{ref:F,className:"plan-annotation-textarea",value:he,onChange:k=>D(k.target.value),onKeyDown:k=>{if(k.key==="Enter"&&(k.ctrlKey||k.metaKey)){k.preventDefault(),$e();return}if(k.key==="Escape"){k.preventDefault(),$e();return}},onBlur:$e,placeholder:Q.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:We(he),style:{fontSize:`${m}px`,flex:1}})]}),!h&&r.jsx(Kt,{index:b,active:w===b,additions:Tt.get(b),onOpen:()=>{S(b),Y("")},onSubmit:()=>we(b),onRemoveAddition:ge,onEditAddition:Ae,onSendSingle:i?k=>De(k,"add"):void 0,isSent:k=>E.current.has(k),insertText:G,setInsertText:Y,textareaRef:w===b?q:void 0,expanded:c,fontSize:m})]},b)}),!h&&J&&r.jsxs("div",{className:"plan-selection-float",style:{top:J.y,left:J.x},children:[r.jsx("button",{className:"plan-selection-float__delete",onMouseDown:f=>{f.preventDefault(),Ke()},title:"Delete selection",children:"−"}),r.jsx("button",{className:"plan-selection-float__replace",onMouseDown:f=>{f.preventDefault(),Je("replace")},title:"Replace selection",children:"⇄"}),r.jsx("button",{className:"plan-selection-float__comment",onMouseDown:f=>{f.preventDefault(),Je("comment")},title:"Comment on selection",children:"?"})]})]}),r.jsx(Qr,{headings:$,scrollRef:te})]})]})});function Kt({index:n,active:e,additions:t,onOpen:o,onSubmit:s,onRemoveAddition:l,onEditAddition:i,onSendSingle:d,isSent:u,insertText:c,setInsertText:h,textareaRef:p,expanded:m,alwaysShow:x,fontSize:C=14}){const[$,N]=a.useState(null),[E,v]=a.useState(""),A=a.useRef(null),I=yt(),U=yt();a.useEffect(()=>{$&&(I.clearUndo(),requestAnimationFrame(()=>{const T=A.current;T&&(T.focus(),T.selectionStart=T.selectionEnd=T.value.length)}))},[$]),a.useEffect(()=>{e&&U.clearUndo()},[e]);const L=a.useCallback(T=>{v(w=>(I.pushUndo(w),T))},[I]),B=a.useCallback(T=>{U.pushUndo(c),h(T)},[c,h,U]),W=a.useCallback(T=>{N(T.id),v(T.content)},[]),O=a.useCallback(()=>{if(!$)return;const T=E.trim();T?i($,T):l($),N(null),v("")},[$,E,i,l]),V=a.useCallback(()=>{N(null),v("")},[]);return r.jsxs("div",{className:`plan-insert-zone${x?" plan-insert-zone--empty":""}`,"data-zone-index":n,children:[t==null?void 0:t.map(T=>r.jsx("div",{className:"plan-annotation-card",children:$===T.id?r.jsx("textarea",{ref:A,className:"plan-annotation-textarea",value:E,onChange:w=>L(w.target.value),onKeyDown:w=>{if(w.key==="Enter"&&(w.ctrlKey||w.metaKey)){w.preventDefault(),O();return}if(w.key==="Escape"){w.preventDefault(),V();return}if(w.key==="Tab"){vt(w,L);return}},onBlur:O,rows:We(E),style:{fontSize:`${C}px`,flex:1,...m?{minWidth:300}:void 0}}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{flex:1,fontSize:`${C}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>W(T),title:"Double-click to edit",children:T.content}),d&&(()=>{const w=(u==null?void 0:u(T.id))??!1;return r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!w&&d(T.id),disabled:w,title:w?"Already sent":"Send to terminal",style:w?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>W(T),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(T.id),children:"×"})]})},T.id)),e?r.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:r.jsx("textarea",{ref:p,className:"plan-annotation-textarea",value:c,onChange:T=>B(T.target.value),onKeyDown:T=>{if(T.key==="Enter"&&(T.ctrlKey||T.metaKey)){T.preventDefault(),s();return}if(T.key==="Escape"){T.preventDefault(),s();return}if(T.key==="Tab"){vt(T,B);return}},placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:We(c),style:{fontSize:`${C}px`,...m?{minWidth:300}:void 0}})}):x&&!(t!=null&&t.length)?r.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:o,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):r.jsx("button",{className:"plan-insert-btn",onClick:o,title:"Add annotation here",children:"+"})]})}async function ke(n,e,t){const o=t?`?path=${encodeURIComponent(t)}`:"",s=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/files${o}`,{headers:ie(n)});if(!s.ok)throw new Error("Failed to list files");return s.json()}function oo(n,e,t,o){return new Promise((s,l)=>{const i=new FormData;for(const u of t)i.append("files",u);const d=new XMLHttpRequest;d.open("POST",`${se}/api/sessions/${encodeURIComponent(e)}/upload`),d.setRequestHeader("Authorization",`Bearer ${n}`),d.upload.addEventListener("progress",u=>{u.lengthComputable&&o&&o(Math.round(u.loaded/u.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?s():l(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>l(new Error("Upload network error"))),d.addEventListener("abort",()=>l(new Error("Upload aborted"))),d.send(i)})}async function so(n,e){const t=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/cwd`,{headers:ie(n)});if(!t.ok)throw new Error("Failed to fetch cwd");return(await t.json()).cwd}async function wt(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/touch`,{method:"POST",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({name:t})});if(!o.ok)throw new Error("Failed to create file");return o.json()}async function hn(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/mkdir`,{method:"POST",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!o.ok)throw new Error("Failed to create directory");return o.json()}async function ao(n,e,t){if(!(await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/rm`,{method:"DELETE",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({path:t})})).ok)throw new Error("Failed to delete")}async function io(n,e){const t=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/download-cwd`,{headers:ie(n)});if(!t.ok)throw new Error("Download failed");const o=await t.blob(),s=URL.createObjectURL(o),l=document.createElement("a");l.href=s;const i=t.headers.get("Content-Disposition"),d=i==null?void 0:i.match(/filename="(.+)"/);l.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(s)}async function lo(n,e,t){const o=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/download?path=${encodeURIComponent(t)}`,{headers:ie(n)});if(!o.ok)throw new Error("Download failed");const s=await o.blob(),l=URL.createObjectURL(s),i=document.createElement("a");i.href=l,i.download=t.split("/").pop()||"download",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(l)}function bn(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:n<1024*1024*1024?`${(n/(1024*1024)).toFixed(1)} MB`:`${(n/(1024*1024*1024)).toFixed(1)} GB`}function co(n,e){if(e==="directory")return"📁";const t=n.slice(n.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}function xn(n){const e=new Date(n*1e3),t=o=>String(o).padStart(2,"0");return`${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}function uo({sessionId:n,token:e,planDir:t,selectedFile:o,onSelectFile:s,onCreateFile:l,onDeleteFile:i}){const[d,u]=a.useState([]),[c,h]=a.useState(!0),[p,m]=a.useState(""),[x,C]=a.useState(!1),$=a.useRef(null),[N,E]=a.useState(t),v=a.useCallback(async()=>{if(!(!e||!N)){h(!0);try{const G=(await ke(e,n,N)).files.filter(Y=>Y.type==="file"&&Y.name.toLowerCase().endsWith(".md")||Y.type==="directory").sort((Y,q)=>{const z=Y.type==="file"&&Y.name===".index.md",P=q.type==="file"&&q.name===".index.md";return z&&!P?-1:!z&&P?1:Y.type==="directory"&&q.type!=="directory"?-1:Y.type!=="directory"&&q.type==="directory"?1:Y.name.localeCompare(q.name)});u(G)}catch{u([])}finally{h(!1)}}},[e,n,N]);a.useEffect(()=>{v()},[v]),a.useEffect(()=>{const S=setInterval(v,5e3);return()=>clearInterval(S)},[v]);const A=a.useCallback(()=>{const S=t.substring(0,t.lastIndexOf("/")+1);return N.startsWith(S)?N.substring(S.length):N},[t,N]),I=a.useCallback(async()=>{const S=p.trim();if(!S)return;const G=S.endsWith(".md")?S:`${S}.md`;C(!0);try{const Y=await wt(e,n,`${A()}/${G}`);Y.ok&&(m(""),await v(),l(Y.path))}catch{}finally{C(!1)}},[p,e,n,A,v,l]),U=a.useCallback(async()=>{const S=p.trim().replace(/\/+$/,"");if(S){C(!0);try{await hn(e,n,`${A()}/${S}`),m(""),await v()}catch{}finally{C(!1)}}},[p,e,n,A,v]),L=a.useCallback(async S=>{const G=`${N}/${S.name}`,Y=S.type==="directory"?`folder "${S.name}" and all its contents`:`"${S.name}"`;if(window.confirm(`Delete ${Y}?`))try{await ao(e,n,G),i==null||i(G),await v()}catch{}},[e,n,N,v,i]),B=a.useCallback(S=>{E(G=>`${G}/${S}`)},[]),W=a.useCallback(()=>{N!==t&&E(S=>S.substring(0,S.lastIndexOf("/")))},[N,t]),O=t.split("/").pop()||"TASK",V=(()=>{const S=t.split("/");return S.length>=2?S[S.length-2]+"/":""})(),T=N===t?V+O+"/":V+O+"/"+N.substring(t.length+1)+"/",w=o?o.split("/").pop():null;return r.jsxs("div",{className:"plan-file-browser",children:[r.jsxs("div",{className:"plan-file-browser__header",children:[r.jsx("span",{className:"plan-file-browser__title",title:T,children:T}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:v,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),r.jsxs("div",{className:"plan-file-browser__create",children:[r.jsx("input",{ref:$,className:"plan-file-browser__input",value:p,onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),I())},placeholder:"name",disabled:x}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:I,disabled:x||!p.trim(),title:"Create new .md file",style:p.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),r.jsx("button",{className:"pane-btn pane-btn--sm",onClick:U,disabled:x||!p.trim(),title:"Create new folder",style:p.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),r.jsxs("div",{className:"plan-file-browser__list",children:[c&&d.length===0&&r.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&d.length===0&&r.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),N!==t&&r.jsxs("div",{className:"plan-file-browser__item",onClick:W,title:"Go up to parent directory",style:{cursor:"pointer"},children:[r.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),r.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(S=>{const G=`${N}/${S.name}`,Y=S.type==="file"&&S.name===w,q=S.type==="directory";return r.jsxs("div",{className:`plan-file-browser__item${Y?" plan-file-browser__item--active":""}`,onClick:()=>q?B(S.name):s(G),title:q?`Open folder ${S.name}`:S.name,style:{cursor:"pointer"},children:[r.jsx("span",{className:"plan-file-browser__icon",children:q?"📁":S.name===".index.md"?"🔒":"□"}),r.jsxs("span",{className:"plan-file-browser__name",children:[S.name,q?"/":""]}),!q&&r.jsx("span",{className:"plan-file-browser__size",children:bn(S.size)}),S.name!==".index.md"&&r.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:z=>{z.stopPropagation(),L(S)},title:`Delete ${S.name}`,children:"×"})]},S.name)})]})]})}const bt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},fo=200;function po(){const[n,e]=a.useState(bt),t=a.useRef("lines"),o=a.useRef([]),s=a.useRef(""),l=a.useRef(""),i=a.useRef([]),d=a.useRef(0),u=a.useRef(0),c=a.useRef(null),h=a.useRef(null),p=a.useCallback(()=>{const E=t.current;e(v=>({...v,receivedBytes:d.current,...E==="lines"?{lines:[...o.current]}:{},...E==="content"?{content:l.current}:{}}))},[]),m=a.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,p()},fo))},[p]),x=a.useCallback(E=>{t.current=E,o.current=[],s.current="",l.current="",i.current=[],d.current=0,u.current=0,h.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...bt,mode:E,status:"streaming"})},[]),C=a.useCallback(E=>{d.current+=E.length;const v=t.current;if(v==="lines"){const I=h.current.decode(E,{stream:!0}).split(`
|
|
30
|
+
`);I[0]=s.current+I[0],s.current=I.pop(),I.length>0&&o.current.push(...I)}else if(v==="content"){const A=h.current.decode(E,{stream:!0});l.current+=A}else i.current.push(new Uint8Array(E));m()},[m]),$=a.useCallback(E=>{switch(E.type){case"file-stream-start":u.current=E.size,e(v=>({...v,totalSize:E.size,mtime:E.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const v=t.current;let A=o.current,I=l.current,U=null;if(v==="lines"){const L=h.current.decode(),B=s.current+L;B&&(A=[...A,B],o.current=A),s.current=""}else if(v==="content"){const L=h.current.decode();I=l.current+L,l.current=I}else{const L=i.current.reduce((W,O)=>W+O.length,0);U=new Uint8Array(L);let B=0;for(const W of i.current)U.set(W,B),B+=W.length;i.current=[]}e({status:"complete",mode:v,lines:v==="lines"?[...A]:[],content:v==="content"?I:"",buffer:v==="binary"?U:null,totalSize:u.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(v=>({...v,status:"error",error:E.error}));break}},[]),N=a.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),o.current=[],s.current="",l.current="",i.current=[],d.current=0,u.current=0,h.current=null,e(bt)},[]);return{state:n,startStream:x,handleChunk:C,handleControl:$,reset:N}}function qt({label:n,percent:e}){return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:n}),e!=null&&r.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[r.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),r.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function mo({sessionId:n,token:e,connected:t,onRequestFileStream:o,onForwardToChat:s,onSendToTerminal:l}){const i=po(),[d,u]=a.useState(!1),c=a.useRef(""),[h,p]=a.useState(null),[m,x]=a.useState(null),[C,$]=a.useState(""),[N,E]=a.useState(!1),v=a.useRef(new Map),A=a.useRef(null),I=a.useRef(null);a.useEffect(()=>{I.current=null;let z=!1;return E(!0),(async()=>{try{const P=await ke(e,n);if(z)return;if(P.files.find(_=>_.name==="TASK"&&_.type==="directory")){const _=P.cwd+"/TASK",H=await ke(e,n,_);if(z)return;const oe=H.files.find(ne=>ne.name===".index.md");if(oe)p(_),x(_+"/"+oe.name);else try{const ne=await wt(e,n,"TASK/.index.md");if(z)return;p(_),ne.ok&&x(ne.path)}catch{p(_)}}else try{const _=await hn(e,n,"TASK");if(z)return;p(_.path);const H=await wt(e,n,"TASK/.index.md");if(z)return;H.ok&&x(H.path)}catch{p(null),x(null)}}catch{p(null)}finally{z||E(!1)}try{const P=await ke(e,n);if(z)return;const X=P.home||"";if(c.current=P.cwd,X){const _=`${X}/.claude/commands`;try{const H=await ke(e,n,_);if(z)return;H.files.some(ne=>ne.name==="aicli-task-review.md")||u(!0)}catch{z||u(!0)}}}catch{}})(),()=>{z=!0}},[n,e]),a.useEffect(()=>(wr(n,i.handleChunk,i.handleControl),()=>Sr(n)),[n,i.handleChunk,i.handleControl]),a.useEffect(()=>{!m||!t||I.current===m&&C||(I.current=m,i.reset(),i.startStream("content"),o==null||o(m))},[m,t]),a.useEffect(()=>{i.state.status==="complete"&&m&&($(i.state.content),v.current.set(m,i.state.content))},[i.state.status,i.state.content,m]);const U=a.useRef(new Map),L=a.useCallback(()=>{var P,X;if(!m)return;const z=((X=(P=A.current)==null?void 0:P.getScrollTop)==null?void 0:X.call(P))??0;z>0&&U.current.set(m,z)},[m]);a.useEffect(()=>{if(!m||!C)return;const z=U.current.get(m);z!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var P,X;(X=(P=A.current)==null?void 0:P.setScrollTop)==null||X.call(P,z)})})},[m,C]);const B=a.useCallback(z=>{z!==m&&(L(),m&&C&&v.current.set(m,C),x(z),$(""),I.current=null)},[m,C,L]),W=a.useCallback(z=>{m&&(m===z||m.startsWith(z+"/"))&&(x(null),$(""),I.current=null),v.current.delete(z)},[m]),O=a.useCallback(z=>{x(z),$(""),I.current=null},[]),V=a.useCallback(z=>{z&&(s==null||s(z))},[s]),T=a.useCallback(()=>{L(),m&&C&&v.current.set(m,C),x(null),$(""),I.current=null},[m,C,L]),w=a.useCallback(()=>{!m||!t||(I.current=null,$(""),i.reset(),i.startStream("content"),o==null||o(m),I.current=m)},[m,t,i,o]),[S,G]=a.useState(()=>{const z=localStorage.getItem(`plan-fb-width-${n}`);if(z){const P=Number(z);if(Number.isFinite(P)&&P>=60&&P<=300)return P}return 130}),Y=a.useRef(S);if(S!==Y.current){Y.current=S;try{localStorage.setItem(`plan-fb-width-${n}`,String(Math.round(S)))}catch{}}const q=a.useCallback(z=>{z.preventDefault();const P=z.clientX,X=S;document.body.classList.add("resizing-panes");const _=oe=>{const ne=oe.clientX-P;G(Math.min(300,Math.max(60,X+ne)))},H=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",H)};document.addEventListener("mousemove",_),document.addEventListener("mouseup",H)},[S]);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[d&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",fontSize:12,flexShrink:0},children:[r.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"/aicli-task-review command not installed"}),r.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{const z=c.current;z&&l&&l(`mkdir -p ~/.claude/commands && cp ${z}/.commands/*.md ~/.claude/commands/`),u(!1)},children:"Install"}),r.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>u(!1),children:"×"})]}),r.jsxs("div",{className:"plan-overlay-body",children:[h&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{width:S,flexShrink:0,overflow:"hidden"},children:r.jsx(uo,{sessionId:n,token:e,planDir:h,selectedFile:m,onSelectFile:B,onCreateFile:O,onDeleteFile:W})}),r.jsx("div",{onMouseDown:q,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:z=>{z.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="var(--border)"}})]}),r.jsx("div",{className:"plan-overlay-center",children:N?r.jsx(qt,{label:"Loading TASK/..."}):m&&!C&&(i.state.status==="streaming"||i.state.status==="idle")?r.jsx(qt,{label:`Loading ${m.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):m?r.jsx(ro,{ref:A,markdown:C,filePath:m,sessionId:n,token:e,onExecute:V,onSend:l,onRefresh:w,onClose:T,readOnly:m.endsWith("/.index.md")}):r.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]})]})}async function ho(n,e){try{const t=await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/draft`,{headers:ie(n)});return t.ok?(await t.json()).content??"":""}catch{return""}}async function Jt(n,e,t){try{await fetch(`${se}/api/sessions/${encodeURIComponent(e)}/draft`,{method:"PUT",headers:{...ie(n),"Content-Type":"application/json"},body:JSON.stringify({content:t})})}catch{}}const kt="chat-history",Vt=50;function gn(){try{const n=localStorage.getItem(kt);return n?JSON.parse(n):[]}catch{return[]}}function bo(n){const t=gn().filter(o=>o.text!==n);t.unshift({text:n,ts:Date.now()}),t.length>Vt&&(t.length=Vt),localStorage.setItem(kt,JSON.stringify(t))}const Yt=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],xo=a.forwardRef(function({onSend:e,onContentChange:t,sessionId:o,token:s},l){const i=M(g=>g.fontSize),[d,u]=a.useState(""),c=a.useRef(null),h=a.useRef(void 0),p=a.useRef(!1),m=a.useRef(!1),{pushUndo:x,popUndo:C}=yt(),$=a.useRef(d);$.current=d;const N=a.useCallback(()=>x($.current),[x]),[E,v]=a.useState(!1),[A,I]=a.useState(""),[U,L]=a.useState(0),[B,W]=a.useState(!1),[O,V]=a.useState([]),[T,w]=a.useState(0),[S,G]=a.useState(""),Y=a.useRef(null),q=a.useMemo(()=>{if(!S)return O;const g=S.toLowerCase();return O.filter(j=>j.text.toLowerCase().includes(g))},[O,S]),[z,P]=a.useState(!1),[X,_]=a.useState(""),[H,oe]=a.useState(""),[ne,be]=a.useState(0),[Ce,Te]=a.useState([]),[Fe,ve]=a.useState(!1),xe=a.useRef(""),Re=a.useRef(null),me=a.useMemo(()=>{if(!A)return Yt;const g=A.toLowerCase();return Yt.filter(j=>j.cmd.toLowerCase().includes(g)||j.desc.toLowerCase().includes(g))},[A]),Q=a.useMemo(()=>{let g=Ce;if(X){const j=X.toLowerCase();g=g.filter(K=>K.name.toLowerCase().includes(j))}return[...g].sort((j,K)=>j.type==="directory"&&K.type!=="directory"?-1:j.type!=="directory"&&K.type==="directory"?1:j.name.localeCompare(K.name))},[Ce,X]),Me=M(g=>g.latency),he=`chat-draft-${o}`,D=a.useRef(!1),F=a.useRef(void 0);a.useEffect(()=>{try{const j=localStorage.getItem(he);j&&!m.current&&u(j)}catch{}let g=!1;return ho(s,o).then(j=>{if(g||m.current){p.current=!0;return}if(j){u(j);try{localStorage.setItem(he,j)}catch{}}p.current=!0}).catch(()=>{p.current=!0}),()=>{g=!0}},[s,o,he]),a.useEffect(()=>{if(!p.current)return;h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{try{localStorage.setItem(he,d)}catch{}},50),F.current&&clearTimeout(F.current);const g=Math.max(200,(Me??30)*3);return F.current=setTimeout(()=>{D.current||(D.current=!0,Jt(s,o,d).catch(()=>{}).finally(()=>{D.current=!1}))},g),()=>{h.current&&clearTimeout(h.current),F.current&&clearTimeout(F.current)}},[d,s,o,Me,he]),a.useEffect(()=>{var g;(g=c.current)==null||g.focus()},[]),a.useEffect(()=>{if(!z)return;let g=!1;return ve(!0),(async()=>{try{if(H){if(!xe.current){const ee=await ke(s,o);if(g)return;xe.current=ee.cwd}const j=`${xe.current}/${H.replace(/\/$/,"")}`,K=await ke(s,o,j);if(g)return;Te(K.files)}else{const j=await ke(s,o);if(g)return;xe.current=j.cwd,Te(j.files)}ve(!1)}catch{if(g)return;Te([]),ve(!1)}})(),()=>{g=!0}},[z,H,s,o]),a.useEffect(()=>{if(!z||!Re.current)return;const g=Re.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[ne,z]);const J=a.useCallback(()=>{const g=$.current.trim();if(g){bo(g),e(g),u("");try{localStorage.removeItem(he)}catch{}Jt(s,o,"").catch(()=>{})}},[e,s,o,he]),ae=a.useCallback(g=>{N(),u(g),m.current=!0},[N]),te=a.useCallback(g=>{const j=c.current;N();const K=$.current;if(j){const ee=j.selectionStart,re=j.selectionEnd,ye=K.slice(0,ee)+g+K.slice(re);u(ye);const le=ee+g.length;requestAnimationFrame(()=>{j.selectionStart=j.selectionEnd=le,j.focus()})}else u(K+g)},[N]);a.useImperativeHandle(l,()=>({send:J,fillContent:ae,insertAtCursor:te}),[J,ae,te]),a.useEffect(()=>{t==null||t(d.trim().length>0)},[d,t]);const Ee=a.useCallback(()=>{const g=c.current;if(!g)return;const{selectionStart:j,selectionEnd:K}=g;if(j!==K){const ee=g.value.substring(j,K);ee&&navigator.clipboard.writeText(ee).catch(()=>{})}},[]),Ne=a.useCallback(()=>{const g=gn();v(!1),I("");const j=c.current;if(j){const K=j.selectionStart,ee=d.slice(0,K),re=d.slice(K),ye=ee.match(/(?:^|\s)(\/history)\s*$/);if(ye){const le=ee.length-ye[1].length;u(d.slice(0,le)+re)}}g.length!==0&&(V(g),w(0),G(""),W(!0))},[d]),we=a.useCallback(g=>{N(),u(g.text),W(!1),requestAnimationFrame(()=>{const j=c.current;j&&(j.selectionStart=j.selectionEnd=g.text.length,j.focus())})},[N]),ge=a.useCallback(g=>{const j=q[g];if(!j)return;const K=O.filter(re=>re.ts!==j.ts||re.text!==j.text);V(K),localStorage.setItem(kt,JSON.stringify(K));const ee=S?K.filter(re=>re.text.toLowerCase().includes(S.toLowerCase())):K;T>=ee.length&&w(Math.max(0,ee.length-1))},[q,O,T,S]);a.useEffect(()=>{if(!B||!Y.current)return;const g=Y.current.querySelector(".history-item--active");g==null||g.scrollIntoView({block:"nearest"})},[T,B]);const Ae=a.useCallback(g=>{if(g==="/history"){Ne();return}const j=c.current;if(!j)return;N();const K=j.selectionStart,ee=d.slice(0,K),re=d.slice(K),le=ee.lastIndexOf(`
|
|
31
31
|
`)+1,ce=ee.slice(le).match(/\/[a-zA-Z:-]*$/);if(ce){const fe=le+(ce.index??0),Se=g+" ",_e=d.slice(0,fe)+Se+re;u(_e);const Pe=fe+Se.length;requestAnimationFrame(()=>{j.selectionStart=j.selectionEnd=Pe,j.focus()})}else{const fe=ee+g+re;u(fe);const Se=K+g.length;requestAnimationFrame(()=>{j.selectionStart=j.selectionEnd=Se,j.focus()})}v(!1),I(""),L(0)},[d,N,Ne]),Ke=a.useCallback(g=>{const j=c.current;if(!j)return;N();const K=j.selectionStart,ee=d.slice(0,K),re=d.slice(K),ye=ee.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!ye)return;const le=ee.length-ye[0].length;if(g.type==="directory"){const de="@"+H+g.name+"/",ce=d.slice(0,le)+de+re;u(ce);const fe=le+de.length;oe(H+g.name+"/"),_(""),be(0),requestAnimationFrame(()=>{j.selectionStart=j.selectionEnd=fe,j.focus()})}else{const de=g.name+" ",ce=d.slice(0,le)+de+re;u(ce);const fe=le+de.length;P(!1),_(""),oe(""),be(0),Te([]),xe.current="",requestAnimationFrame(()=>{j.selectionStart=j.selectionEnd=fe,j.focus()})}},[d,H,N]),Je=a.useCallback(g=>{const j=g.target.value;if(u(j),B){const de=j.trim();de?(G(de),w(0)):G("");return}const K=g.target.selectionStart,ee=j.slice(0,K),re=ee.lastIndexOf(`
|
|
32
|
-
`),le=ee.slice(re+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(le)v(!0),I(le[1]),L(0),P(!1);else{v(!1);const de=ee.match(/@([a-zA-Z0-9_.\-/]*)$/);if(de){const ce=de[1],fe=ce.lastIndexOf("/"),Se=fe>=0?ce.slice(0,fe+1):"",_e=fe>=0?ce.slice(fe+1):ce;_(_e),be(0),oe(Se),P(!0)}else P(!1)}},[B]),ze=a.useCallback(g=>{if(E&&me.length>0){if(g.key==="ArrowDown"){g.preventDefault(),L(j=>(j+1)%me.length);return}if(g.key==="ArrowUp"){g.preventDefault(),L(j=>(j-1+me.length)%me.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),Ae(me[U].cmd);return}if(g.key==="Escape"){g.preventDefault(),v(!1);return}}if($&&Q.length>0){if(g.key==="ArrowDown"){g.preventDefault(),be(j=>(j+1)%Q.length);return}if(g.key==="ArrowUp"){g.preventDefault(),be(j=>(j-1+Q.length)%Q.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),Ke(Q[ne]);return}if(g.key==="Escape"){g.preventDefault(),P(!1);return}}if(B&&q.length>0){if(g.key==="ArrowDown"){g.preventDefault(),w(j=>(j+1)%q.length);return}if(g.key==="ArrowUp"){g.preventDefault(),w(j=>(j-1+q.length)%q.length);return}if(g.key==="Enter"){g.preventDefault(),we(q[T]);return}if(g.key==="Delete"||g.key==="Backspace"&&(g.ctrlKey||g.metaKey)){g.preventDefault(),ge(T);return}if(g.key==="Escape"){g.preventDefault(),W(!1);return}}if(g.key==="Tab"){vt(g,u,x);return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),J())},[J,E,me,U,Ae,$,Q,ne,Ke,x,C,B,q,T,we,ge]);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[E&&me.length>0&&r.jsx("div",{className:"slash-dropdown",children:me.map((g,j)=>r.jsxs("div",{className:`slash-item${j===U?" slash-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ae(g.cmd)},onMouseEnter:()=>L(j),children:[r.jsx("span",{className:"slash-cmd",children:g.cmd}),r.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),$&&(Fe||Q.length>0)&&r.jsx("div",{className:"file-dropdown",ref:Re,children:Fe?r.jsx("div",{className:"file-item file-loading",children:"Loading..."}):Q.map((g,j)=>r.jsxs("div",{className:`file-item${j===ne?" file-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ke(g)},onMouseEnter:()=>be(j),children:[r.jsx("span",{className:"file-icon",children:g.type==="directory"?"📁":"📄"}),r.jsx("span",{className:"file-name",children:g.name})]},g.name))}),B&&r.jsx("div",{className:"history-dropdown",ref:Y,children:q.length===0?r.jsx("div",{className:"history-item history-empty",children:"No history yet"}):q.map((g,j)=>r.jsxs("div",{className:`history-item${j===T?" history-item--active":""}`,onMouseDown:K=>{K.preventDefault(),we(g)},onMouseEnter:()=>w(j),children:[r.jsx("span",{className:"history-text",children:g.text.length>120?g.text.slice(0,120)+"...":g.text}),r.jsx("span",{className:"history-time",children:new Date(g.ts).toLocaleString()}),r.jsx("button",{className:"history-delete",onMouseDown:K=>{K.preventDefault(),K.stopPropagation(),ge(j)},title:"Delete (Del key)",children:"×"})]},`${g.ts}-${j}`))}),r.jsx("textarea",{ref:c,className:"md-editor-textarea",value:d,onChange:Je,onKeyDown:ze,onMouseUp:Ee,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${i}px`}})]})}),go=600,Ue=typeof window<"u"?window.matchMedia(`(max-width: ${go-1}px)`):null;function yo(){const[n,e]=a.useState(()=>(Ue==null?void 0:Ue.matches)??!1);return a.useEffect(()=>{if(!Ue)return;const t=o=>e(o.matches);return Ue.addEventListener("change",t),()=>Ue.removeEventListener("change",t)},[]),n}const vo=a.memo(function({terminal:e}){const t=yo(),o=M(D=>D.splitTerminal),s=M(D=>D.token),l=M(D=>D.toggleChat),i=M(D=>D.togglePlan),{chatOpen:d,planOpen:u}=e.panels,c=a.useCallback(async D=>{let F;if(s)try{F=await so(s,e.id)}catch{}o(e.id,D,F)},[s,e.id,o]),h=a.useRef(null),p=a.useRef(null),m=a.useRef(null),[x,C]=a.useState(!1),[z,N]=a.useState(0),[E,v]=a.useState(!1),[A,I]=a.useState(!1),[U,L]=a.useState(!1),[B,W]=a.useState([]),[O,V]=a.useState(""),[T,w]=a.useState([]),[S,G]=a.useState(!1),Y=a.useRef(null),q=a.useRef(null),$=a.useRef(null),[P,X]=a.useState(()=>{const D=localStorage.getItem(`plan-width-${e.id}`);if(D){const F=Number(D);if(Number.isFinite(F)&&F>=20&&F<=80)return F}return 50}),_=a.useRef(P);if(P!==_.current){_.current=P;try{localStorage.setItem(`plan-width-${e.id}`,String(Math.round(P)))}catch{}}const[H,oe]=a.useState(()=>{const D=localStorage.getItem(`doc-height-${e.id}`);if(D){const F=Number(D);if(Number.isFinite(F)&&F>=15&&F<=60)return F}return 35}),ne=a.useRef(H);if(H!==ne.current){ne.current=H;try{localStorage.setItem(`doc-height-${e.id}`,String(Math.round(H)))}catch{}}const be=async D=>{const F=D.target.files;if(!(!F||F.length===0||!s)){C(!0),N(0);try{await oo(s,e.id,F,J=>{N(J)})}catch(J){alert(`Upload failed: ${J instanceof Error?J.message:"Unknown error"}`)}finally{C(!1),N(0),h.current&&(h.current.value="")}}},Ce=a.useRef(void 0),Te=a.useCallback(D=>{if(p.current){const F=D.replace(/\r?\n/g," ").trimEnd();p.current.sendInput(F),Ce.current=window.setTimeout(()=>{var J;return(J=p.current)==null?void 0:J.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{Ce.current&&clearTimeout(Ce.current)},[]);const Fe=a.useCallback(async()=>{if(s){G(!0),L(!0);try{const D=await ke(s,e.id);V(D.cwd),W(D.files),w([])}catch{L(!1)}finally{G(!1)}}},[s,e.id]),ve=a.useCallback(async D=>{if(s){G(!0);try{const F=await ke(s,e.id,D);w(J=>[...J,O]),V(D),W(F.files)}catch{}finally{G(!1)}}},[s,e.id,O]),xe=a.useCallback(async()=>{if(!s||T.length===0)return;const D=T[T.length-1];G(!0);try{const F=await ke(s,e.id,D);w(J=>J.slice(0,-1)),V(D),W(F.files)}catch{}finally{G(!1)}},[s,e.id,T]),Re=a.useCallback(async D=>{if(s)try{await lo(s,e.id,D)}catch(F){alert(`Download failed: ${F instanceof Error?F.message:"Unknown error"}`)}},[s,e.id]);a.useEffect(()=>{if(!U)return;const D=ae=>{ae.key==="Escape"&&L(!1)},F=ae=>{Y.current&&!Y.current.contains(ae.target)&&L(!1)};document.addEventListener("keydown",D);const J=setTimeout(()=>document.addEventListener("mousedown",F),50);return()=>{document.removeEventListener("keydown",D),document.removeEventListener("mousedown",F),clearTimeout(J)}},[U]);const me=a.useCallback(D=>{if(p.current){const F=D.replace(/\r?\n/g," ").trimEnd();p.current.sendInput(F),setTimeout(()=>{var J;return(J=p.current)==null?void 0:J.sendInput("\r")},50)}},[]),Q=a.useCallback(D=>{D&&m.current&&m.current.fillContent(D)},[]),Me=a.useCallback(D=>{D.preventDefault();const F=q.current;if(!F)return;const J=F.getBoundingClientRect(),ae=J.height-24;document.body.classList.add("resizing-panes-v");const te=Ne=>{const ge=(Ne.clientY-J.top-24)/ae*100,Ae=Math.min(85,Math.max(40,ge));oe(100-Ae)},Ee=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",Ee)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",Ee)},[]),he=a.useCallback(D=>{D.preventDefault();const F=$.current;if(!F)return;const J=F.getBoundingClientRect(),ae=J.width;document.body.classList.add("resizing-panes");const te=Ne=>{const we=(Ne.clientX-J.left)/ae*100,ge=Math.min(80,Math.max(20,we));X(ge)},Ee=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",Ee)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",Ee)},[]);return r.jsxs("div",{ref:q,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[r.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)"}}),r.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)"},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx("input",{ref:h,type:"file",multiple:!0,style:{display:"none"},onChange:be}),r.jsx("button",{className:"pane-btn",onClick:()=>{var D;return(D=h.current)==null?void 0:D.click()},disabled:x,style:x?{color:"var(--accent-yellow)"}:void 0,title:x?`Uploading ${z}%`:"Upload files","aria-label":"Upload files",children:x?`${z}%`:"↑"}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx("button",{className:"pane-btn",onClick:Fe,disabled:E,style:E?{color:"var(--accent-yellow)"}:void 0,title:E?"Downloading...":"Download files","aria-label":"Download files",children:E?"...":"↓"}),U&&r.jsxs("div",{ref:Y,style:{position:"absolute",top:"100%",right:0,marginTop:4,width:300,maxHeight:360,backgroundColor:"var(--bg-primary)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:100,display:"flex",flexDirection:"column",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[T.length>0&&r.jsx("button",{className:"pane-btn",onClick:xe,disabled:S,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),r.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:O.split("/").slice(-2).join("/")||O}),r.jsx("button",{className:"pane-btn",onClick:()=>L(!1),style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),r.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:S?r.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):B.length===0?r.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):B.map(D=>r.jsxs("div",{onClick:()=>{const F=O+"/"+D.name;D.type==="directory"?ve(F):Re(F)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:F=>{F.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:F=>{F.currentTarget.style.backgroundColor="transparent"},children:[r.jsx("span",{style:{flexShrink:0,fontSize:13},children:D.type==="directory"?"📁":co(D.name,D.type)}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.name}),D.type==="directory"?r.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):D.size!=null?r.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:bn(D.size)}):null]},D.name))}),r.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:r.jsx("button",{className:"pane-btn",onClick:async()=>{v(!0),L(!1);try{await io(s||"",e.id)}catch(D){alert(`Download failed: ${D instanceof Error?D.message:"Unknown error"}`)}finally{v(!1)}},style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:"Download All (tar.gz)"})})]})]}),r.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),r.jsx("button",{className:`pane-btn${u?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),r.jsx("button",{className:"pane-btn",onClick:()=>c(t?"vertical":"horizontal"),title:t?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),r.jsx("button",{className:"pane-btn",onClick:()=>c("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),r.jsxs("div",{ref:$,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{width:`${P}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:r.jsx(mo,{sessionId:e.id,token:s||"",connected:e.connected,onRequestFileStream:D=>{var F;return(F=p.current)==null?void 0:F.requestFileStream(D)},onCancelFileStream:()=>{var D;return(D=p.current)==null?void 0:D.cancelFileStream()},onForwardToChat:Q,onSendToTerminal:me})}),r.jsx("div",{className:"md-editor-divider-h",onMouseDown:he,style:{width:"2px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:D=>{D.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:D=>{D.currentTarget.style.backgroundColor="var(--border)"}})]}),r.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[r.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[r.jsx(Fr,{ref:p,sessionId:e.id}),!e.connected&&r.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"md-editor-divider",onMouseDown:Me}),r.jsxs("div",{style:{height:`${H}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",height:"22px",flexShrink:0,backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),r.jsx("button",{className:"pane-btn",onClick:()=>{var D;return(D=m.current)==null?void 0:D.send()},disabled:!A,title:"Send to terminal (Ctrl+Enter)",style:A?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),r.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),r.jsx("div",{style:{flex:1,overflow:"hidden"},children:r.jsx(xo,{ref:m,onSend:Te,onContentChange:I,sessionId:e.id,token:s||""})})]})]})]})]}),e.error&&r.jsx("div",{style:{padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--accent-red)",color:"var(--accent-red)",fontSize:"11px",flexShrink:0},children:e.error})]})});class yn extends a.Component{constructor(){super(...arguments);Nt(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,o){}render(){var t,o;return this.state.hasError?this.props.inline?r.jsxs("div",{style:{height:"100%",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"var(--text-bright)",fontFamily:"monospace",padding:"16px"},children:[r.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),r.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textAlign:"center"},children:((t=this.state.error)==null?void 0:t.message)||"An unexpected error occurred"}),r.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-bright)",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):r.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"var(--text-bright)",fontFamily:"monospace"},children:[r.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),r.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((o=this.state.error)==null?void 0:o.message)||"An unexpected error occurred"}),r.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",border:"none",color:"var(--bg-primary)",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const wo=4,Gt=10;function So(){const n=M(s=>s.layout),e=M(s=>s.terminalIds.length),t=M(s=>s.addTerminal);if(!n)return r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:r.jsx("button",{onClick:()=>t(),style:{background:"none",border:"1px dashed var(--border)",color:"var(--text-secondary)",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const o=e>1;return r.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:r.jsx(vn,{node:n,canClose:o})})}const vn=a.memo(function({node:e,canClose:t}){return e.type==="leaf"?r.jsx(ko,{terminalId:e.terminalId,canClose:t}):r.jsx(Co,{node:e,canClose:t})}),ko=a.memo(function({terminalId:e,canClose:t}){const o=M(l=>l.terminalsMap[e]),s=M(l=>l.reconnectTerminal);return o?r.jsx(yn,{inline:!0,children:r.jsx(vo,{terminal:o,canClose:t})}):r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:r.jsxs("button",{onClick:()=>s(e),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",e]})})}),Co=a.memo(function({node:e,canClose:t}){const o=M(c=>c.setSplitSizes),s=a.useRef(null),l=e.direction==="horizontal",i=a.useRef(e.sizes);i.current=e.sizes;const d=a.useCallback((c,h)=>{h.preventDefault();const p=l?"resizing-panes":"resizing-panes-v";document.body.classList.add(p);const m=l?h.clientX:h.clientY,x=[...i.current],C=s.current,z=l?(C==null?void 0:C.clientWidth)||1:(C==null?void 0:C.clientHeight)||1;let N=null;const E=A=>{N||(N=requestAnimationFrame(()=>{N=null;const L=((l?A.clientX:A.clientY)-m)/z*100,B=x[c]+L,W=x[c+1]-L;if(B>=Gt&&W>=Gt){const O=[...x];O[c]=B,O[c+1]=W,o(e.id,O)}}))},v=()=>{N&&cancelAnimationFrame(N),document.body.classList.remove(p),document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",E),document.addEventListener("mouseup",v)},[l,e.id,o]),u=[];return e.children.forEach((c,h)=>{const p=c.type==="leaf"?c.terminalId:c.id;u.push(r.jsx("div",{style:{flex:`${e.sizes[h]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:r.jsx(vn,{node:c,canClose:t})},p)),h<e.children.length-1&&u.push(r.jsx("div",{onMouseDown:m=>d(h,m),style:{flex:`0 0 ${wo}px`,cursor:l?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${h}`))}),r.jsx("div",{ref:s,style:{display:"flex",flexDirection:l?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:u})});function To({tabId:n}){const e=M(w=>w.tabs.find(S=>S.id===n)),t=M(w=>w.activeTabId),o=M(w=>w.switchTab),s=M(w=>w.closeTab),l=M(w=>w.reopenTab),i=M(w=>w.deleteTab),d=M(w=>w.renameTab),u=M(w=>e?e.terminalIds.map(S=>{const G=w.terminalsMap[S];return G?{id:S,connected:G.connected,active:!0}:{id:S,connected:!1,active:!1}}):[]),c=M(w=>w.disconnectTerminal),h=M(w=>w.reconnectTerminal),p=M(w=>w.killServerSession),[m,x]=a.useState(!1),[C,z]=a.useState(""),[N,E]=a.useState(!1),v=a.useRef(null);if(!e)return null;const A=t===n,I=e.status==="open",U=()=>{I&&o(n)},L=w=>{I&&(w.stopPropagation(),z(e.name),x(!0),setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},0))},B=()=>{const w=C.trim();w&&d(n,w),x(!1)},W=w=>{w.stopPropagation(),l(n)},O=w=>{w.stopPropagation(),s(n)},V=async w=>{w.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await i(n)},T=w=>{w.stopPropagation(),E(!N)};return r.jsxs("div",{children:[r.jsxs("div",{onClick:U,style:{padding:"8px 12px",cursor:I?"pointer":"default",borderLeft:A?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:A?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:I?1:.5},onMouseEnter:w=>{I&&!A&&(w.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:w=>{A||(w.currentTarget.style.backgroundColor="transparent")},children:[I&&e.terminalIds.length>0&&r.jsx("button",{onClick:T,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:N?"▼":"▶"}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[m?r.jsx("input",{ref:v,value:C,onChange:w=>z(w.target.value),onBlur:B,onKeyDown:w=>{w.key==="Enter"&&B(),w.key==="Escape"&&x(!1)},style:{width:"100%",background:"var(--bg-primary)",border:"1px solid var(--accent-blue)",color:"var(--text-bright)",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):r.jsx("div",{onDoubleClick:L,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I?"Double-click to rename":e.name,children:e.name}),r.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",xn(Math.floor(e.createdAt/1e3))]})]}),I?r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:O,style:{flexShrink:0},title:"Close tab",children:"×"}):r.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[r.jsx("button",{className:"pane-btn",onClick:W,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:V,title:"Delete tab",children:"×"})]})]}),I&&N&&u.length>0&&r.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:u.map(w=>r.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${w.connected}`,children:[r.jsx("span",{style:{fontFamily:"monospace"},children:w.id}),r.jsx("span",{style:{marginLeft:"8px",color:w.active?w.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:w.active?w.connected?"●":"◐":"○"}),w.active?r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),c(w.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):r.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[r.jsx("button",{className:"pane-btn",onClick:S=>{S.stopPropagation(),h(w.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),window.confirm(`Kill terminal "${w.id}"? This will destroy the tmux session.`)&&p(w.id)},title:"Kill session",children:"×"})]})]},w.id))})]})}function Eo({sessionId:n,active:e,createdAt:t}){const o=M(d=>d.addTerminal),s=M(d=>d.killServerSession),l=()=>{o("horizontal",n)},i=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${n}"? This will kill the tmux session.`)&&s(n)};return r.jsxs("div",{onClick:l,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent"},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),r.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:xn(t)})]}),r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:i,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function jo(){const n=M(c=>c.sidebarOpen),e=M(c=>c.toggleSidebar),t=M(c=>c.fetchSessions),o=M(c=>n?c.serverSessions:[]),s=M(c=>n?c.tabs:[]),l=M(c=>c.terminalIds.length),i=M(c=>c.tabsLoading),d=new Set(s.flatMap(c=>c.terminalIds)),u=o.filter(c=>!d.has(c.sessionId));return a.useEffect(()=>{if(!n)return;t();let c=setInterval(t,5e3);const h=()=>{document.hidden?c&&(clearInterval(c),c=null):(t(),c||(c=setInterval(t,5e3)))};return document.addEventListener("visibilitychange",h),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",h)}},[n,t]),a.useEffect(()=>{if(!n)return;const c=setTimeout(t,800);return()=>clearTimeout(c)},[l,n,t]),r.jsxs("div",{className:"session-sidebar",style:{width:n?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:n?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[r.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),r.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),r.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),s.length===0?r.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):s.map(c=>r.jsx(To,{tabId:c.id},c.id))]}),!i&&u.length>0&&r.jsxs("div",{style:{marginTop:"16px"},children:[r.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-yellow)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid var(--border)"},children:"ORPHANED SESSIONS"}),u.map(c=>r.jsx(Eo,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const wn=St.memo(()=>{const n=M(I=>I.tabs),e=M(I=>I.activeTabId),t=M(I=>I.addTab),o=M(I=>I.switchTab),s=M(I=>I.closeTab),l=M(I=>I.renameTab),[i,d]=a.useState(null),[u,c]=a.useState(""),h=a.useRef(null),p=n.filter(I=>I.status==="open");a.useEffect(()=>{i&&h.current&&(h.current.focus(),h.current.select())},[i]);const m=I=>{d(I.id),c(I.name)},x=()=>{i&&u.trim()&&l(i,u.trim()),d(null),c("")},C=()=>{d(null),c("")},z=I=>{I.key==="Enter"?x():I.key==="Escape"&&C()},N=I=>{i||o(I)},E=(I,U)=>{I.stopPropagation(),s(U)},v=(I,U)=>{I.button===1&&(I.preventDefault(),s(U))},A=p.length>1;return r.jsxs("div",{className:"tab-bar",children:[p.map(I=>{const U=I.id===e,L=i===I.id,B=I.terminalIds.length;return r.jsx("div",{className:`tab-item ${U?"tab-item--active":""}`,onClick:()=>N(I.id),onDoubleClick:()=>m(I),onMouseDown:W=>v(W,I.id),children:L?r.jsx("input",{ref:h,type:"text",value:u,onChange:W=>c(W.target.value),onBlur:x,onKeyDown:z,className:"tab-item__rename-input"}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"tab-item__name",children:[I.name," ",B>0&&`(${B})`]}),A&&r.jsx("button",{className:"tab-item__close",onClick:W=>E(W,I.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},I.id)}),r.jsx("button",{className:"tab-bar-add",onClick:()=>t(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});wn.displayName="TabBar";function Io(){return localStorage.getItem("ai-cli-online-token")}function Ro(){const n=M(h=>h.token),e=M(h=>h.setToken),t=M(h=>h.tabs),o=M(h=>h.addTab),s=M(h=>h.toggleSidebar),l=M(h=>h.fontSize),i=M(h=>h.setFontSize),d=M(h=>h.tabsLoading),u=M(h=>h.theme),c=M(h=>h.toggleTheme);return a.useEffect(()=>{const h=Io();h&&!n&&e(h)},[]),a.useEffect(()=>{n&&!d&&t.filter(h=>h.status==="open").length===0&&o("Default")},[n,d]),n?r.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[r.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),r.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","2.9.6"]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[r.jsx("button",{className:"header-btn",onClick:()=>i(l-1),disabled:l<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),r.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:l}),r.jsx("button",{className:"header-btn",onClick:()=>i(l+1),disabled:l>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),r.jsx(Do,{}),r.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${u==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:u==="dark"?"☀":"🌙"}),r.jsx("button",{className:"header-btn",onClick:s,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),r.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),r.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[r.jsx("main",{style:{flex:1,overflow:"hidden"},children:r.jsx(So,{})}),r.jsx(jo,{})]}),r.jsx(wn,{})]}):r.jsx(vr,{})}const No=[1,2,3,4];function Do(){const n=M(o=>o.latency);if(n===null)return r.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let e,t;return n<50?(e="var(--accent-green)",t=4):n<150?(e="var(--accent-yellow)",t=3):n<300?(e="var(--accent-orange)",t=2):(e="var(--accent-red)",t=1),r.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${n}ms`,children:[No.map(o=>r.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+o*2}px`,backgroundColor:o<=t?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},o)),r.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[n,"ms"]})]})}gt.createRoot(document.getElementById("root")).render(r.jsx(St.StrictMode,{children:r.jsx(yn,{children:r.jsx(Ro,{})})}));
|
|
32
|
+
`),le=ee.slice(re+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(le)v(!0),I(le[1]),L(0),P(!1);else{v(!1);const de=ee.match(/@([a-zA-Z0-9_.\-/]*)$/);if(de){const ce=de[1],fe=ce.lastIndexOf("/"),Se=fe>=0?ce.slice(0,fe+1):"",_e=fe>=0?ce.slice(fe+1):ce;_(_e),be(0),oe(Se),P(!0)}else P(!1)}},[B]),$e=a.useCallback(g=>{if(E&&me.length>0){if(g.key==="ArrowDown"){g.preventDefault(),L(j=>(j+1)%me.length);return}if(g.key==="ArrowUp"){g.preventDefault(),L(j=>(j-1+me.length)%me.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),Ae(me[U].cmd);return}if(g.key==="Escape"){g.preventDefault(),v(!1);return}}if(z&&Q.length>0){if(g.key==="ArrowDown"){g.preventDefault(),be(j=>(j+1)%Q.length);return}if(g.key==="ArrowUp"){g.preventDefault(),be(j=>(j-1+Q.length)%Q.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),Ke(Q[ne]);return}if(g.key==="Escape"){g.preventDefault(),P(!1);return}}if(B&&q.length>0){if(g.key==="ArrowDown"){g.preventDefault(),w(j=>(j+1)%q.length);return}if(g.key==="ArrowUp"){g.preventDefault(),w(j=>(j-1+q.length)%q.length);return}if(g.key==="Enter"){g.preventDefault(),we(q[T]);return}if(g.key==="Delete"||g.key==="Backspace"&&(g.ctrlKey||g.metaKey)){g.preventDefault(),ge(T);return}if(g.key==="Escape"){g.preventDefault(),W(!1);return}}if(g.key==="Tab"){vt(g,u,x);return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),J())},[J,E,me,U,Ae,z,Q,ne,Ke,x,C,B,q,T,we,ge]);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[E&&me.length>0&&r.jsx("div",{className:"slash-dropdown",children:me.map((g,j)=>r.jsxs("div",{className:`slash-item${j===U?" slash-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ae(g.cmd)},onMouseEnter:()=>L(j),children:[r.jsx("span",{className:"slash-cmd",children:g.cmd}),r.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),z&&(Fe||Q.length>0)&&r.jsx("div",{className:"file-dropdown",ref:Re,children:Fe?r.jsx("div",{className:"file-item file-loading",children:"Loading..."}):Q.map((g,j)=>r.jsxs("div",{className:`file-item${j===ne?" file-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ke(g)},onMouseEnter:()=>be(j),children:[r.jsx("span",{className:"file-icon",children:g.type==="directory"?"📁":"📄"}),r.jsx("span",{className:"file-name",children:g.name})]},g.name))}),B&&r.jsx("div",{className:"history-dropdown",ref:Y,children:q.length===0?r.jsx("div",{className:"history-item history-empty",children:"No history yet"}):q.map((g,j)=>r.jsxs("div",{className:`history-item${j===T?" history-item--active":""}`,onMouseDown:K=>{K.preventDefault(),we(g)},onMouseEnter:()=>w(j),children:[r.jsx("span",{className:"history-text",children:g.text.length>120?g.text.slice(0,120)+"...":g.text}),r.jsx("span",{className:"history-time",children:new Date(g.ts).toLocaleString()}),r.jsx("button",{className:"history-delete",onMouseDown:K=>{K.preventDefault(),K.stopPropagation(),ge(j)},title:"Delete (Del key)",children:"×"})]},`${g.ts}-${j}`))}),r.jsx("textarea",{ref:c,className:"md-editor-textarea",value:d,onChange:Je,onKeyDown:$e,onMouseUp:Ee,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${i}px`}})]})}),go=600,Ue=typeof window<"u"?window.matchMedia(`(max-width: ${go-1}px)`):null;function yo(){const[n,e]=a.useState(()=>(Ue==null?void 0:Ue.matches)??!1);return a.useEffect(()=>{if(!Ue)return;const t=o=>e(o.matches);return Ue.addEventListener("change",t),()=>Ue.removeEventListener("change",t)},[]),n}const vo=a.memo(function({terminal:e}){const t=yo(),o=M(D=>D.splitTerminal),s=M(D=>D.token),l=M(D=>D.toggleChat),i=M(D=>D.togglePlan),{chatOpen:d,planOpen:u}=e.panels,c=a.useCallback(async D=>{let F;if(s)try{F=await so(s,e.id)}catch{}o(e.id,D,F)},[s,e.id,o]),h=a.useRef(null),p=a.useRef(null),m=a.useRef(null),[x,C]=a.useState(!1),[$,N]=a.useState(0),[E,v]=a.useState(!1),[A,I]=a.useState(!1),[U,L]=a.useState(!1),[B,W]=a.useState([]),[O,V]=a.useState(""),[T,w]=a.useState([]),[S,G]=a.useState(!1),Y=a.useRef(null),q=a.useRef(null),z=a.useRef(null),[P,X]=a.useState(()=>{const D=localStorage.getItem(`plan-width-${e.id}`);if(D){const F=Number(D);if(Number.isFinite(F)&&F>=20&&F<=80)return F}return 50}),_=a.useRef(P);if(P!==_.current){_.current=P;try{localStorage.setItem(`plan-width-${e.id}`,String(Math.round(P)))}catch{}}const[H,oe]=a.useState(()=>{const D=localStorage.getItem(`doc-height-${e.id}`);if(D){const F=Number(D);if(Number.isFinite(F)&&F>=15&&F<=60)return F}return 35}),ne=a.useRef(H);if(H!==ne.current){ne.current=H;try{localStorage.setItem(`doc-height-${e.id}`,String(Math.round(H)))}catch{}}const be=async D=>{const F=D.target.files;if(!(!F||F.length===0||!s)){C(!0),N(0);try{await oo(s,e.id,F,J=>{N(J)})}catch(J){alert(`Upload failed: ${J instanceof Error?J.message:"Unknown error"}`)}finally{C(!1),N(0),h.current&&(h.current.value="")}}},Ce=a.useRef(void 0),Te=a.useCallback(D=>{if(p.current){const F=D.replace(/\r?\n/g," ").trimEnd();p.current.sendInput(F),Ce.current=window.setTimeout(()=>{var J;return(J=p.current)==null?void 0:J.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{Ce.current&&clearTimeout(Ce.current)},[]);const Fe=a.useCallback(async()=>{if(s){G(!0),L(!0);try{const D=await ke(s,e.id);V(D.cwd),W(D.files),w([])}catch{L(!1)}finally{G(!1)}}},[s,e.id]),ve=a.useCallback(async D=>{if(s){G(!0);try{const F=await ke(s,e.id,D);w(J=>[...J,O]),V(D),W(F.files)}catch{}finally{G(!1)}}},[s,e.id,O]),xe=a.useCallback(async()=>{if(!s||T.length===0)return;const D=T[T.length-1];G(!0);try{const F=await ke(s,e.id,D);w(J=>J.slice(0,-1)),V(D),W(F.files)}catch{}finally{G(!1)}},[s,e.id,T]),Re=a.useCallback(async D=>{if(s)try{await lo(s,e.id,D)}catch(F){alert(`Download failed: ${F instanceof Error?F.message:"Unknown error"}`)}},[s,e.id]);a.useEffect(()=>{if(!U)return;const D=ae=>{ae.key==="Escape"&&L(!1)},F=ae=>{Y.current&&!Y.current.contains(ae.target)&&L(!1)};document.addEventListener("keydown",D);const J=setTimeout(()=>document.addEventListener("mousedown",F),50);return()=>{document.removeEventListener("keydown",D),document.removeEventListener("mousedown",F),clearTimeout(J)}},[U]);const me=a.useCallback(D=>{if(p.current){const F=D.replace(/\r?\n/g," ").trimEnd();p.current.sendInput(F),setTimeout(()=>{var J;return(J=p.current)==null?void 0:J.sendInput("\r")},50)}},[]),Q=a.useCallback(D=>{D&&m.current&&m.current.fillContent(D)},[]),Me=a.useCallback(D=>{D.preventDefault();const F=q.current;if(!F)return;const J=F.getBoundingClientRect(),ae=J.height-24;document.body.classList.add("resizing-panes-v");const te=Ne=>{const ge=(Ne.clientY-J.top-24)/ae*100,Ae=Math.min(85,Math.max(40,ge));oe(100-Ae)},Ee=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",Ee)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",Ee)},[]),he=a.useCallback(D=>{D.preventDefault();const F=z.current;if(!F)return;const J=F.getBoundingClientRect(),ae=J.width;document.body.classList.add("resizing-panes");const te=Ne=>{const we=(Ne.clientX-J.left)/ae*100,ge=Math.min(80,Math.max(20,we));X(ge)},Ee=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",Ee)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",Ee)},[]);return r.jsxs("div",{ref:q,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[r.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)"}}),r.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)"},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx("input",{ref:h,type:"file",multiple:!0,style:{display:"none"},onChange:be}),r.jsx("button",{className:"pane-btn",onClick:()=>{var D;return(D=h.current)==null?void 0:D.click()},disabled:x,style:x?{color:"var(--accent-yellow)"}:void 0,title:x?`Uploading ${$}%`:"Upload files","aria-label":"Upload files",children:x?`${$}%`:"↑"}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx("button",{className:"pane-btn",onClick:Fe,disabled:E,style:E?{color:"var(--accent-yellow)"}:void 0,title:E?"Downloading...":"Download files","aria-label":"Download files",children:E?"...":"↓"}),U&&r.jsxs("div",{ref:Y,style:{position:"absolute",top:"100%",right:0,marginTop:4,width:300,maxHeight:360,backgroundColor:"var(--bg-primary)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:100,display:"flex",flexDirection:"column",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[T.length>0&&r.jsx("button",{className:"pane-btn",onClick:xe,disabled:S,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),r.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:O.split("/").slice(-2).join("/")||O}),r.jsx("button",{className:"pane-btn",onClick:()=>L(!1),style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),r.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:S?r.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):B.length===0?r.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):B.map(D=>r.jsxs("div",{onClick:()=>{const F=O+"/"+D.name;D.type==="directory"?ve(F):Re(F)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:F=>{F.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:F=>{F.currentTarget.style.backgroundColor="transparent"},children:[r.jsx("span",{style:{flexShrink:0,fontSize:13},children:D.type==="directory"?"📁":co(D.name,D.type)}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.name}),D.type==="directory"?r.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):D.size!=null?r.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:bn(D.size)}):null]},D.name))}),r.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:r.jsx("button",{className:"pane-btn",onClick:async()=>{v(!0),L(!1);try{await io(s||"",e.id)}catch(D){alert(`Download failed: ${D instanceof Error?D.message:"Unknown error"}`)}finally{v(!1)}},style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:"Download All (tar.gz)"})})]})]}),r.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),r.jsx("button",{className:`pane-btn${u?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),r.jsx("button",{className:"pane-btn",onClick:()=>c(t?"vertical":"horizontal"),title:t?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),r.jsx("button",{className:"pane-btn",onClick:()=>c("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),r.jsxs("div",{ref:z,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{width:`${P}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:r.jsx(mo,{sessionId:e.id,token:s||"",connected:e.connected,onRequestFileStream:D=>{var F;return(F=p.current)==null?void 0:F.requestFileStream(D)},onCancelFileStream:()=>{var D;return(D=p.current)==null?void 0:D.cancelFileStream()},onForwardToChat:Q,onSendToTerminal:me})}),r.jsx("div",{className:"md-editor-divider-h",onMouseDown:he,style:{width:"2px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:D=>{D.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:D=>{D.currentTarget.style.backgroundColor="var(--border)"}})]}),r.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[r.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[r.jsx(Fr,{ref:p,sessionId:e.id}),!e.connected&&r.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"md-editor-divider",onMouseDown:Me}),r.jsxs("div",{style:{height:`${H}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",height:"22px",flexShrink:0,backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),r.jsx("button",{className:"pane-btn",onClick:()=>{var D;return(D=m.current)==null?void 0:D.send()},disabled:!A,title:"Send to terminal (Ctrl+Enter)",style:A?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),r.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),r.jsx("div",{style:{flex:1,overflow:"hidden"},children:r.jsx(xo,{ref:m,onSend:Te,onContentChange:I,sessionId:e.id,token:s||""})})]})]})]})]}),e.error&&r.jsx("div",{style:{padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--accent-red)",color:"var(--accent-red)",fontSize:"11px",flexShrink:0},children:e.error})]})});class yn extends a.Component{constructor(){super(...arguments);Nt(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,o){}render(){var t,o;return this.state.hasError?this.props.inline?r.jsxs("div",{style:{height:"100%",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"var(--text-bright)",fontFamily:"monospace",padding:"16px"},children:[r.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),r.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textAlign:"center"},children:((t=this.state.error)==null?void 0:t.message)||"An unexpected error occurred"}),r.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-bright)",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):r.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"var(--text-bright)",fontFamily:"monospace"},children:[r.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),r.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((o=this.state.error)==null?void 0:o.message)||"An unexpected error occurred"}),r.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",border:"none",color:"var(--bg-primary)",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const wo=4,Gt=10;function So(){const n=M(s=>s.layout),e=M(s=>s.terminalIds.length),t=M(s=>s.addTerminal);if(!n)return r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:r.jsx("button",{onClick:()=>t(),style:{background:"none",border:"1px dashed var(--border)",color:"var(--text-secondary)",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const o=e>1;return r.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:r.jsx(vn,{node:n,canClose:o})})}const vn=a.memo(function({node:e,canClose:t}){return e.type==="leaf"?r.jsx(ko,{terminalId:e.terminalId,canClose:t}):r.jsx(Co,{node:e,canClose:t})}),ko=a.memo(function({terminalId:e,canClose:t}){const o=M(l=>l.terminalsMap[e]),s=M(l=>l.reconnectTerminal);return o?r.jsx(yn,{inline:!0,children:r.jsx(vo,{terminal:o,canClose:t})}):r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:r.jsxs("button",{onClick:()=>s(e),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",e]})})}),Co=a.memo(function({node:e,canClose:t}){const o=M(c=>c.setSplitSizes),s=a.useRef(null),l=e.direction==="horizontal",i=a.useRef(e.sizes);i.current=e.sizes;const d=a.useCallback((c,h)=>{h.preventDefault();const p=l?"resizing-panes":"resizing-panes-v";document.body.classList.add(p);const m=l?h.clientX:h.clientY,x=[...i.current],C=s.current,$=l?(C==null?void 0:C.clientWidth)||1:(C==null?void 0:C.clientHeight)||1;let N=null;const E=A=>{N||(N=requestAnimationFrame(()=>{N=null;const L=((l?A.clientX:A.clientY)-m)/$*100,B=x[c]+L,W=x[c+1]-L;if(B>=Gt&&W>=Gt){const O=[...x];O[c]=B,O[c+1]=W,o(e.id,O)}}))},v=()=>{N&&cancelAnimationFrame(N),document.body.classList.remove(p),document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",E),document.addEventListener("mouseup",v)},[l,e.id,o]),u=[];return e.children.forEach((c,h)=>{const p=c.type==="leaf"?c.terminalId:c.id;u.push(r.jsx("div",{style:{flex:`${e.sizes[h]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:r.jsx(vn,{node:c,canClose:t})},p)),h<e.children.length-1&&u.push(r.jsx("div",{onMouseDown:m=>d(h,m),style:{flex:`0 0 ${wo}px`,cursor:l?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${h}`))}),r.jsx("div",{ref:s,style:{display:"flex",flexDirection:l?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:u})});function To({tabId:n}){const e=M(w=>w.tabs.find(S=>S.id===n)),t=M(w=>w.activeTabId),o=M(w=>w.switchTab),s=M(w=>w.closeTab),l=M(w=>w.reopenTab),i=M(w=>w.deleteTab),d=M(w=>w.renameTab),u=M(w=>e?e.terminalIds.map(S=>{const G=w.terminalsMap[S];return G?{id:S,connected:G.connected,active:!0}:{id:S,connected:!1,active:!1}}):[]),c=M(w=>w.disconnectTerminal),h=M(w=>w.reconnectTerminal),p=M(w=>w.killServerSession),[m,x]=a.useState(!1),[C,$]=a.useState(""),[N,E]=a.useState(!1),v=a.useRef(null);if(!e)return null;const A=t===n,I=e.status==="open",U=()=>{I&&o(n)},L=w=>{I&&(w.stopPropagation(),$(e.name),x(!0),setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},0))},B=()=>{const w=C.trim();w&&d(n,w),x(!1)},W=w=>{w.stopPropagation(),l(n)},O=w=>{w.stopPropagation(),s(n)},V=async w=>{w.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await i(n)},T=w=>{w.stopPropagation(),E(!N)};return r.jsxs("div",{children:[r.jsxs("div",{onClick:U,style:{padding:"8px 12px",cursor:I?"pointer":"default",borderLeft:A?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:A?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:I?1:.5},onMouseEnter:w=>{I&&!A&&(w.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:w=>{A||(w.currentTarget.style.backgroundColor="transparent")},children:[I&&e.terminalIds.length>0&&r.jsx("button",{onClick:T,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:N?"▼":"▶"}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[m?r.jsx("input",{ref:v,value:C,onChange:w=>$(w.target.value),onBlur:B,onKeyDown:w=>{w.key==="Enter"&&B(),w.key==="Escape"&&x(!1)},style:{width:"100%",background:"var(--bg-primary)",border:"1px solid var(--accent-blue)",color:"var(--text-bright)",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):r.jsx("div",{onDoubleClick:L,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I?"Double-click to rename":e.name,children:e.name}),r.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",xn(Math.floor(e.createdAt/1e3))]})]}),I?r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:O,style:{flexShrink:0},title:"Close tab",children:"×"}):r.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[r.jsx("button",{className:"pane-btn",onClick:W,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:V,title:"Delete tab",children:"×"})]})]}),I&&N&&u.length>0&&r.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:u.map(w=>r.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${w.connected}`,children:[r.jsx("span",{style:{fontFamily:"monospace"},children:w.id}),r.jsx("span",{style:{marginLeft:"8px",color:w.active?w.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:w.active?w.connected?"●":"◐":"○"}),w.active?r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),c(w.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):r.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[r.jsx("button",{className:"pane-btn",onClick:S=>{S.stopPropagation(),h(w.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),window.confirm(`Kill terminal "${w.id}"? This will destroy the tmux session.`)&&p(w.id)},title:"Kill session",children:"×"})]})]},w.id))})]})}function Eo({sessionId:n,active:e,createdAt:t}){const o=M(d=>d.addTerminal),s=M(d=>d.killServerSession),l=()=>{o("horizontal",n)},i=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${n}"? This will kill the tmux session.`)&&s(n)};return r.jsxs("div",{onClick:l,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent"},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),r.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:xn(t)})]}),r.jsx("button",{className:"pane-btn pane-btn--danger",onClick:i,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function jo(){const n=M(c=>c.sidebarOpen),e=M(c=>c.toggleSidebar),t=M(c=>c.fetchSessions),o=M(c=>n?c.serverSessions:[]),s=M(c=>n?c.tabs:[]),l=M(c=>c.terminalIds.length),i=M(c=>c.tabsLoading),d=new Set(s.flatMap(c=>c.terminalIds)),u=o.filter(c=>!d.has(c.sessionId));return a.useEffect(()=>{if(!n)return;t();let c=setInterval(t,5e3);const h=()=>{document.hidden?c&&(clearInterval(c),c=null):(t(),c||(c=setInterval(t,5e3)))};return document.addEventListener("visibilitychange",h),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",h)}},[n,t]),a.useEffect(()=>{if(!n)return;const c=setTimeout(t,800);return()=>clearTimeout(c)},[l,n,t]),r.jsxs("div",{className:"session-sidebar",style:{width:n?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:n?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[r.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),r.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),r.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),s.length===0?r.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):s.map(c=>r.jsx(To,{tabId:c.id},c.id))]}),!i&&u.length>0&&r.jsxs("div",{style:{marginTop:"16px"},children:[r.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-yellow)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid var(--border)"},children:"ORPHANED SESSIONS"}),u.map(c=>r.jsx(Eo,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const wn=St.memo(()=>{const n=M(I=>I.tabs),e=M(I=>I.activeTabId),t=M(I=>I.addTab),o=M(I=>I.switchTab),s=M(I=>I.closeTab),l=M(I=>I.renameTab),[i,d]=a.useState(null),[u,c]=a.useState(""),h=a.useRef(null),p=n.filter(I=>I.status==="open");a.useEffect(()=>{i&&h.current&&(h.current.focus(),h.current.select())},[i]);const m=I=>{d(I.id),c(I.name)},x=()=>{i&&u.trim()&&l(i,u.trim()),d(null),c("")},C=()=>{d(null),c("")},$=I=>{I.key==="Enter"?x():I.key==="Escape"&&C()},N=I=>{i||o(I)},E=(I,U)=>{I.stopPropagation(),s(U)},v=(I,U)=>{I.button===1&&(I.preventDefault(),s(U))},A=p.length>1;return r.jsxs("div",{className:"tab-bar",children:[p.map(I=>{const U=I.id===e,L=i===I.id,B=I.terminalIds.length;return r.jsx("div",{className:`tab-item ${U?"tab-item--active":""}`,onClick:()=>N(I.id),onDoubleClick:()=>m(I),onMouseDown:W=>v(W,I.id),children:L?r.jsx("input",{ref:h,type:"text",value:u,onChange:W=>c(W.target.value),onBlur:x,onKeyDown:$,className:"tab-item__rename-input"}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"tab-item__name",children:[I.name," ",B>0&&`(${B})`]}),A&&r.jsx("button",{className:"tab-item__close",onClick:W=>E(W,I.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},I.id)}),r.jsx("button",{className:"tab-bar-add",onClick:()=>t(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});wn.displayName="TabBar";function Io(){return localStorage.getItem("ai-cli-online-token")}function Ro(){const n=M(h=>h.token),e=M(h=>h.setToken),t=M(h=>h.tabs),o=M(h=>h.addTab),s=M(h=>h.toggleSidebar),l=M(h=>h.fontSize),i=M(h=>h.setFontSize),d=M(h=>h.tabsLoading),u=M(h=>h.theme),c=M(h=>h.toggleTheme);return a.useEffect(()=>{const h=Io();h&&!n&&e(h)},[]),a.useEffect(()=>{n&&!d&&t.filter(h=>h.status==="open").length===0&&o("Default")},[n,d]),n?r.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[r.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),r.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","2.9.6"]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[r.jsx("button",{className:"header-btn",onClick:()=>i(l-1),disabled:l<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),r.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:l}),r.jsx("button",{className:"header-btn",onClick:()=>i(l+1),disabled:l>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),r.jsx(Do,{}),r.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${u==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:u==="dark"?"☀":"🌙"}),r.jsx("button",{className:"header-btn",onClick:s,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),r.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),r.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[r.jsx("main",{style:{flex:1,overflow:"hidden"},children:r.jsx(So,{})}),r.jsx(jo,{})]}),r.jsx(wn,{})]}):r.jsx(vr,{})}const No=[1,2,3,4];function Do(){const n=M(o=>o.latency);if(n===null)return r.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let e,t;return n<50?(e="var(--accent-green)",t=4):n<150?(e="var(--accent-yellow)",t=3):n<300?(e="var(--accent-orange)",t=2):(e="var(--accent-red)",t=1),r.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${n}ms`,children:[No.map(o=>r.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+o*2}px`,backgroundColor:o<=t?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},o)),r.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[n,"ms"]})]})}gt.createRoot(document.getElementById("root")).render(r.jsx(St.StrictMode,{children:r.jsx(yn,{children:r.jsx(Ro,{})})}));
|
package/web/dist/index.html
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<!-- LXGW WenKai Mono (中文等宽字体, CDN unicode-range 按需加载) -->
|
|
11
11
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkaimono-regular.css" />
|
|
12
12
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkaimono-bold.css" />
|
|
13
|
-
<script type="module" crossorigin src="/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/assets/index-Ct6rfAt5.js"></script>
|
|
14
14
|
<link rel="modulepreload" crossorigin href="/assets/react-vendor-BCIvbQoU.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/terminal-DnNpv9tw.js">
|
|
16
16
|
<link rel="modulepreload" crossorigin href="/assets/markdown-CU76q5qk.js">
|