ai-cli-online 3.0.16 → 3.0.17
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
package/server/package.json
CHANGED
package/shared/package.json
CHANGED
|
@@ -22,12 +22,12 @@ var Zn=Object.defineProperty;var Qn=(n,e,t)=>e in n?Zn(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 gt=a,wr=vr;function Sr(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var kr=typeof Object.is=="function"?Object.is:Sr,Cr=wr.useSyncExternalStore,Tr=gt.useRef,Er=gt.useEffect,jr=gt.useMemo,Ir=gt.useDebugValue;Rn.useSyncExternalStoreWithSelector=function(n,e,t,r,o){var i=Tr(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=jr(function(){function p(m){if(!c){if(c=!0,d=m,m=r(m),o!==void 0&&l.hasValue){var x=l.value;if(o(x,m))return f=x}return f=m}if(x=f,kr(d,m))return x;var T=r(m);return o!==void 0&&o(x,T)?(d=m,x):(d=m,f=T)}var c=!1,d,f,h=t===void 0?null:t;return[function(){return p(e())},h===null?void 0:function(){return p(h())}]},[e,t,r,o]);var u=Cr(n,i[0],i[1]);return Er(function(){l.hasValue=!0,l.value=u},[u]),Ir(u),u};In.exports=Rn;var Rr=In.exports;const Lr=tr(Rr),Nn={},{useDebugValue:Mr}=$t,{useSyncExternalStoreWithSelector:Nr}=Lr;let Gt=!1;const Dr=n=>n;function Ar(n,e=Dr,t){(Nn?"production":void 0)!=="production"&&t&&!Gt&&(Gt=!0);const r=Nr(n.subscribe,n.getState,n.getServerState||n.getInitialState,e,t);return Mr(r),r}const Jt=n=>{const e=typeof n=="function"?dr(n):n,t=(r,o)=>Ar(e,r,o);return Object.assign(t,e),t},$r=n=>n?Jt(n):Jt,$e="";function ve(n){return{Authorization:`Bearer ${n}`}}class Xe extends Error{constructor(e,t){super(t),this.status=e,this.name="ApiError"}}function Oe(n,e){return`${$e}/api/sessions/${encodeURIComponent(n)}/${e}`}function Vt(n){return`${$e}/api/settings/${n}`}async function Ye(n){if(!n.ok){const e=await n.text().catch(()=>n.statusText);throw new Xe(n.status,e)}return n.json()}const pe={async get(n,e,t,r){const o=new URL(Oe(e,t),window.location.origin);if(r)for(const[l,u]of Object.entries(r))o.searchParams.set(l,u);const i=await fetch(o.toString(),{headers:ve(n)});return Ye(i)},async getOptional(n,e,t,r){const o=new URL(Oe(e,t),window.location.origin);if(r)for(const[l,u]of Object.entries(r))o.searchParams.set(l,u);const i=await fetch(o.toString(),{headers:ve(n)});return i.status===304?null:Ye(i)},async post(n,e,t,r){const o=await fetch(Oe(e,t),{method:"POST",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(r)});return Ye(o)},async put(n,e,t,r){const o=await fetch(Oe(e,t),{method:"PUT",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const i=await o.text().catch(()=>o.statusText);throw new Xe(o.status,i)}},async putJson(n,e,t,r){const o=await fetch(Oe(e,t),{method:"PUT",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(r)});return Ye(o)},async del(n,e,t,r){const o=await fetch(Oe(e,t),{method:"DELETE",headers:{...ve(n),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!o.ok){const i=await o.text().catch(()=>o.statusText);throw new Xe(o.status,i)}},async getBlob(n,e,t,r){const o=new URL(Oe(e,t),window.location.origin);if(r)for(const[l,u]of Object.entries(r))o.searchParams.set(l,u);const i=await fetch(o.toString(),{headers:ve(n)});if(!i.ok)throw new Xe(i.status,"Download failed");return i}},xt={async get(n,e){const t=await fetch(Vt(e),{headers:ve(n)});return Ye(t)},async put(n,e,t){const r=await fetch(Vt(e),{method:"PUT",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.text().catch(()=>r.statusText);throw new Xe(r.status,o)}}};async function zr(n){try{return(await xt.get(n,"font-size")).fontSize}catch{return 14}}async function _r(n,e){try{await xt.put(n,"font-size",{fontSize:e})}catch{}}let nt=null;const Or=(n,e)=>({fontSize:14,setFontSize:t=>{const r=Math.max(10,Math.min(24,t));n({fontSize:r}),nt&&clearTimeout(nt),nt=setTimeout(()=>{nt=null;const o=e().token;o&&_r(o,r)},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 r=await fetch(`${$e}/api/sessions`,{headers:ve(t)});if(!r.ok)return;const o=await r.json();n({serverSessions:o})}catch{}}});function Tt(n,e){return(t,r,o)=>{const i=r(),l=i.terminalsMap[t];if(!l)return;const u=!l.panels[n],p={...l.panels,[n]:u,...u&&e?{[e]:!1}:{}},c={...i.terminalsMap,[t]:{...l,panels:p}},d=i.tabs.find(h=>h.terminalIds.includes(t));let f=i.tabs;if(d){const h={...d.panelStates,[t]:p};f=De(i.tabs,d.id,m=>({...m,panelStates:h}))}o({terminalsMap:c,tabs:f})}}function lt(n,e){if(n.type==="leaf")return n.terminalId===e?null:n;const t=[],r=[];for(let l=0;l<n.children.length;l++){const u=lt(n.children[l],e);u!==null&&(t.push(u),r.push(n.sizes[l]))}if(t.length===0)return null;if(t.length===1)return t[0];const o=r.reduce((l,u)=>l+u,0),i=r.map(l=>l/o*100);return{...n,children:t,sizes:i}}function Dn(n,e,t,r,o){return n.type==="leaf"?n.terminalId===e?{id:o,type:"split",direction:t,children:[n,r],sizes:[50,50]}:n:{...n,children:n.children.map(i=>Dn(i,e,t,r,o))}}function An(n,e,t){return n.type==="leaf"?n:n.id===e?{...n,sizes:t}:{...n,children:n.children.map(r=>An(r,e,t))}}function Et(n){return n.tabs.find(e=>e.id===n.activeTabId)}function De(n,e,t){return n.map(r=>r.id===e?t(r):r)}function qt(n,e){const t=n.tabs.find(c=>c.terminalIds.includes(e));if(!t){const{[e]:c,...d}=n.terminalsMap;return{terminalsMap:d}}const r=t.terminalIds.filter(c=>c!==e),o=t.layout?lt(t.layout,e):null,i=De(n.tabs,t.id,c=>({...c,terminalIds:r,layout:o})),{[e]:l,...u}=n.terminalsMap,p={terminalsMap:u,tabs:i};return t.id===n.activeTabId&&(p.terminalIds=r,p.layout=o),p}async function Fr(n){try{return(await xt.get(n,"tabs-layout")).layout}catch{return null}}async function Br(n,e){try{await xt.put(n,"tabs-layout",{layout:e})}catch{}}function Yt(n,e){try{const t=`${$e}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:n});navigator.sendBeacon(t,new Blob([r],{type:"application/json"}))}catch{}}const Mt="ai-cli-online-tabs",Xt="ai-cli-online-layout",Zt="ai-cli-online-session-names";let Ee=null;function Pr(n){Ee=n,Jr()}let rt=null,Fe=null,Ze=null;function Wr(n){Ze=n,Fe&&clearTimeout(Fe),Fe=setTimeout(()=>{Fe=null,Ze=null;const e=Ee==null?void 0:Ee.getState().token;e&&Br(e,n)},2e3)}function he(n){const e={version:2,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId,tabs:n.tabs};try{localStorage.setItem(Mt,JSON.stringify(e))}catch{}Wr(e)}function Hr(n){rt&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,he(n)},500)}function fe(n){return{tabs:n.tabs,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId}}function Ur(){try{const n=localStorage.getItem(Mt);if(n){const e=JSON.parse(n);if(e.version===2)return e}}catch{}try{const n=localStorage.getItem(Xt);if(n){const e=JSON.parse(n);let t="Default";try{const i=localStorage.getItem(Zt);if(i){const l=JSON.parse(i),u=Object.values(l)[0];u&&(t=u)}}catch{}const r={id:"tab1",name:t,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Mt,JSON.stringify(o))}catch{}return localStorage.removeItem(Xt),localStorage.removeItem(Zt),o}}catch{}return null}function Kr(n,e){const t=new Set(e.map(l=>l.sessionId)),r=[];for(const l of n.tabs){if(l.status!=="open"){const c=l.terminalIds.filter(d=>t.has(d));if(c.length>0){let d=l.layout;for(const f of l.terminalIds)!t.has(f)&&d&&(d=lt(d,f));r.push({...l,terminalIds:c,layout:d})}continue}const u=l.terminalIds.filter(c=>t.has(c));if(u.length===0)continue;let p=l.layout;for(const c of l.terminalIds)!t.has(c)&&p&&(p=lt(p,c));r.push({...l,terminalIds:u,layout:p})}if(r.filter(l=>l.status==="open").length===0)return null;let o=n.activeTabId;if(!r.find(l=>l.id===o&&l.status==="open")){const l=r.find(u=>u.status==="open");o=(l==null?void 0:l.id)||""}return{...n,activeTabId:o,tabs:r}}async function Gr(n,e){var o,i;if(!Ee)return;const{setState:t,getState:r}=Ee;try{const[l,u]=await Promise.all([Fr(n),fetch(`${$e}/api/sessions`,{headers:ve(n)}).then(x=>x.ok?x.json():[]).catch(()=>[])]);if(r().token!==n)return;const p=l&&((o=l.tabs)==null?void 0:o.length)>0?l:e;if(!p||p.tabs.length===0){t({tabsLoading:!1});return}const c=Kr(p,u);if(!c){t({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:p.nextId,nextSplitId:p.nextSplitId,nextTabId:p.nextTabId,terminalIds:[],layout:null});return}const d=r().terminalsMap,f={};for(const x of c.tabs)if(x.status==="open")for(const T of x.terminalIds)f[T]=d[T]||{id:T,connected:!1,sessionResumed:!1,error:null,panels:((i=x.panelStates)==null?void 0:i[T])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const h=c.tabs.find(x=>x.id===c.activeTabId&&x.status==="open")||c.tabs.find(x=>x.status==="open"),m=(h==null?void 0:h.id)||"";t({tabsLoading:!1,terminalsMap:f,tabs:c.tabs,activeTabId:m,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(h==null?void 0:h.terminalIds)||[],layout:(h==null?void 0:h.layout)||null}),he(fe(r()))}catch{r().token===n&&t({tabsLoading:!1})}}function Jr(){typeof window>"u"||!Ee||window.addEventListener("beforeunload",()=>{const n=Ee==null?void 0:Ee.getState().token;if(n)if(Ze)Fe&&(clearTimeout(Fe),Fe=null),Yt(n,Ze),Ze=null;else{const e=Ee.getState();e.tabs.length>0&&Yt(n,fe(e))}})}const $=$r((...n)=>{const[e,t]=n;return{...Or(...n),token:null,tabsLoading:!1,setToken:r=>{var o;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}zr(r).then(l=>{t().token===r&&e({fontSize:l})});const i=Ur();if(i&&i.tabs.length>0){const l={};for(const c of i.tabs)if(c.status==="open")for(const d of c.terminalIds)l[d]={id:d,connected:!1,sessionResumed:!1,error:null,panels:((o=c.panelStates)==null?void 0:o[d])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const u=i.tabs.find(c=>c.id===i.activeTabId&&c.status==="open")||i.tabs.find(c=>c.status==="open"),p=(u==null?void 0:u.id)||"";e({token:r,tabsLoading:!0,terminalsMap:l,tabs:i.tabs,activeTabId:p,nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null})}else e({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Gr(r,i);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),e({token:r,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:r=>{const o=t(),i=`tab${o.nextTabId}`,l=`t${o.nextId}`,u={id:l,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},p={type:"leaf",terminalId:l},c={id:i,name:r||`Tab ${o.nextTabId}`,status:"open",terminalIds:[l],layout:p,createdAt:Date.now()};return e({tabs:[...o.tabs,c],activeTabId:i,nextTabId:o.nextTabId+1,nextId:o.nextId+1,terminalsMap:{...o.terminalsMap,[l]:u},terminalIds:c.terminalIds,layout:c.layout}),he(fe(t())),i},switchTab:r=>{const i=t().tabs.find(l=>l.id===r);!i||i.status!=="open"||(e({activeTabId:r,terminalIds:i.terminalIds,layout:i.layout}),he(fe(t())))},closeTab:r=>{const o=t(),i=o.tabs.find(h=>h.id===r);if(!i||i.status!=="open"||o.tabs.filter(h=>h.status==="open").length<=1)return;const u={...o.terminalsMap};for(const h of i.terminalIds)delete u[h];const p=De(o.tabs,r,h=>({...h,status:"closed"}));let c=o.activeTabId,d=o.terminalIds,f=o.layout;if(o.activeTabId===r){const h=o.tabs.findIndex(T=>T.id===r),m=p.filter(T=>T.status==="open"),x=m.find(T=>p.findIndex(E=>E.id===T.id)>h)||m[m.length-1];x&&(c=x.id,d=x.terminalIds,f=x.layout)}e({tabs:p,activeTabId:c,terminalsMap:u,terminalIds:d,layout:f}),he(fe(t()))},reopenTab:r=>{var p;const o=t(),i=o.tabs.find(c=>c.id===r);if(!i||i.status!=="closed")return;const l={...o.terminalsMap};for(const c of i.terminalIds)l[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((p=i.panelStates)==null?void 0:p[c])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const u=De(o.tabs,r,c=>({...c,status:"open"}));e({tabs:u,activeTabId:r,terminalsMap:l,terminalIds:i.terminalIds,layout:i.layout}),he(fe(t()))},deleteTab:async r=>{const o=t(),i=o.tabs.find(x=>x.id===r);if(!i)return;const l=o.token;l&&await Promise.all(i.terminalIds.map(x=>fetch(`${$e}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:ve(l)}).catch(()=>{})));const u=t(),p=u.tabs.find(x=>x.id===r);if(!p)return;const c={...u.terminalsMap};for(const x of p.terminalIds)delete c[x];const d=u.tabs.filter(x=>x.id!==r);let f=u.activeTabId,h=u.terminalIds,m=u.layout;if(u.activeTabId===r){const x=d.find(T=>T.status==="open");x?(f=x.id,h=x.terminalIds,m=x.layout):(f="",h=[],m=null)}e({tabs:d,activeTabId:f,terminalsMap:c,terminalIds:h,layout:m}),he(fe(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(r,o)=>{const i=De(t().tabs,r,l=>({...l,name:o}));e({tabs:i}),he(fe(t()))},addTerminal:(r,o)=>{const i=t();if(o&&i.terminalsMap[o])return o;const l=Et(i);if(!l){const z=`tab${i.nextTabId}`,F=o||`t${i.nextId}`;let B=i.nextId;const P=F.match(/^t(\d+)$/);P&&(B=Math.max(B,parseInt(P[1],10)+1));const O=o?B:B+1,N={id:F,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},C={type:"leaf",terminalId:F},S={id:z,name:`Tab ${i.nextTabId}`,status:"open",terminalIds:[F],layout:C,createdAt:Date.now()};return e({tabs:[...i.tabs,S],activeTabId:z,nextTabId:i.nextTabId+1,nextId:O,terminalsMap:{...i.terminalsMap,[F]:N},terminalIds:[F],layout:C}),he(fe(t())),F}const{nextId:u,nextSplitId:p,terminalsMap:c}=i,{terminalIds:d,layout:f}=l,h=o||`t${u}`;let m=u;const x=h.match(/^t(\d+)$/);x&&(m=Math.max(m,parseInt(x[1],10)+1));const T={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},k={type:"leaf",terminalId:h};let E,b=p;if(!f)E=k;else if(f.type==="leaf"){const z=r||"horizontal";E={id:`s${b}`,type:"split",direction:z,children:[f,k],sizes:[50,50]},b++}else if(f.direction===(r||"horizontal")){const F=100/(f.children.length+1),B=(100-F)/100,P=[...f.sizes.map(O=>O*B),F];E={...f,children:[...f.children,k],sizes:P}}else{const z=r||"horizontal";E={id:`s${b}`,type:"split",direction:z,children:[f,k],sizes:[50,50]},b++}const j=[...d,h],w=o?m:m+1,L=De(i.tabs,l.id,z=>({...z,terminalIds:j,layout:E}));return e({terminalsMap:{...c,[h]:T},terminalIds:j,layout:E,tabs:L,nextId:w,nextSplitId:b}),he(fe(t())),h},splitTerminal:(r,o,i)=>{const l=t(),u=Et(l);if(!u||!u.layout)return"";const{nextId:p,nextSplitId:c,terminalsMap:d}=l,f=`t${p}`,h={id:f,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1},...i?{startCwd:i}:{}},m={type:"leaf",terminalId:f},x=`s${c}`,T=Dn(u.layout,r,o,m,x),k=[...u.terminalIds,f],E=p+1,b=c+1,j=De(l.tabs,u.id,w=>({...w,terminalIds:k,layout:T}));return e({terminalsMap:{...d,[f]:h},terminalIds:k,layout:T,tabs:j,nextId:E,nextSplitId:b}),he(fe(t())),f},removeTerminal:r=>{const o=qt(t(),r);o&&(e(o),he(fe(t())))},disconnectTerminal:r=>{const o=t();if(!o.terminalsMap[r])return;const{[r]:l,...u}=o.terminalsMap;e({terminalsMap:u})},reconnectTerminal:r=>{var p;const o=t();if(o.terminalsMap[r])return;const i=o.tabs.find(c=>c.terminalIds.includes(r)),l=((p=i==null?void 0:i.panelStates)==null?void 0:p[r])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1},u={id:r,connected:!1,sessionResumed:!1,error:null,panels:l};e({terminalsMap:{...o.terminalsMap,[r]:u}})},setTerminalConnected:(r,o)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.connected===o?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,connected:o}}}})},setTerminalResumed:(r,o)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.sessionResumed===o?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,sessionResumed:o}}}})},setTerminalError:(r,o)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.error===o?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,error:o}}}})},toggleChat:r=>{Tt("chatOpen")(r,t,e),he(fe(t()))},togglePlan:r=>{Tt("planOpen","gitHistoryOpen")(r,t,e),he(fe(t()))},toggleGitHistory:r=>{Tt("gitHistoryOpen","planOpen")(r,t,e),he(fe(t()))},setSplitSizes:(r,o)=>{const i=t(),l=Et(i);if(!l||!l.layout)return;const u=An(l.layout,r,o),p=De(i.tabs,l.id,c=>({...c,layout:u}));e({layout:u,tabs:p}),Hr(fe(t()))},killServerSession:async r=>{const o=t().token;if(!o)return;try{await fetch(`${$e}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:ve(o)})}catch{}const i=qt(t(),r);i&&(e(i),he(fe(t()))),setTimeout(()=>t().fetchSessions(),500)}}});Pr($);typeof document<"u"&&document.documentElement.setAttribute("data-theme",$.getState().theme);function Vr(){const[n,e]=a.useState(""),t=$(o=>o.setToken),r=o=>{o.preventDefault(),n.trim()&&t(n.trim())};return s.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:s.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:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.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:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.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"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:n,onChange:o=>e(o.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"}})]}),s.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"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const bt=new Map;function qr(n,e,t){bt.set(n,{onChunk:e,onControl:t})}function Yr(n){bt.delete(n)}function Xr(n,e){var t;(t=bt.get(n))==null||t.onChunk(e)}function Zr(n,e){var t;(t=bt.get(n))==null||t.onControl(e)}const Qr=1,Qt=2,es=3,ts=4,ns=5,rs=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,st=500,ss=8e3,os=1e4,en=4e3,as=5e3,is=10,ls=64*1024,cs=new TextDecoder,ds=new TextEncoder;function tn(n,e){const t=ds.encode(e),r=new Uint8Array(1+t.length);return r[0]=n,r.set(t,1),r.buffer}function us(n,e,t){const r=a.useRef(null),o=a.useRef(st),i=a.useRef(null),l=a.useRef(null),u=a.useRef(null),p=a.useRef(null),c=a.useRef(!1),d=a.useRef(t),f=a.useRef(!1),h=a.useRef(0),m=a.useRef(!0),x=a.useRef(!navigator.onLine),T=a.useRef(""),k=a.useRef(null),E=a.useRef("");d.current=t;const b=a.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null),u.current&&(clearTimeout(u.current),u.current=null),i.current&&(clearTimeout(i.current),i.current=null),p.current&&(clearTimeout(p.current),p.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),j=a.useCallback(()=>{var V;const{token:P,setTerminalError:O}=$.getState();if(!P||c.current)return;if(r.current){const W=r.current.readyState;if(W===WebSocket.OPEN||W===WebSocket.CONNECTING)return}f.current=!1;const N=(V=$.getState().terminalsMap[e])==null?void 0:V.startCwd;let C=`${rs}?sessionId=${encodeURIComponent(e)}`;N&&(C+=`&cwd=${encodeURIComponent(N)}`);const S=new WebSocket(C);S.binaryType="arraybuffer",p.current=window.setTimeout(()=>{S.readyState===WebSocket.CONNECTING&&S.close()},as);const X=()=>{S.readyState===WebSocket.OPEN&&(h.current=performance.now(),S.send(JSON.stringify({type:"ping"})),u.current=window.setTimeout(()=>{h.current>0&&(h.current=0,S.close())},en))};S.onopen=()=>{p.current&&(clearTimeout(p.current),p.current=null),S.send(JSON.stringify({type:"auth",token:P})),O(e,null),o.current=st,m.current=!0},S.onclose=W=>{const{setTerminalConnected:J,setTerminalError:ee,setToken:Y}=$.getState();if(J(e,!1),b(),f.current)return;if(W.code===4001){c.current=!0,ee(e,"Authentication failed"),Y(null),localStorage.removeItem("ai-cli-online-token");return}if(W.code===4002)return;if(W.code===4005){ee(e,"Connection limit reached");return}if(!navigator.onLine){x.current=!0;return}if(m.current){m.current=!1,i.current=window.setTimeout(()=>j(),50);return}const I=o.current;o.current=Math.min(I*2,ss);const D=Math.round(I*(.5+Math.random()));i.current=window.setTimeout(()=>{j()},D)},S.onerror=()=>{},S.onmessage=W=>{var J;try{const ee=n.current;if(W.data instanceof ArrayBuffer){const I=new Uint8Array(W.data);if(I.length<1)return;const D=I[0],K=I.subarray(1);switch(D){case Qr:ee==null||ee.write(K);break;case es:ee==null||ee.write(K);break;case ts:{(J=d.current)==null||J.call(d,cs.decode(K));break}case ns:{Xr(e,K);break}}return}const Y=JSON.parse(W.data);switch(Y.type){case"connected":{const I=$.getState();I.setTerminalConnected(e,!0),I.setTerminalResumed(e,Y.resumed);const D=n.current;D&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:D.cols,rows:D.rows})),E.current&&(S.send(tn(Qt,E.current)),E.current=""),X(),l.current=window.setInterval(X,os);break}case"error":$.getState().setTerminalError(e,Y.error);break;case"pong":{if(u.current&&(clearTimeout(u.current),u.current=null),h.current>0){const I=Math.round(performance.now()-h.current),D=$.getState();(D.terminalIds.length===0||D.terminalIds[0]===e)&&D.setLatency(I),h.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Zr(e,Y);break}}catch{}},r.current=S},[e,n,b]),w=a.useCallback(P=>{const O=r.current;if(!O||O.readyState!==WebSocket.OPEN){E.current.length<ls&&(E.current+=P);return}T.current+=P,k.current||(k.current=window.setTimeout(()=>{const N=T.current;T.current="",k.current=null,N&&O.readyState===WebSocket.OPEN&&O.send(tn(Qt,N))},is))},[]),L=a.useCallback((P,O)=>{var N;((N=r.current)==null?void 0:N.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:P,rows:O}))},[]),z=a.useCallback(()=>{var P;((P=r.current)==null?void 0:P.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),F=a.useCallback(P=>{var O;((O=r.current)==null?void 0:O.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:P}))},[]),B=a.useCallback(()=>{var P;((P=r.current)==null?void 0:P.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return a.useEffect(()=>{$.getState().token&&(c.current=!1,j());const O=()=>{x.current=!1,o.current=st,m.current=!0;const S=r.current;(!S||S.readyState===WebSocket.CLOSED||S.readyState===WebSocket.CLOSING)&&j()},N=()=>{x.current=!0},C=()=>{if(document.visibilityState!=="visible")return;const S=r.current;if(!S||S.readyState!==WebSocket.OPEN){!x.current&&!f.current&&(o.current=st,m.current=!0,j());return}h.current=performance.now(),S.send(JSON.stringify({type:"ping"})),u.current&&clearTimeout(u.current),u.current=window.setTimeout(()=>{h.current>0&&(h.current=0,S.close())},en)};return window.addEventListener("online",O),window.addEventListener("offline",N),document.addEventListener("visibilitychange",C),()=>{f.current=!0,b(),window.removeEventListener("online",O),window.removeEventListener("offline",N),document.removeEventListener("visibilitychange",C),r.current&&(r.current.close(),r.current=null)}},[j,b,e]),{sendInput:w,sendResize:L,requestScrollback:z,requestFileStream:F,cancelFileStream:B}}function fs(n){const e=a.useRef(null),t=a.useRef(null),r=a.useRef(n);r.current=n;const o=a.useCallback(()=>{t.current&&(clearTimeout(t.current),t.current=null),e.current&&(e.current.remove(),e.current=null)},[]),i=a.useCallback((l,u)=>{o();const p=document.createElement("div");p.style.cssText=`position:fixed;left:${l}px;top:${u}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",d=>{var h;d.preventDefault();const f=(h=d.clipboardData)==null?void 0:h.getData("text/plain");f&&r.current(f),o()}),c.addEventListener("keydown",d=>{d.key==="Escape"&&o()}),p.appendChild(c),document.body.appendChild(p),e.current=p,requestAnimationFrame(()=>{const d=p.getBoundingClientRect();d.right>window.innerWidth&&(p.style.left=`${window.innerWidth-d.width-8}px`),d.bottom>window.innerHeight&&(p.style.top=`${window.innerHeight-d.height-8}px`),c.focus()}),t.current=setTimeout(o,8e3)},[o]);return a.useEffect(()=>{const l=()=>{e.current&&o()};return document.addEventListener("click",l),()=>{document.removeEventListener("click",l),o()}},[o]),{showPasteFloat:i,removePasteFloat:o}}const ct={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"},dt={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"},$n="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",ps=a.forwardRef(function({sessionId:e},t){const r=a.useRef(null),o=a.useRef(null),i=a.useRef(null),[l,u]=a.useState(!1),[p,c]=a.useState(""),d=$(L=>L.fontSize),f=$(L=>L.theme),h=a.useCallback(L=>{c(L),u(!0)},[]),{sendInput:m,sendResize:x,requestScrollback:T,requestFileStream:k,cancelFileStream:E}=us(o,e,h);a.useImperativeHandle(t,()=>({sendInput:m,requestFileStream:k,cancelFileStream:E}),[m,k,E]);const b=a.useRef(m),j=a.useRef(x);b.current=m,j.current=x;const{removePasteFloat:w}=fs(L=>b.current(L));return a.useEffect(()=>{if(!r.current)return;let L=!1,z=null,F=null,B=null,P=null;if(L||!r.current)return;const O=new Sn({cursorBlink:!0,scrollback:1e4,fontSize:$.getState().fontSize,fontFamily:$n,theme:$.getState().theme==="dark"?ct:dt,allowProposedApi:!0}),N=new kn;O.loadAddon(N),O.loadAddon(new nr((Y,I)=>{window.open(I,"_blank","noopener,noreferrer")})),O.open(r.current);try{const Y=new Cn;Y.onContextLoss(()=>{Y.dispose()}),O.loadAddon(Y)}catch{}o.current=O,i.current=N,O.onSelectionChange(()=>{const Y=O.getSelection();Y&&navigator.clipboard.writeText(Y).catch(()=>{})});const C=O.element,S=Y=>{var I;Y.preventDefault(),w(),(I=navigator.clipboard)!=null&&I.readText&&navigator.clipboard.readText().then(D=>{D&&b.current(D)}).catch(()=>{})};C&&C.addEventListener("contextmenu",S);const X=()=>{try{const Y=r.current;if(Y&&Y.clientWidth>0&&Y.clientHeight>0)return N.fit(),j.current(O.cols,O.rows),!0}catch{}return!1};requestAnimationFrame(()=>X());let V=0;z=setInterval(()=>{V++,(X()||V>=10)&&(clearInterval(z),z=null)},100),document.fonts.ready.then(()=>{if(!L)try{N.fit(),j.current(O.cols,O.rows)}catch{}});let W=null;const J=()=>{L||(W&&clearTimeout(W),W=setTimeout(()=>{if(!L)try{N.fit(),j.current(O.cols,O.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",J),O.onData(Y=>{b.current(Y)});let ee=!1;return P=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!ee){ee=!0;const I=()=>{document.removeEventListener("mouseup",I),ee=!1,requestAnimationFrame(()=>{try{N.fit(),j.current(O.cols,O.rows)}catch{}})};document.addEventListener("mouseup",I)}return}F||(F=requestAnimationFrame(()=>{F=null;try{N.fit(),B&&clearTimeout(B),B=setTimeout(()=>{B=null,j.current(O.cols,O.rows)},50)}catch{}}))}),P.observe(r.current),()=>{L=!0,z&&clearInterval(z),F&&cancelAnimationFrame(F),B&&clearTimeout(B),W&&clearTimeout(W),document.fonts.removeEventListener("loadingdone",J),P&&P.disconnect(),w(),C&&C.removeEventListener("contextmenu",S),o.current&&(o.current.dispose(),o.current=null),i.current=null}},[e]),a.useEffect(()=>{const L=o.current,z=i.current;if(!(!L||!z)&&L.options.fontSize!==d){L.options.fontSize=d;try{z.fit()}catch{}j.current(L.cols,L.rows)}},[d]),a.useEffect(()=>{o.current&&(o.current.options.theme=f==="dark"?ct:dt)},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:L=>{L.currentTarget.blur(),l?(u(!1),c("")):T()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:l?"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:l?"✕":s.jsx("span",{style:{fontSize:14},children:"👁"})}),l&&s.jsx(ms,{data:p,onClose:()=>{u(!1),c("")}})]})});function ms({data:n,onClose:e}){const t=a.useRef(null),r=a.useRef(e);r.current=e;const o=$(c=>c.fontSize),i=$(c=>c.theme),l=a.useRef(null),u=a.useRef(null);a.useEffect(()=>{if(!t.current)return;const c=new Sn({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:$n,theme:i==="dark"?ct:dt});l.current=c;const d=new kn;u.current=d,c.loadAddon(d),c.open(t.current);let f=null;try{f=new Cn,f.onContextLoss(()=>{f==null||f.dispose(),f=null}),c.loadAddon(f)}catch{f=null}c.onSelectionChange(()=>{const E=c.getSelection();E&&navigator.clipboard.writeText(E).catch(()=>{})}),c.attachCustomKeyEventHandler(E=>(E.key==="Escape"&&r.current(),!1)),c.write(n);let h=null;const m=()=>{const E=t.current;if(!E||E.clientWidth<=0||E.clientHeight<=0)return!1;try{return d.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!m()){let E=0;h=setInterval(()=>{E++,(m()||E>=30)&&(clearInterval(h),h=null)},50)}});let x=null;const T=new ResizeObserver(()=>{x||(x=requestAnimationFrame(()=>{x=null,m()}))});T.observe(t.current);const k=E=>{E.key==="Escape"&&r.current()};return document.addEventListener("keydown",k),()=>{if(h&&clearInterval(h),x&&cancelAnimationFrame(x),document.removeEventListener("keydown",k),T.disconnect(),f){try{f.dispose()}catch{}f=null}c.dispose(),l.current=null,u.current=null}},[n]),a.useEffect(()=>{var c;if(l.current){l.current.options.fontSize=o;try{(c=u.current)==null||c.fit()}catch{}}},[o]),a.useEffect(()=>{l.current&&(l.current.options.theme=i==="dark"?ct:dt)},[i]);const p=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[s.jsx("div",{style:{height:p,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:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:t,style:{position:"absolute",top:p,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const hs=50;function Nt(){const n=a.useRef([]),e=a.useCallback(o=>{n.current.push(o),n.current.length>hs&&n.current.shift()},[]),t=a.useCallback(()=>n.current.pop(),[]),r=a.useCallback(()=>{n.current=[]},[]);return a.useMemo(()=>({pushUndo:e,popUndo:t,clearUndo:r}),[e,t,r])}function Dt(n,e,t){n.preventDefault();const r=n.currentTarget,o=r.selectionStart,i=r.selectionEnd,l=r.value;t==null||t(l);const u=l.slice(0,o)+" "+l.slice(i);e(u),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function ut(n,e=20){var t;return Math.min(e,Math.max(1,(((t=n.match(/\n/g))==null?void 0:t.length)??0)+1))}let Ue=null,zn="dark";const gs=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],xs={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"},bs={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"},ys={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function nn(n,e){return zn=e,n.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?xs:bs,gantt:ys}),n}function vs(n="dark"){return Ue?zn!==n?Ue.then(e=>nn(e,n)):Ue:(Ue=(async()=>{for(const e of gs)try{const t=await import(e);return nn(t.default,n)}catch{}throw Ue=null,new Error("All mermaid CDN sources failed")})(),Ue)}let rn=0;function ws(n,e,t="dark"){const r=a.useRef(t);a.useEffect(()=>{const o=n.current;if(!o)return;const i=r.current!==t;r.current=t;const l=o.querySelectorAll("code.language-mermaid, code.language-gantt"),u=i?o.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(l.length===0&&u.length===0)return;let p=!1;return(async()=>{let c;try{c=await vs(t)}catch{if(p)return;for(const f of l){const h=f.parentElement;if(!h||h.tagName!=="PRE")continue;h.classList.add("mermaid-error");const m=document.createElement("div");m.className="mermaid-error__msg",m.textContent="Failed to load Mermaid library",h.appendChild(m)}return}if(!p){for(const d of u){if(p)break;const f=d.getAttribute("data-mermaid-source");if(!f)continue;const h=`mermaid-${++rn}`;try{const{svg:m}=await c.render(h,f);if(p)break;d.innerHTML=Rt.sanitize(m,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const d of l){if(p)break;const f=d.parentElement;if(!f||f.tagName!=="PRE")continue;const h=d.textContent||"";if(!h.trim())continue;const m=`mermaid-${++rn}`;try{const{svg:x}=await c.render(m,h);if(p)break;const T=document.createElement("div");T.className="mermaid-diagram",T.setAttribute("data-mermaid-source",h),T.innerHTML=Rt.sanitize(x,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),f.replaceWith(T)}catch{if(p)break;f.classList.add("mermaid-error");const x=document.createElement("div");x.className="mermaid-error__msg",x.textContent="Mermaid syntax error",f.appendChild(x)}}}})(),()=>{p=!0}},[e,t])}async function Ss(n,e,t){const r=await pe.get(n,e,"annotations",{path:t});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function _n(n,e,t,r,o){await pe.put(n,e,"annotations",{path:t,content:r,updatedAt:o})}async function sn(n,e,t,r){return pe.post(n,e,"task-annotations",{modulePath:t,content:r})}const At={additions:[],deletions:[],replacements:[],comments:[]};let ks=0;function Ce(){return`ann_${++ks}_${Date.now()}`}function Qe(n,e){return`plan-annotations-${n}-${e}`}function on(n,e){return`plan-scroll-${n}-${e}`}function Cs(n){const e=String(Tn.parser([n],{async:!1}));return Rt.sanitize(e,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function ot(n,e){let t=1;for(let r=0;r<e&&r<n.length;r++){const o=n[r].raw??"";for(const i of o)i===`
|
|
25
|
+
*/var gt=a,wr=vr;function Sr(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var kr=typeof Object.is=="function"?Object.is:Sr,Cr=wr.useSyncExternalStore,Tr=gt.useRef,Er=gt.useEffect,jr=gt.useMemo,Ir=gt.useDebugValue;Rn.useSyncExternalStoreWithSelector=function(n,e,t,r,o){var i=Tr(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=jr(function(){function p(m){if(!c){if(c=!0,d=m,m=r(m),o!==void 0&&l.hasValue){var x=l.value;if(o(x,m))return f=x}return f=m}if(x=f,kr(d,m))return x;var T=r(m);return o!==void 0&&o(x,T)?(d=m,x):(d=m,f=T)}var c=!1,d,f,h=t===void 0?null:t;return[function(){return p(e())},h===null?void 0:function(){return p(h())}]},[e,t,r,o]);var u=Cr(n,i[0],i[1]);return Er(function(){l.hasValue=!0,l.value=u},[u]),Ir(u),u};In.exports=Rn;var Rr=In.exports;const Lr=tr(Rr),Nn={},{useDebugValue:Mr}=$t,{useSyncExternalStoreWithSelector:Nr}=Lr;let Gt=!1;const Dr=n=>n;function Ar(n,e=Dr,t){(Nn?"production":void 0)!=="production"&&t&&!Gt&&(Gt=!0);const r=Nr(n.subscribe,n.getState,n.getServerState||n.getInitialState,e,t);return Mr(r),r}const Jt=n=>{const e=typeof n=="function"?dr(n):n,t=(r,o)=>Ar(e,r,o);return Object.assign(t,e),t},$r=n=>n?Jt(n):Jt,$e="";function ve(n){return{Authorization:`Bearer ${n}`}}class Xe extends Error{constructor(e,t){super(t),this.status=e,this.name="ApiError"}}function Oe(n,e){return`${$e}/api/sessions/${encodeURIComponent(n)}/${e}`}function Vt(n){return`${$e}/api/settings/${n}`}async function Ye(n){if(!n.ok){const e=await n.text().catch(()=>n.statusText);throw new Xe(n.status,e)}return n.json()}const pe={async get(n,e,t,r){const o=new URL(Oe(e,t),window.location.origin);if(r)for(const[l,u]of Object.entries(r))o.searchParams.set(l,u);const i=await fetch(o.toString(),{headers:ve(n)});return Ye(i)},async getOptional(n,e,t,r){const o=new URL(Oe(e,t),window.location.origin);if(r)for(const[l,u]of Object.entries(r))o.searchParams.set(l,u);const i=await fetch(o.toString(),{headers:ve(n)});return i.status===304?null:Ye(i)},async post(n,e,t,r){const o=await fetch(Oe(e,t),{method:"POST",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(r)});return Ye(o)},async put(n,e,t,r){const o=await fetch(Oe(e,t),{method:"PUT",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const i=await o.text().catch(()=>o.statusText);throw new Xe(o.status,i)}},async putJson(n,e,t,r){const o=await fetch(Oe(e,t),{method:"PUT",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(r)});return Ye(o)},async del(n,e,t,r){const o=await fetch(Oe(e,t),{method:"DELETE",headers:{...ve(n),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!o.ok){const i=await o.text().catch(()=>o.statusText);throw new Xe(o.status,i)}},async getBlob(n,e,t,r){const o=new URL(Oe(e,t),window.location.origin);if(r)for(const[l,u]of Object.entries(r))o.searchParams.set(l,u);const i=await fetch(o.toString(),{headers:ve(n)});if(!i.ok)throw new Xe(i.status,"Download failed");return i}},xt={async get(n,e){const t=await fetch(Vt(e),{headers:ve(n)});return Ye(t)},async put(n,e,t){const r=await fetch(Vt(e),{method:"PUT",headers:{...ve(n),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.text().catch(()=>r.statusText);throw new Xe(r.status,o)}}};async function zr(n){try{return(await xt.get(n,"font-size")).fontSize}catch{return 14}}async function _r(n,e){try{await xt.put(n,"font-size",{fontSize:e})}catch{}}let nt=null;const Or=(n,e)=>({fontSize:14,setFontSize:t=>{const r=Math.max(10,Math.min(24,t));n({fontSize:r}),nt&&clearTimeout(nt),nt=setTimeout(()=>{nt=null;const o=e().token;o&&_r(o,r)},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 r=await fetch(`${$e}/api/sessions`,{headers:ve(t)});if(!r.ok)return;const o=await r.json();n({serverSessions:o})}catch{}}});function Tt(n,e){return(t,r,o)=>{const i=r(),l=i.terminalsMap[t];if(!l)return;const u=!l.panels[n],p={...l.panels,[n]:u,...u&&e?{[e]:!1}:{}},c={...i.terminalsMap,[t]:{...l,panels:p}},d=i.tabs.find(h=>h.terminalIds.includes(t));let f=i.tabs;if(d){const h={...d.panelStates,[t]:p};f=De(i.tabs,d.id,m=>({...m,panelStates:h}))}o({terminalsMap:c,tabs:f})}}function lt(n,e){if(n.type==="leaf")return n.terminalId===e?null:n;const t=[],r=[];for(let l=0;l<n.children.length;l++){const u=lt(n.children[l],e);u!==null&&(t.push(u),r.push(n.sizes[l]))}if(t.length===0)return null;if(t.length===1)return t[0];const o=r.reduce((l,u)=>l+u,0),i=r.map(l=>l/o*100);return{...n,children:t,sizes:i}}function Dn(n,e,t,r,o){return n.type==="leaf"?n.terminalId===e?{id:o,type:"split",direction:t,children:[n,r],sizes:[50,50]}:n:{...n,children:n.children.map(i=>Dn(i,e,t,r,o))}}function An(n,e,t){return n.type==="leaf"?n:n.id===e?{...n,sizes:t}:{...n,children:n.children.map(r=>An(r,e,t))}}function Et(n){return n.tabs.find(e=>e.id===n.activeTabId)}function De(n,e,t){return n.map(r=>r.id===e?t(r):r)}function qt(n,e){const t=n.tabs.find(c=>c.terminalIds.includes(e));if(!t){const{[e]:c,...d}=n.terminalsMap;return{terminalsMap:d}}const r=t.terminalIds.filter(c=>c!==e),o=t.layout?lt(t.layout,e):null,i=De(n.tabs,t.id,c=>({...c,terminalIds:r,layout:o})),{[e]:l,...u}=n.terminalsMap,p={terminalsMap:u,tabs:i};return t.id===n.activeTabId&&(p.terminalIds=r,p.layout=o),p}async function Fr(n){try{return(await xt.get(n,"tabs-layout")).layout}catch{return null}}async function Br(n,e){try{await xt.put(n,"tabs-layout",{layout:e})}catch{}}function Yt(n,e){try{const t=`${$e}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:n});navigator.sendBeacon(t,new Blob([r],{type:"application/json"}))}catch{}}const Mt="ai-cli-online-tabs",Xt="ai-cli-online-layout",Zt="ai-cli-online-session-names";let Ee=null;function Pr(n){Ee=n,Jr()}let rt=null,Fe=null,Ze=null;function Wr(n){Ze=n,Fe&&clearTimeout(Fe),Fe=setTimeout(()=>{Fe=null,Ze=null;const e=Ee==null?void 0:Ee.getState().token;e&&Br(e,n)},2e3)}function he(n){const e={version:2,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId,tabs:n.tabs};try{localStorage.setItem(Mt,JSON.stringify(e))}catch{}Wr(e)}function Hr(n){rt&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,he(n)},500)}function fe(n){return{tabs:n.tabs,activeTabId:n.activeTabId,nextId:n.nextId,nextSplitId:n.nextSplitId,nextTabId:n.nextTabId}}function Ur(){try{const n=localStorage.getItem(Mt);if(n){const e=JSON.parse(n);if(e.version===2)return e}}catch{}try{const n=localStorage.getItem(Xt);if(n){const e=JSON.parse(n);let t="Default";try{const i=localStorage.getItem(Zt);if(i){const l=JSON.parse(i),u=Object.values(l)[0];u&&(t=u)}}catch{}const r={id:"tab1",name:t,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Mt,JSON.stringify(o))}catch{}return localStorage.removeItem(Xt),localStorage.removeItem(Zt),o}}catch{}return null}function Kr(n,e){const t=new Set(e.map(l=>l.sessionId)),r=[];for(const l of n.tabs){if(l.status!=="open"){const c=l.terminalIds.filter(d=>t.has(d));if(c.length>0){let d=l.layout;for(const f of l.terminalIds)!t.has(f)&&d&&(d=lt(d,f));r.push({...l,terminalIds:c,layout:d})}continue}const u=l.terminalIds.filter(c=>t.has(c));if(u.length===0)continue;let p=l.layout;for(const c of l.terminalIds)!t.has(c)&&p&&(p=lt(p,c));r.push({...l,terminalIds:u,layout:p})}if(r.filter(l=>l.status==="open").length===0)return null;let o=n.activeTabId;if(!r.find(l=>l.id===o&&l.status==="open")){const l=r.find(u=>u.status==="open");o=(l==null?void 0:l.id)||""}return{...n,activeTabId:o,tabs:r}}async function Gr(n,e){var o,i;if(!Ee)return;const{setState:t,getState:r}=Ee;try{const[l,u]=await Promise.all([Fr(n),fetch(`${$e}/api/sessions`,{headers:ve(n)}).then(x=>x.ok?x.json():[]).catch(()=>[])]);if(r().token!==n)return;const p=l&&((o=l.tabs)==null?void 0:o.length)>0?l:e;if(!p||p.tabs.length===0){t({tabsLoading:!1});return}const c=Kr(p,u);if(!c){t({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:p.nextId,nextSplitId:p.nextSplitId,nextTabId:p.nextTabId,terminalIds:[],layout:null});return}const d=r().terminalsMap,f={};for(const x of c.tabs)if(x.status==="open")for(const T of x.terminalIds)f[T]=d[T]||{id:T,connected:!1,sessionResumed:!1,error:null,panels:((i=x.panelStates)==null?void 0:i[T])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const h=c.tabs.find(x=>x.id===c.activeTabId&&x.status==="open")||c.tabs.find(x=>x.status==="open"),m=(h==null?void 0:h.id)||"";t({tabsLoading:!1,terminalsMap:f,tabs:c.tabs,activeTabId:m,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(h==null?void 0:h.terminalIds)||[],layout:(h==null?void 0:h.layout)||null}),he(fe(r()))}catch{r().token===n&&t({tabsLoading:!1})}}function Jr(){typeof window>"u"||!Ee||window.addEventListener("beforeunload",()=>{const n=Ee==null?void 0:Ee.getState().token;if(n)if(Ze)Fe&&(clearTimeout(Fe),Fe=null),Yt(n,Ze),Ze=null;else{const e=Ee.getState();e.tabs.length>0&&Yt(n,fe(e))}})}const z=$r((...n)=>{const[e,t]=n;return{...Or(...n),token:null,tabsLoading:!1,setToken:r=>{var o;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}zr(r).then(l=>{t().token===r&&e({fontSize:l})});const i=Ur();if(i&&i.tabs.length>0){const l={};for(const c of i.tabs)if(c.status==="open")for(const d of c.terminalIds)l[d]={id:d,connected:!1,sessionResumed:!1,error:null,panels:((o=c.panelStates)==null?void 0:o[d])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const u=i.tabs.find(c=>c.id===i.activeTabId&&c.status==="open")||i.tabs.find(c=>c.status==="open"),p=(u==null?void 0:u.id)||"";e({token:r,tabsLoading:!0,terminalsMap:l,tabs:i.tabs,activeTabId:p,nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null})}else e({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Gr(r,i);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),e({token:r,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:r=>{const o=t(),i=`tab${o.nextTabId}`,l=`t${o.nextId}`,u={id:l,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},p={type:"leaf",terminalId:l},c={id:i,name:r||`Tab ${o.nextTabId}`,status:"open",terminalIds:[l],layout:p,createdAt:Date.now()};return e({tabs:[...o.tabs,c],activeTabId:i,nextTabId:o.nextTabId+1,nextId:o.nextId+1,terminalsMap:{...o.terminalsMap,[l]:u},terminalIds:c.terminalIds,layout:c.layout}),he(fe(t())),i},switchTab:r=>{const i=t().tabs.find(l=>l.id===r);!i||i.status!=="open"||(e({activeTabId:r,terminalIds:i.terminalIds,layout:i.layout}),he(fe(t())))},closeTab:r=>{const o=t(),i=o.tabs.find(h=>h.id===r);if(!i||i.status!=="open"||o.tabs.filter(h=>h.status==="open").length<=1)return;const u={...o.terminalsMap};for(const h of i.terminalIds)delete u[h];const p=De(o.tabs,r,h=>({...h,status:"closed"}));let c=o.activeTabId,d=o.terminalIds,f=o.layout;if(o.activeTabId===r){const h=o.tabs.findIndex(T=>T.id===r),m=p.filter(T=>T.status==="open"),x=m.find(T=>p.findIndex(E=>E.id===T.id)>h)||m[m.length-1];x&&(c=x.id,d=x.terminalIds,f=x.layout)}e({tabs:p,activeTabId:c,terminalsMap:u,terminalIds:d,layout:f}),he(fe(t()))},reopenTab:r=>{var p;const o=t(),i=o.tabs.find(c=>c.id===r);if(!i||i.status!=="closed")return;const l={...o.terminalsMap};for(const c of i.terminalIds)l[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((p=i.panelStates)==null?void 0:p[c])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const u=De(o.tabs,r,c=>({...c,status:"open"}));e({tabs:u,activeTabId:r,terminalsMap:l,terminalIds:i.terminalIds,layout:i.layout}),he(fe(t()))},deleteTab:async r=>{const o=t(),i=o.tabs.find(x=>x.id===r);if(!i)return;const l=o.token;l&&await Promise.all(i.terminalIds.map(x=>fetch(`${$e}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:ve(l)}).catch(()=>{})));const u=t(),p=u.tabs.find(x=>x.id===r);if(!p)return;const c={...u.terminalsMap};for(const x of p.terminalIds)delete c[x];const d=u.tabs.filter(x=>x.id!==r);let f=u.activeTabId,h=u.terminalIds,m=u.layout;if(u.activeTabId===r){const x=d.find(T=>T.status==="open");x?(f=x.id,h=x.terminalIds,m=x.layout):(f="",h=[],m=null)}e({tabs:d,activeTabId:f,terminalsMap:c,terminalIds:h,layout:m}),he(fe(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(r,o)=>{const i=De(t().tabs,r,l=>({...l,name:o}));e({tabs:i}),he(fe(t()))},addTerminal:(r,o)=>{const i=t();if(o&&i.terminalsMap[o])return o;const l=Et(i);if(!l){const L=`tab${i.nextTabId}`,_=o||`t${i.nextId}`;let B=i.nextId;const P=_.match(/^t(\d+)$/);P&&(B=Math.max(B,parseInt(P[1],10)+1));const F=o?B:B+1,D={id:_,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},C={type:"leaf",terminalId:_},S={id:L,name:`Tab ${i.nextTabId}`,status:"open",terminalIds:[_],layout:C,createdAt:Date.now()};return e({tabs:[...i.tabs,S],activeTabId:L,nextTabId:i.nextTabId+1,nextId:F,terminalsMap:{...i.terminalsMap,[_]:D},terminalIds:[_],layout:C}),he(fe(t())),_}const{nextId:u,nextSplitId:p,terminalsMap:c}=i,{terminalIds:d,layout:f}=l,h=o||`t${u}`;let m=u;const x=h.match(/^t(\d+)$/);x&&(m=Math.max(m,parseInt(x[1],10)+1));const T={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},k={type:"leaf",terminalId:h};let E,b=p;if(!f)E=k;else if(f.type==="leaf"){const L=r||"horizontal";E={id:`s${b}`,type:"split",direction:L,children:[f,k],sizes:[50,50]},b++}else if(f.direction===(r||"horizontal")){const _=100/(f.children.length+1),B=(100-_)/100,P=[...f.sizes.map(F=>F*B),_];E={...f,children:[...f.children,k],sizes:P}}else{const L=r||"horizontal";E={id:`s${b}`,type:"split",direction:L,children:[f,k],sizes:[50,50]},b++}const j=[...d,h],w=o?m:m+1,N=De(i.tabs,l.id,L=>({...L,terminalIds:j,layout:E}));return e({terminalsMap:{...c,[h]:T},terminalIds:j,layout:E,tabs:N,nextId:w,nextSplitId:b}),he(fe(t())),h},splitTerminal:(r,o,i)=>{const l=t(),u=Et(l);if(!u||!u.layout)return"";const{nextId:p,nextSplitId:c,terminalsMap:d}=l,f=`t${p}`,h={id:f,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1},...i?{startCwd:i}:{}},m={type:"leaf",terminalId:f},x=`s${c}`,T=Dn(u.layout,r,o,m,x),k=[...u.terminalIds,f],E=p+1,b=c+1,j=De(l.tabs,u.id,w=>({...w,terminalIds:k,layout:T}));return e({terminalsMap:{...d,[f]:h},terminalIds:k,layout:T,tabs:j,nextId:E,nextSplitId:b}),he(fe(t())),f},removeTerminal:r=>{const o=qt(t(),r);o&&(e(o),he(fe(t())))},disconnectTerminal:r=>{const o=t();if(!o.terminalsMap[r])return;const{[r]:l,...u}=o.terminalsMap;e({terminalsMap:u})},reconnectTerminal:r=>{var p;const o=t();if(o.terminalsMap[r])return;const i=o.tabs.find(c=>c.terminalIds.includes(r)),l=((p=i==null?void 0:i.panelStates)==null?void 0:p[r])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1},u={id:r,connected:!1,sessionResumed:!1,error:null,panels:l};e({terminalsMap:{...o.terminalsMap,[r]:u}})},setTerminalConnected:(r,o)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.connected===o?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,connected:o}}}})},setTerminalResumed:(r,o)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.sessionResumed===o?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,sessionResumed:o}}}})},setTerminalError:(r,o)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.error===o?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,error:o}}}})},toggleChat:r=>{Tt("chatOpen")(r,t,e),he(fe(t()))},togglePlan:r=>{Tt("planOpen","gitHistoryOpen")(r,t,e),he(fe(t()))},toggleGitHistory:r=>{Tt("gitHistoryOpen","planOpen")(r,t,e),he(fe(t()))},setSplitSizes:(r,o)=>{const i=t(),l=Et(i);if(!l||!l.layout)return;const u=An(l.layout,r,o),p=De(i.tabs,l.id,c=>({...c,layout:u}));e({layout:u,tabs:p}),Hr(fe(t()))},killServerSession:async r=>{const o=t().token;if(!o)return;try{await fetch(`${$e}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:ve(o)})}catch{}const i=qt(t(),r);i&&(e(i),he(fe(t()))),setTimeout(()=>t().fetchSessions(),500)}}});Pr(z);typeof document<"u"&&document.documentElement.setAttribute("data-theme",z.getState().theme);function Vr(){const[n,e]=a.useState(""),t=z(o=>o.setToken),r=o=>{o.preventDefault(),n.trim()&&t(n.trim())};return s.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:s.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:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.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:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.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"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:n,onChange:o=>e(o.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"}})]}),s.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"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const bt=new Map;function qr(n,e,t){bt.set(n,{onChunk:e,onControl:t})}function Yr(n){bt.delete(n)}function Xr(n,e){var t;(t=bt.get(n))==null||t.onChunk(e)}function Zr(n,e){var t;(t=bt.get(n))==null||t.onControl(e)}const Qr=1,Qt=2,es=3,ts=4,ns=5,rs=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,st=500,ss=8e3,os=1e4,en=4e3,as=5e3,is=10,ls=64*1024,cs=new TextDecoder,ds=new TextEncoder;function tn(n,e){const t=ds.encode(e),r=new Uint8Array(1+t.length);return r[0]=n,r.set(t,1),r.buffer}function us(n,e,t){const r=a.useRef(null),o=a.useRef(st),i=a.useRef(null),l=a.useRef(null),u=a.useRef(null),p=a.useRef(null),c=a.useRef(!1),d=a.useRef(t),f=a.useRef(!1),h=a.useRef(0),m=a.useRef(!0),x=a.useRef(!navigator.onLine),T=a.useRef(""),k=a.useRef(null),E=a.useRef("");d.current=t;const b=a.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null),u.current&&(clearTimeout(u.current),u.current=null),i.current&&(clearTimeout(i.current),i.current=null),p.current&&(clearTimeout(p.current),p.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),j=a.useCallback(()=>{var V;const{token:P,setTerminalError:F}=z.getState();if(!P||c.current)return;if(r.current){const W=r.current.readyState;if(W===WebSocket.OPEN||W===WebSocket.CONNECTING)return}f.current=!1;const D=(V=z.getState().terminalsMap[e])==null?void 0:V.startCwd;let C=`${rs}?sessionId=${encodeURIComponent(e)}`;D&&(C+=`&cwd=${encodeURIComponent(D)}`);const S=new WebSocket(C);S.binaryType="arraybuffer",p.current=window.setTimeout(()=>{S.readyState===WebSocket.CONNECTING&&S.close()},as);const X=()=>{S.readyState===WebSocket.OPEN&&(h.current=performance.now(),S.send(JSON.stringify({type:"ping"})),u.current=window.setTimeout(()=>{h.current>0&&(h.current=0,S.close())},en))};S.onopen=()=>{p.current&&(clearTimeout(p.current),p.current=null),S.send(JSON.stringify({type:"auth",token:P})),F(e,null),o.current=st,m.current=!0},S.onclose=W=>{const{setTerminalConnected:J,setTerminalError:ee,setToken:Y}=z.getState();if(J(e,!1),b(),f.current)return;if(W.code===4001){c.current=!0,ee(e,"Authentication failed"),Y(null),localStorage.removeItem("ai-cli-online-token");return}if(W.code===4002)return;if(W.code===4005){ee(e,"Connection limit reached");return}if(!navigator.onLine){x.current=!0;return}if(m.current){m.current=!1,i.current=window.setTimeout(()=>j(),50);return}const I=o.current;o.current=Math.min(I*2,ss);const A=Math.round(I*(.5+Math.random()));i.current=window.setTimeout(()=>{j()},A)},S.onerror=()=>{},S.onmessage=W=>{var J;try{const ee=n.current;if(W.data instanceof ArrayBuffer){const I=new Uint8Array(W.data);if(I.length<1)return;const A=I[0],K=I.subarray(1);switch(A){case Qr:ee==null||ee.write(K);break;case es:ee==null||ee.write(K);break;case ts:{(J=d.current)==null||J.call(d,cs.decode(K));break}case ns:{Xr(e,K);break}}return}const Y=JSON.parse(W.data);switch(Y.type){case"connected":{const I=z.getState();I.setTerminalConnected(e,!0),I.setTerminalResumed(e,Y.resumed);const A=n.current;A&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:A.cols,rows:A.rows})),E.current&&(S.send(tn(Qt,E.current)),E.current=""),X(),l.current=window.setInterval(X,os);break}case"error":z.getState().setTerminalError(e,Y.error);break;case"pong":{if(u.current&&(clearTimeout(u.current),u.current=null),h.current>0){const I=Math.round(performance.now()-h.current),A=z.getState();(A.terminalIds.length===0||A.terminalIds[0]===e)&&A.setLatency(I),h.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Zr(e,Y);break}}catch{}},r.current=S},[e,n,b]),w=a.useCallback(P=>{const F=r.current;if(!F||F.readyState!==WebSocket.OPEN){E.current.length<ls&&(E.current+=P);return}T.current+=P,k.current||(k.current=window.setTimeout(()=>{const D=T.current;T.current="",k.current=null,D&&F.readyState===WebSocket.OPEN&&F.send(tn(Qt,D))},is))},[]),N=a.useCallback((P,F)=>{var D;((D=r.current)==null?void 0:D.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:P,rows:F}))},[]),L=a.useCallback(()=>{var P;((P=r.current)==null?void 0:P.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),_=a.useCallback(P=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:P}))},[]),B=a.useCallback(()=>{var P;((P=r.current)==null?void 0:P.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return a.useEffect(()=>{z.getState().token&&(c.current=!1,j());const F=()=>{x.current=!1,o.current=st,m.current=!0;const S=r.current;(!S||S.readyState===WebSocket.CLOSED||S.readyState===WebSocket.CLOSING)&&j()},D=()=>{x.current=!0},C=()=>{if(document.visibilityState!=="visible")return;const S=r.current;if(!S||S.readyState!==WebSocket.OPEN){!x.current&&!f.current&&(o.current=st,m.current=!0,j());return}h.current=performance.now(),S.send(JSON.stringify({type:"ping"})),u.current&&clearTimeout(u.current),u.current=window.setTimeout(()=>{h.current>0&&(h.current=0,S.close())},en)};return window.addEventListener("online",F),window.addEventListener("offline",D),document.addEventListener("visibilitychange",C),()=>{f.current=!0,b(),window.removeEventListener("online",F),window.removeEventListener("offline",D),document.removeEventListener("visibilitychange",C),r.current&&(r.current.close(),r.current=null)}},[j,b,e]),{sendInput:w,sendResize:N,requestScrollback:L,requestFileStream:_,cancelFileStream:B}}function fs(n){const e=a.useRef(null),t=a.useRef(null),r=a.useRef(n);r.current=n;const o=a.useCallback(()=>{t.current&&(clearTimeout(t.current),t.current=null),e.current&&(e.current.remove(),e.current=null)},[]),i=a.useCallback((l,u)=>{o();const p=document.createElement("div");p.style.cssText=`position:fixed;left:${l}px;top:${u}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",d=>{var h;d.preventDefault();const f=(h=d.clipboardData)==null?void 0:h.getData("text/plain");f&&r.current(f),o()}),c.addEventListener("keydown",d=>{d.key==="Escape"&&o()}),p.appendChild(c),document.body.appendChild(p),e.current=p,requestAnimationFrame(()=>{const d=p.getBoundingClientRect();d.right>window.innerWidth&&(p.style.left=`${window.innerWidth-d.width-8}px`),d.bottom>window.innerHeight&&(p.style.top=`${window.innerHeight-d.height-8}px`),c.focus()}),t.current=setTimeout(o,8e3)},[o]);return a.useEffect(()=>{const l=()=>{e.current&&o()};return document.addEventListener("click",l),()=>{document.removeEventListener("click",l),o()}},[o]),{showPasteFloat:i,removePasteFloat:o}}const ct={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"},dt={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"},$n="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",ps=a.forwardRef(function({sessionId:e},t){const r=a.useRef(null),o=a.useRef(null),i=a.useRef(null),[l,u]=a.useState(!1),[p,c]=a.useState(""),d=z(N=>N.fontSize),f=z(N=>N.theme),h=a.useCallback(N=>{c(N),u(!0)},[]),{sendInput:m,sendResize:x,requestScrollback:T,requestFileStream:k,cancelFileStream:E}=us(o,e,h);a.useImperativeHandle(t,()=>({sendInput:m,requestFileStream:k,cancelFileStream:E}),[m,k,E]);const b=a.useRef(m),j=a.useRef(x);b.current=m,j.current=x;const{removePasteFloat:w}=fs(N=>b.current(N));return a.useEffect(()=>{if(!r.current)return;let N=!1,L=null,_=null,B=null,P=null;if(N||!r.current)return;const F=new Sn({cursorBlink:!0,scrollback:1e4,fontSize:z.getState().fontSize,fontFamily:$n,theme:z.getState().theme==="dark"?ct:dt,allowProposedApi:!0}),D=new kn;F.loadAddon(D),F.loadAddon(new nr((Y,I)=>{window.open(I,"_blank","noopener,noreferrer")})),F.open(r.current);try{const Y=new Cn;Y.onContextLoss(()=>{Y.dispose()}),F.loadAddon(Y)}catch{}o.current=F,i.current=D,F.onSelectionChange(()=>{const Y=F.getSelection();Y&&navigator.clipboard.writeText(Y).catch(()=>{})});const C=F.element,S=Y=>{var I;Y.preventDefault(),w(),(I=navigator.clipboard)!=null&&I.readText&&navigator.clipboard.readText().then(A=>{A&&b.current(A)}).catch(()=>{})};C&&C.addEventListener("contextmenu",S);const X=()=>{try{const Y=r.current;if(Y&&Y.clientWidth>0&&Y.clientHeight>0)return D.fit(),j.current(F.cols,F.rows),!0}catch{}return!1};requestAnimationFrame(()=>X());let V=0;L=setInterval(()=>{V++,(X()||V>=10)&&(clearInterval(L),L=null)},100),document.fonts.ready.then(()=>{if(!N)try{D.fit(),j.current(F.cols,F.rows)}catch{}});let W=null;const J=()=>{N||(W&&clearTimeout(W),W=setTimeout(()=>{if(!N)try{D.fit(),j.current(F.cols,F.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",J),F.onData(Y=>{b.current(Y)});let ee=!1;return P=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!ee){ee=!0;const I=()=>{document.removeEventListener("mouseup",I),ee=!1,requestAnimationFrame(()=>{try{D.fit(),j.current(F.cols,F.rows)}catch{}})};document.addEventListener("mouseup",I)}return}_||(_=requestAnimationFrame(()=>{_=null;try{D.fit(),B&&clearTimeout(B),B=setTimeout(()=>{B=null,j.current(F.cols,F.rows)},50)}catch{}}))}),P.observe(r.current),()=>{N=!0,L&&clearInterval(L),_&&cancelAnimationFrame(_),B&&clearTimeout(B),W&&clearTimeout(W),document.fonts.removeEventListener("loadingdone",J),P&&P.disconnect(),w(),C&&C.removeEventListener("contextmenu",S),o.current&&(o.current.dispose(),o.current=null),i.current=null}},[e]),a.useEffect(()=>{const N=o.current,L=i.current;if(!(!N||!L)&&N.options.fontSize!==d){N.options.fontSize=d;try{L.fit()}catch{}j.current(N.cols,N.rows)}},[d]),a.useEffect(()=>{o.current&&(o.current.options.theme=f==="dark"?ct:dt)},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:N=>{N.currentTarget.blur(),l?(u(!1),c("")):T()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:l?"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:N=>{N.currentTarget.style.opacity="1"},onMouseLeave:N=>{N.currentTarget.style.opacity="0.8"},children:l?"✕":s.jsx("span",{style:{fontSize:14},children:"👁"})}),l&&s.jsx(ms,{data:p,onClose:()=>{u(!1),c("")}})]})});function ms({data:n,onClose:e}){const t=a.useRef(null),r=a.useRef(e);r.current=e;const o=z(c=>c.fontSize),i=z(c=>c.theme),l=a.useRef(null),u=a.useRef(null);a.useEffect(()=>{if(!t.current)return;const c=new Sn({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:$n,theme:i==="dark"?ct:dt});l.current=c;const d=new kn;u.current=d,c.loadAddon(d),c.open(t.current);let f=null;try{f=new Cn,f.onContextLoss(()=>{f==null||f.dispose(),f=null}),c.loadAddon(f)}catch{f=null}c.onSelectionChange(()=>{const E=c.getSelection();E&&navigator.clipboard.writeText(E).catch(()=>{})}),c.attachCustomKeyEventHandler(E=>(E.key==="Escape"&&r.current(),!1)),c.write(n);let h=null;const m=()=>{const E=t.current;if(!E||E.clientWidth<=0||E.clientHeight<=0)return!1;try{return d.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!m()){let E=0;h=setInterval(()=>{E++,(m()||E>=30)&&(clearInterval(h),h=null)},50)}});let x=null;const T=new ResizeObserver(()=>{x||(x=requestAnimationFrame(()=>{x=null,m()}))});T.observe(t.current);const k=E=>{E.key==="Escape"&&r.current()};return document.addEventListener("keydown",k),()=>{if(h&&clearInterval(h),x&&cancelAnimationFrame(x),document.removeEventListener("keydown",k),T.disconnect(),f){try{f.dispose()}catch{}f=null}c.dispose(),l.current=null,u.current=null}},[n]),a.useEffect(()=>{var c;if(l.current){l.current.options.fontSize=o;try{(c=u.current)==null||c.fit()}catch{}}},[o]),a.useEffect(()=>{l.current&&(l.current.options.theme=i==="dark"?ct:dt)},[i]);const p=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[s.jsx("div",{style:{height:p,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:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:t,style:{position:"absolute",top:p,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const hs=50;function Nt(){const n=a.useRef([]),e=a.useCallback(o=>{n.current.push(o),n.current.length>hs&&n.current.shift()},[]),t=a.useCallback(()=>n.current.pop(),[]),r=a.useCallback(()=>{n.current=[]},[]);return a.useMemo(()=>({pushUndo:e,popUndo:t,clearUndo:r}),[e,t,r])}function Dt(n,e,t){n.preventDefault();const r=n.currentTarget,o=r.selectionStart,i=r.selectionEnd,l=r.value;t==null||t(l);const u=l.slice(0,o)+" "+l.slice(i);e(u),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function ut(n,e=20){var t;return Math.min(e,Math.max(1,(((t=n.match(/\n/g))==null?void 0:t.length)??0)+1))}let Ue=null,zn="dark";const gs=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],xs={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"},bs={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"},ys={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function nn(n,e){return zn=e,n.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?xs:bs,gantt:ys}),n}function vs(n="dark"){return Ue?zn!==n?Ue.then(e=>nn(e,n)):Ue:(Ue=(async()=>{for(const e of gs)try{const t=await import(e);return nn(t.default,n)}catch{}throw Ue=null,new Error("All mermaid CDN sources failed")})(),Ue)}let rn=0;function ws(n,e,t="dark"){const r=a.useRef(t);a.useEffect(()=>{const o=n.current;if(!o)return;const i=r.current!==t;r.current=t;const l=o.querySelectorAll("code.language-mermaid, code.language-gantt"),u=i?o.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(l.length===0&&u.length===0)return;let p=!1;return(async()=>{let c;try{c=await vs(t)}catch{if(p)return;for(const f of l){const h=f.parentElement;if(!h||h.tagName!=="PRE")continue;h.classList.add("mermaid-error");const m=document.createElement("div");m.className="mermaid-error__msg",m.textContent="Failed to load Mermaid library",h.appendChild(m)}return}if(!p){for(const d of u){if(p)break;const f=d.getAttribute("data-mermaid-source");if(!f)continue;const h=`mermaid-${++rn}`;try{const{svg:m}=await c.render(h,f);if(p)break;d.innerHTML=Rt.sanitize(m,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const d of l){if(p)break;const f=d.parentElement;if(!f||f.tagName!=="PRE")continue;const h=d.textContent||"";if(!h.trim())continue;const m=`mermaid-${++rn}`;try{const{svg:x}=await c.render(m,h);if(p)break;const T=document.createElement("div");T.className="mermaid-diagram",T.setAttribute("data-mermaid-source",h),T.innerHTML=Rt.sanitize(x,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),f.replaceWith(T)}catch{if(p)break;f.classList.add("mermaid-error");const x=document.createElement("div");x.className="mermaid-error__msg",x.textContent="Mermaid syntax error",f.appendChild(x)}}}})(),()=>{p=!0}},[e,t])}async function Ss(n,e,t){const r=await pe.get(n,e,"annotations",{path:t});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function _n(n,e,t,r,o){await pe.put(n,e,"annotations",{path:t,content:r,updatedAt:o})}async function sn(n,e,t,r){return pe.post(n,e,"task-annotations",{modulePath:t,content:r})}const At={additions:[],deletions:[],replacements:[],comments:[]};let ks=0;function Ce(){return`ann_${++ks}_${Date.now()}`}function Qe(n,e){return`plan-annotations-${n}-${e}`}function on(n,e){return`plan-scroll-${n}-${e}`}function Cs(n){const e=String(Tn.parser([n],{async:!1}));return Rt.sanitize(e,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function ot(n,e){let t=1;for(let r=0;r<e&&r<n.length;r++){const o=n[r].raw??"";for(const i of o)i===`
|
|
26
26
|
`&&t++}return t}function at(n,e,t,r){const o=n.join(`
|
|
27
|
-
`);let i=0;for(let m=0;m<e-1&&m<n.length;m++)i+=n[m].length+1;let l=0;for(let m=0;m<t&&m<n.length;m++)l+=n[m].length+1;let u=i,p=Math.min(o.length,l);if(r){const m=Math.max(0,i-10),x=Math.min(o.length,l+10),k=o.slice(m,x).indexOf(r);k>=0&&(u=m+k,p=u+r.length)}const c=Math.max(0,u-20),d=o.slice(c,u).replace(/\n/g,"↵"),f=Math.min(o.length,p+20),h=o.slice(p,f).replace(/\n/g,"↵");return{before:d,after:h}}function an(n,e){const t=[],r=[],o=[],i=[];for(const l of n.additions){const{before:u,after:p}=at(e,l.sourceLine,l.sourceLine);t.push([`Line${l.sourceLine}:...${u}`,l.content,`${p}...`])}for(const l of n.deletions){const{before:u,after:p}=at(e,l.startLine,l.endLine,l.selectedText);r.push([`Line${l.startLine}:...${u}`,l.selectedText,`${p}...`])}for(const l of n.replacements){const{before:u,after:p}=at(e,l.startLine,l.endLine,l.selectedText);o.push([`Line${l.startLine}:...${u}`,l.selectedText,l.content,`${p}...`])}for(const l of n.comments){const{before:u,after:p}=at(e,l.startLine,l.endLine,l.selectedText);i.push([`Line${l.startLine}:...${u}`,l.selectedText,l.content,`${p}...`])}return{"Insert Annotations":t,"Delete Annotations":r,"Replace Annotations":o,"Comment Annotations":i}}function ln(n){return n.additions.length>0||n.deletions.length>0||n.replacements.length>0||n.comments.length>0}function cn(n){return/^[a-zA-Z0-9_./:@=-]+$/.test(n)?n:"'"+n.replace(/'/g,"'\\''")+"'"}function dn(n,e){return`/moonview:annotate ${cn(n)} ${cn(e)} --silent`}function un(n){const e=n.split("/"),t=e.indexOf("AiTasks");return t>=0&&t+1<e.length?e.slice(0,t+2).join("/"):n.substring(0,n.lastIndexOf("/"))}function ft(n){const e=new Set;return n.additions.forEach(t=>e.add(t.id)),n.deletions.forEach(t=>e.add(t.id)),n.replacements.forEach(t=>e.add(t.id)),n.comments.forEach(t=>e.add(t.id)),e}function fn(n){return n.replacements||(n.replacements=[]),n.comments||(n.comments=[]),n}function Ts({sessionId:n,filePath:e,token:t,annotations:r,annLoadedRef:o,setAnnotations:i,baselineIdsRef:l}){const u
|
|
28
|
-
`);let o=!1;for(const i of r){if(/^```/.test(i.trim())){o=!o;continue}if(o)continue;const l=i.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(l){const u=l[1].length,p=Fn(l[2]),c=On(p,t);e.push({id:c,text:p,level:u})}}return e}const js=160,Is=22;function Rs({headings:n,scrollRef:e}){const[t,r]=a.useState(null),[o,i]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),l=a.useRef(null),u=a.useRef(!1),p=a.useMemo(()=>Math.min(...n.map(f=>f.level)),[n]),c=a.useCallback(()=>{i(f=>{const h=!f;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);a.useEffect(()=>{const f=e.current;if(!f||n.length===0)return;const h=()=>{u.current=!1;const x=f.scrollTop,T=50;let k=null;for(const E of n){const b=f.querySelector(`[id="${CSS.escape(E.id)}"]`);b&&b.offsetTop<=x+T&&(k=E.id)}r(k)},m=()=>{u.current||(u.current=!0,requestAnimationFrame(h))};return h(),f.addEventListener("scroll",m,{passive:!0}),()=>f.removeEventListener("scroll",m)},[n,e]);const d=a.useCallback(f=>{const h=e.current;if(!h)return;const m=h.querySelector(`[id="${CSS.escape(f)}"]`);m&&(m.scrollIntoView({behavior:"smooth",block:"start"}),r(f))},[e]);return a.useEffect(()=>{if(!t||o)return;const f=l.current;if(!f)return;const h=f.querySelector(`[data-toc-id="${CSS.escape(t)}"]`);if(h){const m=h.offsetTop-f.offsetTop,x=m+h.offsetHeight;(m<f.scrollTop||x>f.scrollTop+f.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[t,o]),n.length<2?null:o?s.jsx("div",{style:{width:Is,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:s.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:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):s.jsxs("div",{ref:l,style:{width:js,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),s.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:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:n.map((f,h)=>s.jsx("div",{"data-toc-id":f.id,onClick:()=>d(f.id),style:{padding:`2px 6px 2px ${(f.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:t===f.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:t===f.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:f.level<=2?500:400,transition:"color 0.1s"},title:f.text,onMouseEnter:m=>{t!==f.id&&(m.currentTarget.style.color="var(--text-primary)"),m.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:m=>{t!==f.id&&(m.currentTarget.style.color="var(--text-secondary)"),m.currentTarget.style.backgroundColor="transparent"},children:f.text},`${f.id}-${h}`))})]})}const Ls={add:{symbol:"+",color:"var(--accent-yellow)",field:"content"},del:{symbol:"−",color:"var(--accent-red)",field:"selectedText"},rep:{symbol:"⇄",color:"var(--accent-blue)",field:"content"},com:{symbol:"?",color:"var(--accent-green)",field:"content"}};function Ms({annotations:n,annCounts:e,isSent:t,onSendAll:r,onSendSingle:o,onDelete:i}){const[l,u]=a.useState(!1),p=a.useRef(null);a.useEffect(()=>{if(!l)return;const f=h=>{p.current&&!p.current.contains(h.target)&&u(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[l]);const c=a.useCallback((f,h,m)=>{const x=Ls[h],T=t(f);return s.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[s.jsx("span",{className:"plan-anno-dropdown__type",style:{color:x.color},children:x.symbol}),s.jsxs("span",{className:"plan-anno-dropdown__text",children:[m.slice(0,60),m.length>60?"...":""]}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!T&&o(f,h),disabled:T,title:T?"Already sent":"Send to terminal",style:T?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(f,h),title:"Delete",children:"×"})]},f)},[t,o,i]),d=(()=>{const f=n.additions[0],h=n.deletions[0],m=n.replacements[0],x=n.comments[0],T=f?f.content:h?h.selectedText:m?m.content:x?x.content:"";return T?T.slice(0,40)+(T.length>40?"...":""):""})();return s.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[s.jsxs("div",{className:`plan-anno-dropdown-trigger${l?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>u(f=>!f),title:e.total>0?`${e.total} annotations (${e.unsent} unsent)`:"No annotations",children:[s.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:d}),s.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),l&&s.jsxs("div",{className:"plan-anno-dropdown",children:[e.unsent>0&&s.jsx("div",{className:"plan-anno-dropdown__header",children:s.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",e.unsent,")"]})}),s.jsxs("div",{className:"plan-anno-dropdown__list",children:[n.additions.map(f=>c(f.id,"add",f.content)),n.deletions.map(f=>c(f.id,"del",f.selectedText)),n.replacements.map(f=>c(f.id,"rep",f.content)),n.comments.map(f=>c(f.id,"com",f.content)),e.total===0&&s.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const Ns={del:{className:"plan-deletion-card",icon:"",color:"var(--accent-red)"},rep:{className:"plan-replace-card",icon:"⇄",color:"var(--accent-blue)"},com:{className:"plan-comment-card",icon:"?",color:"var(--accent-green)"}};function jt({type:n,annotation:e,fontSize:t,onEdit:r,onRemove:o,onSend:i,isSent:l}){const u=Ns[n],[p,c]=a.useState(!1),[d,f]=a.useState(""),h=a.useRef(null),m=n==="del"?e.selectedText:e.content,x=a.useCallback(()=>{c(!0),f(m)},[m]),T=a.useCallback(()=>{const k=d.trim();k?r(e.id,k):o(e.id),c(!1)},[d,e.id,r,o]);return a.useEffect(()=>{p&&requestAnimationFrame(()=>{const k=h.current;k&&(k.focus(),k.selectionStart=k.selectionEnd=k.value.length)})},[p]),p?s.jsx("div",{className:u.className,children:s.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:d,onChange:k=>f(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),T()),k.key==="Escape"&&(k.preventDefault(),c(!1))},onBlur:T,rows:ut(d),style:{fontSize:`${t}px`,flex:1}})}):s.jsxs("div",{className:u.className,children:[u.icon&&s.jsx("span",{style:{color:u.color,flexShrink:0},children:u.icon}),n==="del"?s.jsx("span",{style:{flex:1,fontSize:`${t}px`,color:u.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:e.selectedText}):n==="rep"?s.jsxs("span",{style:{flex:1,fontSize:`${t}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:e.selectedText}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),s.jsx("span",{style:{color:"var(--accent-blue)"},children:e.content})]}):s.jsxs("span",{style:{flex:1,fontSize:`${t}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',e.selectedText,'"']}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),s.jsx("span",{style:{color:"var(--accent-green)"},children:e.content})]}),i&&s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!l&&i(e.id),disabled:l,title:l?"Already sent":"Send to terminal",style:l?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:x,style:{color:"var(--accent-blue)"},title:`Edit ${n==="del"?"deletion":n==="rep"?"replacement":"comment"}`,children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>o(e.id),title:`Remove ${n==="del"?"deletion":n==="rep"?"replacement":"comment"}`,children:"×"})]})}function Ds({x:n,y:e,onDelete:t,onReplace:r,onComment:o}){return s.jsxs("div",{className:"plan-selection-float",style:{top:e,left:n},children:[s.jsx("button",{className:"plan-selection-float__delete",onMouseDown:i=>{i.preventDefault(),t()},title:"Delete selection",children:"−"}),s.jsx("button",{className:"plan-selection-float__replace",onMouseDown:i=>{i.preventDefault(),r()},title:"Replace selection",children:"⇄"}),s.jsx("button",{className:"plan-selection-float__comment",onMouseDown:i=>{i.preventDefault(),o()},title:"Comment on selection",children:"?"})]})}const As=a.forwardRef(function({markdown:e,filePath:t,sessionId:r,token:o,onExecute:i,onSend:l,onRefresh:u,onClose:p,onContentSaved:c,expanded:d,readOnly:f},h){const m=$(g=>g.fontSize),[x,T]=a.useState(null),k=a.useRef(void 0),E=a.useCallback((g,y)=>{clearTimeout(k.current),T({type:g,msg:y}),k.current=setTimeout(()=>T(null),g==="ok"?2500:5e3)},[]);a.useEffect(()=>()=>clearTimeout(k.current),[]);const[b,j]=a.useState(!1),[w,L]=a.useState(""),[z,F]=a.useState(!1),B=a.useRef(null),P=$(g=>g.latency),O=`plan-edit:${r}:${t}`,N=a.useRef(void 0),C=a.useRef(void 0),S=a.useRef(!1);a.useEffect(()=>{if(!b)return;clearTimeout(N.current),N.current=setTimeout(()=>{try{localStorage.setItem(O,w)}catch{}},50),clearTimeout(C.current);const g=Math.max(200,(P??30)*3);return C.current=setTimeout(()=>{S.current||(S.current=!0,pn(o,r,t,w).then(y=>{c==null||c(w,y.mtime)}).catch(()=>{}).finally(()=>{S.current=!1}))},g),()=>{clearTimeout(N.current),clearTimeout(C.current)}},[w,b,O,o,r,t,P,c]),a.useEffect(()=>{j(!1)},[t]),a.useEffect(()=>{b&&requestAnimationFrame(()=>{var g;return(g=B.current)==null?void 0:g.focus()})},[b]);const X=a.useCallback(()=>{if(f||b)return;const g=localStorage.getItem(`plan-edit:${r}:${t}`);L(g??e),j(!0)},[f,b,e,r,t]),V=a.useCallback(()=>{j(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${t}`)},[r,t]),W=a.useCallback(async()=>{if(!z){F(!0);try{const g=await pn(o,r,t,w);c==null||c(w,g.mtime),j(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${t}`),E("ok","Saved")}catch(g){const y=g instanceof Error?g.message:"Failed to save";E("err",y)}finally{F(!1)}}},[z,o,r,t,w,c,E]),J=a.useMemo(()=>e?Tn.lexer(e):[],[e]),ee=a.useMemo(()=>e.split(`
|
|
29
|
-
`),[e]),Y=a.useMemo(()=>Es(e),[e]),I=a.useMemo(()=>{const g=new Map,y=new Map;return J.forEach((A,M)=>{if(A.type==="heading"){const oe=Fn(A.text||""),re=On(oe,y);g.set(M,re)}}),g},[J]),D=a.useRef(new Set),K=a.useRef(!1),[H,ne]=a.useState(()=>{try{const g=localStorage.getItem(Qe(r,t)),y=g?JSON.parse(g):At;return D.current=ft(y),y.replacements||(y.replacements=[]),y.comments||(y.comments=[]),y}catch{return At}});Ts({sessionId:r,filePath:t,token:o,annotations:H,annLoadedRef:K,setAnnotations:ne,baselineIdsRef:D});const[ae,xe]=a.useState(0),ze=a.useMemo(()=>{const g=D.current,y=H.additions.length+H.deletions.length+H.replacements.length+H.comments.length;let A=0;return H.additions.forEach(M=>{g.has(M.id)&&A++}),H.deletions.forEach(M=>{g.has(M.id)&&A++}),H.replacements.forEach(M=>{g.has(M.id)&&A++}),H.comments.forEach(M=>{g.has(M.id)&&A++}),{total:y,sent:A,unsent:y-A}},[H,ae]),[_,U]=a.useState(null),[Z,Q]=a.useState(""),q=a.useRef(null),[te,ye]=a.useState(null),[je,Ie]=a.useState(""),_e=a.useRef(null),[ce,Se]=a.useState(null),me=a.useRef(null),Je=a.useRef(0),Be=a.useRef(null);a.useEffect(()=>{const g=me.current;if(!g)return;let y;const A=()=>{clearTimeout(y),y=setTimeout(()=>{const M=on(r,t);if(g.scrollTop>0)try{localStorage.setItem(M,String(g.scrollTop))}catch{}else localStorage.removeItem(M)},50)};return g.addEventListener("scroll",A,{passive:!0}),()=>{clearTimeout(y),g.removeEventListener("scroll",A)}},[r,t]),a.useEffect(()=>{if(!J.length)return;const g=localStorage.getItem(on(r,t));if(!g)return;const y=Number(g),A=me.current;if(!A||(A.scrollTop=y,A.scrollTop>=y-10))return;let M;const oe=()=>{A.scrollTop=y,re.disconnect()},re=new MutationObserver(()=>{clearTimeout(M),M=setTimeout(oe,80)});re.observe(A,{childList:!0,subtree:!0});const le=setTimeout(oe,500);return()=>{clearTimeout(M),clearTimeout(le),re.disconnect()}},[r,t,J.length]),a.useEffect(()=>{_!=null&&requestAnimationFrame(()=>{var g;return(g=q.current)==null?void 0:g.focus()})},[_]),a.useEffect(()=>{te&&requestAnimationFrame(()=>{var g;return(g=_e.current)==null?void 0:g.focus()})},[te]);const Pe=a.useRef({annotations:H,activeInsert:_,insertText:Z,pendingAction:te,pendingText:je,tokens:J,filePath:t,sessionId:r,token:o});Pe.current={annotations:H,activeInsert:_,insertText:Z,pendingAction:te,pendingText:je,tokens:J,filePath:t,sessionId:r,token:o},a.useEffect(()=>()=>{const g=Pe.current;let y=g.annotations,A=!1;if(g.activeInsert!=null&&g.insertText.trim()){const M=ot(g.tokens,g.activeInsert+1);y={...y,additions:[...y.additions,{id:Ce(),afterTokenIndex:g.activeInsert,sourceLine:M,content:g.insertText.trim()}]},A=!0}if(g.pendingAction&&g.pendingText.trim()){const M=g.pendingAction,oe=g.pendingText.trim();M.type==="replace"?y={...y,replacements:[...y.replacements,{id:Ce(),tokenIndices:M.tokenIndices,startLine:M.startLine,endLine:M.endLine,selectedText:M.text,content:oe}]}:y={...y,comments:[...y.comments,{id:Ce(),tokenIndices:M.tokenIndices,startLine:M.startLine,endLine:M.endLine,selectedText:M.text,content:oe}]},A=!0}if(A){const M=JSON.stringify(y);try{localStorage.setItem(Qe(g.sessionId,g.filePath),M)}catch{}_n(g.token,g.sessionId,g.filePath,M,Date.now()).catch(()=>{})}},[]);const Me=a.useCallback(g=>{if(!Z.trim()){U(null),Q("");return}const y=ot(J,g+1);ne(A=>({...A,additions:[...A.additions,{id:Ce(),afterTokenIndex:g,sourceLine:y,content:Z.trim()}]})),U(null),Q("")},[Z,J]),Ne=a.useCallback(g=>{ne(y=>({...y,additions:y.additions.filter(A=>A.id!==g)}))},[]),et=a.useCallback((g,y)=>{ne(A=>({...A,additions:A.additions.map(M=>M.id===g?{...M,id:Ce(),content:y}:M)}))},[]),yt=a.useCallback(()=>{var g;ce&&(ne(y=>({...y,deletions:[...y.deletions,{id:Ce(),tokenIndices:ce.tokenIndices,startLine:ce.startLine,endLine:ce.endLine,selectedText:ce.text.slice(0,80)}]})),Se(null),(g=window.getSelection())==null||g.removeAllRanges())},[ce]),v=a.useCallback(g=>{var y;ce&&(ye({type:g,tokenIndices:ce.tokenIndices,startLine:ce.startLine,endLine:ce.endLine,text:ce.text.slice(0,80)}),Ie(""),Se(null),(y=window.getSelection())==null||y.removeAllRanges())},[ce]),R=a.useCallback(()=>{if(!te)return;const g=je.trim();if(!g){ye(null),Ie("");return}te.type==="replace"?ne(y=>({...y,replacements:[...y.replacements,{id:Ce(),tokenIndices:te.tokenIndices,startLine:te.startLine,endLine:te.endLine,selectedText:te.text,content:g}]})):ne(y=>({...y,comments:[...y.comments,{id:Ce(),tokenIndices:te.tokenIndices,startLine:te.startLine,endLine:te.endLine,selectedText:te.text,content:g}]})),ye(null),Ie("")},[te,je]),G=a.useCallback(g=>{ne(y=>({...y,replacements:y.replacements.filter(A=>A.id!==g)}))},[]),se=a.useCallback((g,y)=>{ne(A=>({...A,replacements:A.replacements.map(M=>M.id===g?{...M,id:Ce(),content:y}:M)}))},[]),ie=a.useCallback(g=>{ne(y=>({...y,comments:y.comments.filter(A=>A.id!==g)}))},[]),ke=a.useCallback((g,y)=>{ne(A=>({...A,comments:A.comments.map(M=>M.id===g?{...M,id:Ce(),content:y}:M)}))},[]),de=a.useCallback(g=>{ne(y=>({...y,deletions:y.deletions.filter(A=>A.id!==g)}))},[]),be=a.useCallback((g,y)=>{ne(A=>({...A,deletions:A.deletions.map(M=>M.id===g?{...M,id:Ce(),selectedText:y}:M)}))},[]),ge=a.useCallback(g=>{let y=g instanceof Element?g:g.parentElement;for(;y&&y!==me.current;){if(y.hasAttribute("data-token-index"))return y;y=y.parentElement}return null},[]),ue=a.useCallback(()=>{const g=window.getSelection();if(!g||g.isCollapsed||!me.current){Se(null);return}const y=g.toString().trim();if(!y){Se(null);return}const A=g.getRangeAt(0);if(!me.current.contains(A.commonAncestorContainer)){Se(null);return}const M=ge(A.startContainer),oe=ge(A.endContainer);if(!M||!oe){Se(null);return}const re=parseInt(M.getAttribute("data-token-index")||"0",10),le=parseInt(oe.getAttribute("data-token-index")||"0",10),Ft=[];for(let kt=Math.min(re,le);kt<=Math.max(re,le);kt++)Ft.push(kt);const Yn=ot(J,Math.min(re,le)),Xn=ot(J,Math.max(re,le)+1),Bt=A.getBoundingClientRect(),St=me.current,Pt=St.getBoundingClientRect();navigator.clipboard.writeText(y).catch(()=>{});const tt=Be.current,Wt=tt&&Date.now()-tt.time<500;Je.current=Date.now(),Se({x:(Wt?tt.x:Bt.right)-Pt.left+St.scrollLeft+6,y:(Wt?tt.y:Bt.top)-Pt.top+St.scrollTop-44,tokenIndices:Ft,startLine:Yn,endLine:Xn,text:y})},[J,ge]),we=a.useRef(void 0);a.useEffect(()=>{const g=()=>{we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{const y=window.getSelection();if(!y||y.isCollapsed||!me.current){if(Date.now()-Je.current<300)return;Se(null);return}const A=y.anchorNode;A&&me.current.contains(A)&&ue()},120)};return document.addEventListener("selectionchange",g),()=>{document.removeEventListener("selectionchange",g),we.current&&clearTimeout(we.current)}},[ue]);const Ve=$(g=>g.theme);ws(me,J,Ve);const We=a.useCallback(()=>{const g=D.current;return{additions:H.additions.filter(y=>!g.has(y.id)),deletions:H.deletions.filter(y=>!g.has(y.id)),replacements:H.replacements.filter(y=>!g.has(y.id)),comments:H.comments.filter(y=>!g.has(y.id))}},[H]),vt=a.useCallback(async()=>{const g=We();if(!ln(g))return;const y=an(g,ee),A=un(t);try{const{path:M}=await sn(o,r,A,y),oe=dn(t,M);i(oe),D.current=ft(H),xe(le=>le+1);const re=g.additions.length+g.deletions.length+g.replacements.length+g.comments.length;E("ok",`Sent ${re} annotation(s)`)}catch(M){const oe=M instanceof Error?M.message:"Failed to send";E("err",oe)}},[We,H,ee,i,t,o,r,E]),He=a.useCallback(async(g,y)=>{if(!l)return;const A={additions:[],deletions:[],replacements:[],comments:[]};if(y==="add"){const re=H.additions.find(le=>le.id===g);if(!re)return;A.additions.push(re)}else if(y==="del"){const re=H.deletions.find(le=>le.id===g);if(!re)return;A.deletions.push(re)}else if(y==="rep"){const re=H.replacements.find(le=>le.id===g);if(!re)return;A.replacements.push(re)}else{const re=H.comments.find(le=>le.id===g);if(!re)return;A.comments.push(re)}const M=an(A,ee),oe=un(t);try{const{path:re}=await sn(o,r,oe,M);l(dn(t,re)),D.current.add(g),xe(le=>le+1),E("ok","Sent 1 annotation")}catch(re){const le=re instanceof Error?re.message:"Failed to send";E("err",le)}},[l,t,H,ee,o,r,E]),Gn=a.useCallback((g,y)=>{y==="add"?Ne(g):y==="del"?de(g):y==="rep"?G(g):ie(g)},[Ne,de,G,ie]);a.useImperativeHandle(h,()=>({getSummary:()=>{const g=We();return ln(g)?"[pending annotations]":""},handleEscape:()=>b?(V(),!0):te?(R(),!0):_!=null?(Me(_),!0):!1,getScrollTop:()=>{var g;return((g=me.current)==null?void 0:g.scrollTop)??0},setScrollTop:g=>{requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=g)})}}),[We,b,V,_,Me,te,R]);const Jn=a.useMemo(()=>{const g=new Set;return H.deletions.forEach(y=>y.tokenIndices.forEach(A=>g.add(A))),g},[H.deletions]),Vn=a.useMemo(()=>{const g=new Set;return H.replacements.forEach(y=>y.tokenIndices.forEach(A=>g.add(A))),g},[H.replacements]),qn=a.useMemo(()=>{const g=new Set;return H.comments.forEach(y=>y.tokenIndices.forEach(A=>g.add(A))),g},[H.comments]),_t=a.useMemo(()=>{const g=new Map;return H.additions.forEach(y=>{const A=g.get(y.afterTokenIndex)||[];A.push(y),g.set(y.afterTokenIndex,A)}),g},[H.additions]),Ot=ze.unsent>0,wt=a.useCallback(g=>D.current.has(g),[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:t,children:t.split("/").pop()||t}),x&&s.jsx("span",{style:{fontSize:"10px",color:x.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:x.type==="err"?"pointer":void 0},title:x.type==="err"?"Click to copy":x.msg,onClick:x.type==="err"?()=>{navigator.clipboard.writeText(x.msg).catch(()=>{}),E("ok","Copied")}:void 0,children:x.msg}),b?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"pane-btn",onClick:W,disabled:z,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:z?"Saving...":"Save"}),s.jsx("button",{className:"pane-btn",onClick:V,disabled:z,title:"Cancel (Esc)",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[u&&s.jsx("button",{className:"pane-btn",onClick:u,title:"Refresh current file",children:"↻"}),!f&&s.jsx("button",{className:"pane-btn",onClick:X,title:"Edit file (double-click content)",children:"Edit"}),s.jsx("button",{className:"pane-btn",onClick:vt,disabled:!Ot,title:"Send all annotations",style:Ot?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),s.jsx(Ms,{annotations:H,annCounts:ze,isSent:wt,onSendAll:vt,onSendSingle:He,onDelete:Gn}),p&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await vt(),p()},title:"Send annotations & close file",children:"×"})]})]}),s.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[b?s.jsx("textarea",{ref:B,className:"plan-edit-textarea",style:{fontSize:`${m}px`},value:w,onChange:g=>L(g.target.value),onKeyDown:g=>{if(g.key==="s"&&(g.ctrlKey||g.metaKey)){g.preventDefault(),W();return}if(g.key==="Escape"){g.preventDefault(),V();return}},spellCheck:!1}):s.jsxs("div",{ref:me,className:`plan-anno-content md-preview${_!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${m}px`,minWidth:0},onMouseUp:g=>{Be.current={x:g.clientX,y:g.clientY,time:Date.now()},ue()},onDoubleClick:g=>{f||g.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||X()},children:[!f&&s.jsx(mn,{index:-1,active:_===-1,additions:_t.get(-1),onOpen:()=>{U(-1),Q("")},onSubmit:()=>Me(-1),onRemoveAddition:Ne,onEditAddition:et,onSendSingle:l?g=>He(g,"add"):void 0,isSent:wt,insertText:Z,setInsertText:Q,textareaRef:_===-1?q:void 0,expanded:d,alwaysShow:J.length===0,fontSize:m}),J.map((g,y)=>{const A=Cs(g);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":y,id:I.get(y),className:Jn.has(y)?"plan-block--deleted":Vn.has(y)?"plan-block--replaced":qn.has(y)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:A}}),H.deletions.filter(M=>M.tokenIndices[0]===y).map(M=>s.jsx(jt,{type:"del",annotation:M,fontSize:m,onEdit:be,onRemove:de,onSend:l?oe=>He(oe,"del"):void 0,isSent:D.current.has(M.id)},M.id)),H.replacements.filter(M=>M.tokenIndices[0]===y).map(M=>s.jsx(jt,{type:"rep",annotation:M,fontSize:m,onEdit:se,onRemove:G,onSend:l?oe=>He(oe,"rep"):void 0,isSent:D.current.has(M.id)},M.id)),H.comments.filter(M=>M.tokenIndices[0]===y).map(M=>s.jsx(jt,{type:"com",annotation:M,fontSize:m,onEdit:ke,onRemove:ie,onSend:l?oe=>He(oe,"com"):void 0,isSent:D.current.has(M.id)},M.id)),te&&te.tokenIndices[0]===y&&s.jsxs("div",{className:te.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[s.jsx("span",{style:{color:te.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:te.type==="replace"?"⇄":"?"}),s.jsx("textarea",{ref:_e,className:"plan-annotation-textarea",value:je,onChange:M=>Ie(M.target.value),onKeyDown:M=>{if(M.key==="Enter"&&(M.ctrlKey||M.metaKey)){M.preventDefault(),R();return}if(M.key==="Escape"){M.preventDefault(),R();return}},onBlur:R,placeholder:te.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:ut(je),style:{fontSize:`${m}px`,flex:1}})]}),!f&&s.jsx(mn,{index:y,active:_===y,additions:_t.get(y),onOpen:()=>{U(y),Q("")},onSubmit:()=>Me(y),onRemoveAddition:Ne,onEditAddition:et,onSendSingle:l?M=>He(M,"add"):void 0,isSent:wt,insertText:Z,setInsertText:Q,textareaRef:_===y?q:void 0,expanded:d,fontSize:m})]},y)}),!f&&ce&&s.jsx(Ds,{x:ce.x,y:ce.y,onDelete:yt,onReplace:()=>v("replace"),onComment:()=>v("comment")})]}),!b&&s.jsx(Rs,{headings:Y,scrollRef:me})]})]})});function mn({index:n,active:e,additions:t,onOpen:r,onSubmit:o,onRemoveAddition:i,onEditAddition:l,onSendSingle:u,isSent:p,insertText:c,setInsertText:d,textareaRef:f,expanded:h,alwaysShow:m,fontSize:x=14}){const[T,k]=a.useState(null),[E,b]=a.useState(""),j=a.useRef(null),w=Nt(),L=Nt();a.useEffect(()=>{T&&(w.clearUndo(),requestAnimationFrame(()=>{const N=j.current;N&&(N.focus(),N.selectionStart=N.selectionEnd=N.value.length)}))},[T]),a.useEffect(()=>{e&&L.clearUndo()},[e]);const z=a.useCallback(N=>{b(C=>(w.pushUndo(C),N))},[w]),F=a.useCallback(N=>{L.pushUndo(c),d(N)},[c,d,L]),B=a.useCallback(N=>{k(N.id),b(N.content)},[]),P=a.useCallback(()=>{if(!T)return;const N=E.trim();N?l(T,N):i(T),k(null),b("")},[T,E,l,i]),O=a.useCallback(()=>{k(null),b("")},[]);return s.jsxs("div",{className:`plan-insert-zone${m?" plan-insert-zone--empty":""}`,"data-zone-index":n,children:[t==null?void 0:t.map(N=>s.jsx("div",{className:"plan-annotation-card",children:T===N.id?s.jsx("textarea",{ref:j,className:"plan-annotation-textarea",value:E,onChange:C=>z(C.target.value),onKeyDown:C=>{if(C.key==="Enter"&&(C.ctrlKey||C.metaKey)){C.preventDefault(),P();return}if(C.key==="Escape"){C.preventDefault(),O();return}if(C.key==="Tab"){Dt(C,z);return}},onBlur:P,rows:ut(E),style:{fontSize:`${x}px`,flex:1,...h?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${x}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>B(N),title:"Double-click to edit",children:N.content}),u&&(()=>{const C=(p==null?void 0:p(N.id))??!1;return s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!C&&u(N.id),disabled:C,title:C?"Already sent":"Send to terminal",style:C?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>B(N),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(N.id),children:"×"})]})},N.id)),e?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:f,className:"plan-annotation-textarea",value:c,onChange:N=>F(N.target.value),onKeyDown:N=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)){N.preventDefault(),o();return}if(N.key==="Escape"){N.preventDefault(),o();return}if(N.key==="Tab"){Dt(N,F);return}},onBlur:o,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:ut(c),style:{fontSize:`${x}px`,...h?{minWidth:300}:void 0}})}):m&&!(t!=null&&t.length)?s.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:r,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function Le(n,e,t){const r=t?{path:t}:void 0;return pe.get(n,e,"files",r)}function $s(n,e,t,r){return new Promise((o,i)=>{const l=new FormData;for(const p of t)l.append("files",p);const u=new XMLHttpRequest;u.open("POST",`${$e}/api/sessions/${encodeURIComponent(e)}/upload`),u.setRequestHeader("Authorization",`Bearer ${n}`),u.upload.addEventListener("progress",p=>{p.lengthComputable&&r&&r(Math.round(p.loaded/p.total*100))}),u.addEventListener("load",()=>{u.status>=200&&u.status<300?o():i(new Error(`Upload failed: ${u.status}`))}),u.addEventListener("error",()=>i(new Error("Upload network error"))),u.addEventListener("abort",()=>i(new Error("Upload aborted"))),u.send(l)})}async function hn(n,e){return(await pe.get(n,e,"cwd")).cwd}async function zs(n,e,t){return pe.post(n,e,"touch",{name:t})}async function _s(n,e,t){return pe.post(n,e,"mkdir",{path:t})}async function Os(n,e,t){return pe.del(n,e,"rm",{path:t})}async function Fs(n,e){const t=await pe.getBlob(n,e,"download-cwd"),r=await t.blob(),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o;const l=t.headers.get("Content-Disposition"),u=l==null?void 0:l.match(/filename="(.+)"/);i.download=u?decodeURIComponent(u[1]):"cwd.tar.gz",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}async function Bs(n,e,t){const o=await(await pe.getBlob(n,e,"download",{path:t})).blob(),i=URL.createObjectURL(o),l=document.createElement("a");l.href=i,l.download=t.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}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 Ps(n,e){if(e==="directory")return"📁";const t=n.slice(n.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}function Pn(n){const e=new Date(n*1e3),t=r=>String(r).padStart(2,"0");return`${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}function Ws({sessionId:n,token:e,planDir:t,selectedFile:r,onSelectFile:o,onCreateFile:i,onDeleteFile:l}){const[u,p]=a.useState([]),[c,d]=a.useState(!0),[f,h]=a.useState(""),[m,x]=a.useState(!1),T=a.useRef(null),[k,E]=a.useState(()=>{if(r&&r.startsWith(t+"/")){const S=r.substring(0,r.lastIndexOf("/"));if(S.startsWith(t))return S}return t});a.useEffect(()=>{if(r&&r.startsWith(t+"/")){const S=r.substring(0,r.lastIndexOf("/"));if(S.startsWith(t)){E(S);return}}E(t)},[r,t]);const b=a.useCallback(async()=>{if(!(!e||!k)){d(!0);try{const X=(await Le(e,n,k)).files.filter(V=>V.type==="file"&&(V.name.toLowerCase().endsWith(".md")||V.name===".index.json")||V.type==="directory").sort((V,W)=>{const J=V.type==="file"&&V.name===".index.json",ee=W.type==="file"&&W.name===".index.json";return J&&!ee?-1:!J&&ee?1:V.type==="directory"&&W.type!=="directory"?-1:V.type!=="directory"&&W.type==="directory"?1:V.name.localeCompare(W.name)});p(X)}catch{p([])}finally{d(!1)}}},[e,n,k]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const S=setInterval(b,5e3);return()=>clearInterval(S)},[b]);const j=a.useCallback(()=>{const S=t.substring(0,t.lastIndexOf("/")+1);return k.startsWith(S)?k.substring(S.length):k},[t,k]),w=a.useCallback(async()=>{const S=f.trim();if(!S)return;const X=S.endsWith(".md")?S:`${S}.md`;x(!0);try{const V=await zs(e,n,`${j()}/${X}`);V.ok&&(h(""),await b(),i(V.path))}catch{}finally{x(!1)}},[f,e,n,j,b,i]),L=a.useCallback(async()=>{const S=f.trim().replace(/\/+$/,"");if(S){x(!0);try{await _s(e,n,`${j()}/${S}`),h(""),await b()}catch{}finally{x(!1)}}},[f,e,n,j,b]),z=a.useCallback(async S=>{const X=`${k}/${S.name}`,V=S.type==="directory"?`folder "${S.name}" and all its contents`:`"${S.name}"`;if(window.confirm(`Delete ${V}?`))try{await Os(e,n,X),l==null||l(X),await b()}catch{}},[e,n,k,b,l]),F=a.useCallback(S=>{E(X=>`${X}/${S}`)},[]),B=a.useCallback(()=>{k!==t&&E(S=>S.substring(0,S.lastIndexOf("/")))},[k,t]),P=t.split("/").pop()||"AiTasks",O=(()=>{const S=t.split("/");return S.length>=2?S[S.length-2]+"/":""})(),N=k===t?O+P+"/":O+P+"/"+k.substring(t.length+1)+"/",C=r?r.split("/").pop():null;return s.jsxs("div",{className:"plan-file-browser",children:[s.jsxs("div",{className:"plan-file-browser__header",children:[s.jsx("span",{className:"plan-file-browser__title",title:N,children:N}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:b,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),s.jsxs("div",{className:"plan-file-browser__create",children:[s.jsx("input",{ref:T,className:"plan-file-browser__input",value:f,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),w())},placeholder:"name",disabled:m}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:w,disabled:m||!f.trim(),title:"Create new .md file",style:f.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:L,disabled:m||!f.trim(),title:"Create new folder",style:f.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),s.jsxs("div",{className:"plan-file-browser__list",children:[c&&u.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&u.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),k!==t&&s.jsxs("div",{className:"plan-file-browser__item",onClick:B,title:"Go up to parent directory",style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),s.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),u.map(S=>{const X=`${k}/${S.name}`,V=S.type==="file"&&S.name===C,W=S.type==="directory";return s.jsxs("div",{className:`plan-file-browser__item${V?" plan-file-browser__item--active":""}`,onClick:()=>W?F(S.name):o(X),title:W?`Open folder ${S.name}`:S.name,style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",children:W?"📁":S.name===".index.json"?"🔒":"□"}),s.jsxs("span",{className:"plan-file-browser__name",children:[S.name,W?"/":""]}),!W&&s.jsx("span",{className:"plan-file-browser__size",children:Bn(S.size)}),!S.name.startsWith(".")&&s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:J=>{J.stopPropagation(),z(S)},title:`Delete ${S.name}`,children:"×"})]},S.name)})]})]})}const It={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},Hs=200;function Us(){const[n,e]=a.useState(It),t=a.useRef("lines"),r=a.useRef([]),o=a.useRef(""),i=a.useRef(""),l=a.useRef([]),u=a.useRef(0),p=a.useRef(0),c=a.useRef(null),d=a.useRef(null),f=a.useCallback(()=>{const E=t.current;e(b=>({...b,receivedBytes:u.current,...E==="lines"?{lines:[...r.current]}:{},...E==="content"?{content:i.current}:{}}))},[]),h=a.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,f()},Hs))},[f]),m=a.useCallback(E=>{t.current=E,r.current=[],o.current="",i.current="",l.current=[],u.current=0,p.current=0,d.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...It,mode:E,status:"streaming"})},[]),x=a.useCallback(E=>{u.current+=E.length;const b=t.current;if(b==="lines"){const w=d.current.decode(E,{stream:!0}).split(`
|
|
30
|
-
`);w[0]=o.current+w[0],o.current=w.pop(),w.length>0&&r.current.push(...w)}else if(b==="content"){const j=d.current.decode(E,{stream:!0});i.current+=j}else l.current.push(new Uint8Array(E));h()},[h]),T=a.useCallback(E=>{switch(E.type){case"file-stream-start":p.current=E.size,e(b=>({...b,totalSize:E.size,mtime:E.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const b=t.current;let j=r.current,w=i.current,L=null;if(b==="lines"){const z=d.current.decode(),F=o.current+z;F&&(j=[...j,F],r.current=j),o.current=""}else if(b==="content"){const z=d.current.decode();w=i.current+z,i.current=w}else{const z=l.current.reduce((B,P)=>B+P.length,0);L=new Uint8Array(z);let F=0;for(const B of l.current)L.set(B,F),F+=B.length;l.current=[]}e({status:"complete",mode:b,lines:b==="lines"?[...j]:[],content:b==="content"?w:"",buffer:b==="binary"?L:null,totalSize:p.current,receivedBytes:u.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(b=>({...b,status:"error",error:E.error}));break}},[]),k=a.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),r.current=[],o.current="",i.current="",l.current=[],u.current=0,p.current=0,d.current=null,e(It)},[]);return{state:n,startStream:m,handleChunk:x,handleControl:T,reset:k}}function gn({label:n,percent:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:n}),e!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function Ks({sessionId:n,token:e,connected:t,onRequestFileStream:r,onSendToTerminal:o}){const i=Us(),[l,u]=a.useState(!1),[p,c]=a.useState(null),[d,f]=a.useState(null),[h,m]=a.useState(""),[x,T]=a.useState(!1),[k,E]=a.useState(!1),b=a.useRef(null),j="plan-selected-file",w=a.useRef(void 0);a.useEffect(()=>{if(d)return clearTimeout(w.current),w.current=setTimeout(()=>{try{localStorage.setItem(j,d)}catch{}},50),()=>clearTimeout(w.current)},[d]);const L=a.useRef(null);a.useEffect(()=>{L.current=null;let _=!1;return T(!0),E(!1),(async()=>{let U="";try{const Z=await Le(e,n);if(_)return;if(U=Z.home||"",Z.files.find(q=>q.name==="AiTasks"&&q.type==="directory")){const q=Z.cwd+"/AiTasks";c(q);const te=localStorage.getItem(j);te&&te.startsWith(q+"/")&&f(te)}else c(null),f(null),E(!0)}catch{c(null)}finally{_||T(!1)}try{if(_)return;if(U){const Z=`${U}/.claude/plugins/installed_plugins.json`,Q=await it(e,n,Z,0);if(!_&&Q)try{const q=JSON.parse(Q.content);"ai-cli-task@moonview"in(q.plugins||q)||u(!0)}catch{u(!0)}}}catch{}})(),()=>{_=!0}},[n,e]),a.useEffect(()=>{if(!k||!t)return;const _=setInterval(async()=>{try{const U=await Le(e,n);if(U.files.find(Q=>Q.name==="AiTasks"&&Q.type==="directory")){const Q=U.cwd+"/AiTasks";c(Q),E(!1);const q=localStorage.getItem(j);q&&q.startsWith(Q+"/")&&f(q)}}catch{}},3e3);return()=>clearInterval(_)},[k,t,e,n,j]),a.useEffect(()=>(qr(n,i.handleChunk,i.handleControl),()=>Yr(n)),[n,i.handleChunk,i.handleControl]),a.useEffect(()=>{!d||!t||L.current===d&&h||(L.current=d,i.reset(),i.startStream("content"),r==null||r(d))},[d,t]);const z=a.useRef(0);a.useEffect(()=>{i.state.status==="complete"&&d&&(m(i.state.content),z.current=Date.now())},[i.state.status,i.state.content,d]),a.useEffect(()=>{if(!d||!t||!h)return;const _=setInterval(async()=>{if(z.current)try{const U=await it(e,n,d,z.current);U&&(m(U.content),z.current=U.mtime)}catch{}},3e3);return()=>clearInterval(_)},[d,t,h,e,n]);const F=a.useRef(new Map),B=a.useCallback(()=>{var U,Z;if(!d)return;const _=((Z=(U=b.current)==null?void 0:U.getScrollTop)==null?void 0:Z.call(U))??0;_>0&&F.current.set(d,_)},[d]);a.useEffect(()=>{if(!d||!h)return;const _=F.current.get(d);_!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var U,Z;(Z=(U=b.current)==null?void 0:U.setScrollTop)==null||Z.call(U,_)})})},[d,h]);const P=a.useCallback(_=>{_!==d&&(B(),f(_),m(""),L.current=null)},[d,B]),O=a.useCallback(_=>{d&&(d===_||d.startsWith(_+"/"))&&(f(null),m(""),L.current=null)},[d]),N=a.useCallback(_=>{f(_),m(""),L.current=null},[]),C=a.useCallback(_=>{_&&(o==null||o(_))},[o]),S=a.useCallback((_,U)=>{m(_),z.current=U},[]),X=a.useCallback(()=>{B(),f(null),m(""),L.current=null},[B]),V=a.useCallback(()=>{!d||!t||(L.current=null,m(""),i.reset(),i.startStream("content"),r==null||r(d),L.current=d)},[d,t,i,r]),[W,J]=a.useState(()=>{const _=localStorage.getItem(`plan-fb-width-${n}`);if(_){const U=Number(_);if(Number.isFinite(U)&&U>=60&&U<=300)return U}return 130}),ee=a.useRef(W);if(W!==ee.current){ee.current=W;try{localStorage.setItem(`plan-fb-width-${n}`,String(Math.round(W)))}catch{}}const Y=a.useCallback(_=>{_.preventDefault();const U=_.clientX,Z=W;document.body.classList.add("resizing-panes");const Q=te=>{const ye=te.clientX-U;J(Math.min(300,Math.max(60,Z+ye)))},q=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",Q),document.removeEventListener("mouseup",q)};document.addEventListener("mousemove",Q),document.addEventListener("mouseup",q)},[W]),I=a.useMemo(()=>{if(!p||!d||!d.startsWith(p+"/"))return null;const _=d.substring(p.length+1),U=_.indexOf("/");if(U<0)return null;const Z=_.substring(0,U);return!Z||Z.startsWith(".")?null:{name:Z,dir:`${p}/${Z}`}},[p,d]),D=I==null?void 0:I.dir,[K,H]=a.useState(null),ne=a.useRef(0);a.useEffect(()=>{H(null),ne.current=0},[D]),a.useEffect(()=>{if(!D||!t)return;let _=!1;const U=async()=>{try{const Q=await it(e,n,`${D}/.index.json`,ne.current||void 0);if(_)return;if(Q){ne.current=Q.mtime;try{const q=JSON.parse(Q.content);H({status:q.status||"draft",phase:q.phase||"",type:q.type||"",completed_steps:q.completed_steps||0,title:q.title||""})}catch{}}}catch{}};U();const Z=setInterval(U,3e3);return()=>{_=!0,clearInterval(Z)}},[D,t,e,n]);const[ae,xe]=a.useState(null);a.useEffect(()=>{xe(null)},[D]),a.useEffect(()=>{if(!D||!t)return;let _=!1;const U=async()=>{try{const Q=await it(e,n,`${D}/.auto-signal`);if(_)return;if(Q)try{const q=JSON.parse(Q.content);xe({step:q.step,result:q.result,next:q.next,iteration:q.iteration})}catch{xe(null)}}catch{_||xe(null)}};U();const Z=setInterval(U,2e3);return()=>{_=!0,clearInterval(Z)}},[D,t,e,n]);const ze=a.useCallback(()=>{!I||!o||o(`/moonview:auto AiTasks/${I.name}`)},[I,o]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[l&&s.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:[s.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),s.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{o&&o("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),u(!1)},children:"Install"}),s.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>u(!1),children:"×"})]}),s.jsxs("div",{className:"plan-overlay-body",children:[p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:W,flexShrink:0,overflow:"hidden"},children:s.jsx(Ws,{sessionId:n,token:e,planDir:p,selectedFile:d,onSelectFile:P,onCreateFile:N,onDeleteFile:O})}),s.jsx("div",{onMouseDown:Y,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)"}})]}),s.jsx("div",{className:"plan-overlay-center",children:x?s.jsx(gn,{label:"Loading AiTasks/..."}):k?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),s.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",s.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/moonview:init <name>"})," in the terminal to create a task"]})]}):d&&!h&&(i.state.status==="streaming"||i.state.status==="idle")?s.jsx(gn,{label:`Loading ${d.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):d?s.jsx(As,{ref:b,markdown:h,filePath:d,sessionId:n,token:e,onExecute:C,onSend:o,onRefresh:V,onClose:X,onContentSaved:S,readOnly:d.endsWith("/.index.json")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]}),I&&K&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--border)",fontSize:11,flexShrink:0,minHeight:22},children:[s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:500},title:K.title,children:I.name}),s.jsx("span",{style:{color:K.status==="complete"?"var(--accent-green)":K.status==="executing"||K.status==="review"?"var(--accent-blue)":K.status==="blocked"?"var(--accent-red)":K.status==="cancelled"?"var(--text-secondary)":"var(--accent-yellow)",fontWeight:500},children:K.status}),K.phase&&s.jsxs("span",{style:{color:"var(--text-secondary)"},children:["(",K.phase,")"]}),ae?s.jsxs("span",{style:{color:"var(--accent-yellow)"},children:[ae.step,":",ae.result," → ",ae.next,ae.iteration!=null&&` #${ae.iteration}`]}):s.jsx("button",{className:"pane-btn",onClick:ze,disabled:!t||K.status==="complete"||K.status==="cancelled",style:{color:"var(--accent-green)",fontWeight:500,fontSize:11,...!t||K.status==="complete"||K.status==="cancelled"?{opacity:.4}:{}},title:"Start auto mode for this task",children:"Auto ▶"}),K.completed_steps>0&&s.jsxs("span",{style:{color:"var(--text-secondary)",marginLeft:"auto"},children:["step ",K.completed_steps]})]})]})}async function Gs(n,e,t={}){const r={};return t.page&&(r.page=String(t.page)),t.limit&&(r.limit=String(t.limit)),t.file&&(r.file=t.file),t.all&&(r.all="true"),t.branch&&(r.branch=t.branch),pe.get(e,n,"git-log",r)}async function Js(n,e,t,r){const o={commit:t};return r&&(o.file=r),(await pe.get(e,n,"git-diff",o)).diff}async function Vs(n,e){return pe.get(e,n,"git-branches")}const pt=["#0085d9","#d9008f","#3fb950","#d98500","#a300d9","#56d4dd","#e05050","#00d9a3"];function qs(n){const e=new Map;if(n.length===0)return e;const t=[],r=[];let o=1;const i=new Map,l=new Map;function u(p){for(let d=0;d<t.length;d++)if(t[d]===null)return t[d]=p,r[d]=d===0?0:o++%pt.length,d;const c=t.length;return t.push(p),r[c]=c===0?0:o++%pt.length,c}for(const p of n){const{hash:c,parents:d}=p,f=d.length>1,h=t.indexOf(c)!==-1;let m=h?t.indexOf(c):u(c);const x=r[m],T=[],k=[];for(let b=0;b<t.length;b++)b!==m&&t[b]===c&&(T.push({fromLane:b,toLane:m,colorIndex:r[b],type:"merge-in"}),t[b]=null);if(d.length===0)t[m]=null;else{t[m]=d[0];for(let b=1;b<d.length;b++){const j=d[b],w=t.indexOf(j);if(w!==-1)T.push({fromLane:w,toLane:m,colorIndex:r[w],type:"merge-in"});else if(i.has(j)){const L=i.get(j),z=l.get(j);T.push({fromLane:L,toLane:m,colorIndex:z,type:"merge-in"})}else{const L=u(j);k.push(L),T.push({fromLane:m,toLane:L,colorIndex:r[L],type:"branch-out"})}}}for(;t.length>0&&t[t.length-1]===null;)t.pop(),r.pop();const E=[];for(let b=0;b<t.length;b++)t[b]!==null&&E.push({lane:b,colorIndex:r[b]});i.set(c,m),l.set(c,x),e.set(c,{lane:m,activeLanes:E,connections:T,colorIndex:x,isMerge:f,newLanes:k,wasExpected:h})}return e}function Ys(n){const e=Date.now()-new Date(n).getTime(),t=Math.floor(e/6e4);if(t<1)return"now";if(t<60)return`${t}m`;const r=Math.floor(t/60);if(r<24)return`${r}h`;const o=Math.floor(r/24);if(o<30)return`${o}d`;const i=Math.floor(o/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}const mt=20,Ae=32,Xs=4,Zs=5,Te=Ae/2;function Re(n){return n*mt+mt/2}function qe(n){return pt[n%pt.length]}function Qs(n){if(n.type==="branch-out"){const e=Re(n.fromLane),t=Re(n.toLane);if(e===t)return`M ${e} ${Te} L ${e} ${Ae}`;const r=(Ae-Te)*.8;return`M ${e} ${Te} C ${e} ${Te+r}, ${t} ${Ae-r}, ${t} ${Ae}`}else{const e=Re(n.fromLane),t=Re(n.toLane);if(e===t)return`M ${e} 0 L ${e} ${Te}`;const r=Te*.8;return`M ${e} 0 C ${e} ${r}, ${t} ${Te-r}, ${t} ${Te}`}}const eo=a.memo(function({laneNode:e,maxLanes:t}){const r=t*mt,o=e.newLanes;return s.jsxs("svg",{width:r,height:Ae,style:{flexShrink:0,display:"block"},children:[e.activeLanes.map(i=>o.includes(i.lane)?null:s.jsx("line",{x1:Re(i.lane),y1:0,x2:Re(i.lane),y2:Ae,stroke:qe(i.colorIndex),strokeWidth:2,strokeLinecap:"round"},`active-${i.lane}`)),e.connections.map((i,l)=>s.jsx("path",{d:Qs(i),stroke:qe(i.colorIndex),strokeWidth:2,fill:"none",strokeLinecap:"round"},`conn-${l}`)),e.wasExpected&&!e.activeLanes.some(i=>i.lane===e.lane)&&!o.includes(e.lane)&&s.jsx("line",{x1:Re(e.lane),y1:0,x2:Re(e.lane),y2:Te,stroke:qe(e.colorIndex),strokeWidth:2,strokeLinecap:"round"}),e.isMerge?s.jsx("circle",{cx:Re(e.lane),cy:Te,r:Zs,fill:"var(--bg-primary)",stroke:qe(e.colorIndex),strokeWidth:2}):s.jsx("circle",{cx:Re(e.lane),cy:Te,r:Xs,fill:qe(e.colorIndex)})]})}),to={head:{bg:"var(--accent-red)",color:"#fff"},branch:{bg:"var(--accent-blue)",color:"#fff"},remote:{bg:"var(--accent-purple)",color:"#fff"},tag:{bg:"var(--accent-green)",color:"#fff"}};function no({refs:n,fontSize:e}){if(n.length===0)return null;const t=e-4;return s.jsx(s.Fragment,{children:n.map((r,o)=>{const i=to[r.type];return s.jsx("span",{style:{display:"inline-block",padding:"0 4px",borderRadius:3,fontSize:t,lineHeight:`${t+6}px`,backgroundColor:i.bg,color:i.color,whiteSpace:"nowrap",flexShrink:0,fontFamily:"'JetBrains Mono', monospace"},children:r.type==="head"&&r.name!=="HEAD"?`HEAD → ${r.name}`:r.name},o)})})}function ro(n){const e=n.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return e?[parseInt(e[1],10),parseInt(e[2],10)]:[1,1]}const so=a.memo(function({diff:e,fontSize:t}){if(!e.trim())return s.jsx("div",{style:{padding:8,color:"var(--text-secondary)",fontSize:t},children:"No diff available"});const r=[];let o=null,i=1,l=1;for(const p of e.split(`
|
|
31
|
-
`))if(p.startsWith("@@")){const[c,d]=ro(p);i=c,l=d,o={header:p,lines:[]},r.push(o)}else p.startsWith("diff ")||p.startsWith("index ")||p.startsWith("---")||p.startsWith("+++")||o&&(p.startsWith("+")?o.lines.push({type:"add",text:p,oldNum:null,newNum:l++}):p.startsWith("-")?o.lines.push({type:"del",text:p,oldNum:i++,newNum:null}):o.lines.push({type:"context",text:p,oldNum:i++,newNum:l++}));const u=t*2.6;return s.jsx("div",{style:{fontSize:t,fontFamily:"'JetBrains Mono', monospace",overflow:"auto"},children:r.map((p,c)=>s.jsxs("div",{children:[s.jsx("div",{style:{padding:"2px 8px",paddingLeft:u*2+12,backgroundColor:"var(--bg-secondary)",color:"var(--accent-cyan)",fontSize:t-1,borderTop:c>0?"1px solid var(--border)":void 0},children:p.header}),p.lines.map((d,f)=>s.jsxs("div",{style:{display:"flex",whiteSpace:"pre",backgroundColor:d.type==="add"?"rgba(63, 185, 80, 0.12)":d.type==="del"?"rgba(248, 81, 73, 0.12)":"transparent"},children:[s.jsx("span",{style:{display:"inline-block",width:u,textAlign:"right",paddingRight:4,color:"var(--text-secondary)",opacity:.5,flexShrink:0,userSelect:"none"},children:d.oldNum??""}),s.jsx("span",{style:{display:"inline-block",width:u,textAlign:"right",paddingRight:6,color:"var(--text-secondary)",opacity:.5,flexShrink:0,userSelect:"none",borderRight:"1px solid var(--border)",marginRight:6},children:d.newNum??""}),s.jsx("span",{style:{flex:1,color:d.type==="add"?"var(--accent-green)":d.type==="del"?"var(--accent-red)":"var(--text-primary)"},children:d.text})]},f))]},c))})}),oo=a.memo(function({commit:e,sessionId:t,token:r,fontSize:o,laneNode:i,maxLanes:l}){const[u,p]=a.useState(!1),[c,d]=a.useState(null),[f,h]=a.useState(""),[m,x]=a.useState(!1),T=a.useRef(c);T.current=c;const k=a.useCallback(async w=>{if(T.current===w){d(null);return}d(w),x(!0);try{const L=await Js(t,r,e.hash,w);h(L)}catch{h("Failed to load diff")}finally{x(!1)}},[t,r,e.hash]),E=o-2,b=o-4,j=l*mt;return s.jsxs("div",{children:[s.jsxs("div",{onClick:()=>p(!u),style:{padding:"2px 8px",cursor:"pointer",display:"flex",flexDirection:"row",alignItems:"center",gap:4,height:Ae},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="var(--bg-hover)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="transparent"},children:[i&&l>0&&s.jsx(eo,{laneNode:i,maxLanes:l}),s.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:6},children:[s.jsx(no,{refs:e.refs,fontSize:o}),s.jsx("span",{style:{fontSize:E,color:"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:e.message}),s.jsxs("span",{style:{fontSize:b,color:"var(--text-secondary)",flexShrink:0,whiteSpace:"nowrap"},children:[e.author.split(" ")[0]," · ",Ys(e.date)]}),s.jsx("span",{style:{fontSize:b,color:"var(--accent-yellow)",fontFamily:"'JetBrains Mono', monospace",flexShrink:0,opacity:.6},children:e.shortHash}),s.jsx("span",{style:{fontSize:b,color:"var(--text-secondary)",flexShrink:0},children:u?"▼":"▶"})]})]}),u&&s.jsx("div",{style:{padding:"0 10px 6px",marginLeft:j+10},children:e.files.length===0?s.jsx("div",{style:{fontSize:E,color:"var(--text-secondary)",padding:"4px 0"},children:"No files changed"}):e.files.map(w=>s.jsxs("div",{children:[s.jsxs("div",{onClick:()=>k(w.path),style:{display:"flex",alignItems:"center",gap:6,padding:"2px 4px",cursor:"pointer",fontSize:o,borderRadius:3},onMouseEnter:L=>{L.currentTarget.style.backgroundColor="var(--bg-hover)"},onMouseLeave:L=>{L.currentTarget.style.backgroundColor="transparent"},children:[s.jsxs("span",{style:{fontSize:b,color:"var(--accent-green)",fontFamily:"'JetBrains Mono', monospace",minWidth:28,textAlign:"right"},children:["+",w.additions]}),s.jsxs("span",{style:{fontSize:b,color:"var(--accent-red)",fontFamily:"'JetBrains Mono', monospace",minWidth:28,textAlign:"right"},children:["-",w.deletions]}),s.jsx("span",{style:{color:c===w.path?"var(--accent-blue)":"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:w.path})]}),c===w.path&&s.jsx("div",{style:{margin:"2px 0 4px",border:"1px solid var(--border)",borderRadius:4,overflow:"hidden",maxHeight:400,overflowY:"auto"},children:m?s.jsx("div",{style:{padding:8,color:"var(--text-secondary)",fontSize:o},children:"Loading..."}):s.jsx(so,{diff:f,fontSize:o})})]},w.path))})]})}),ao=a.memo(function({sessionId:e,token:t}){const r=$(I=>I.fontSize),[o,i]=a.useState([]),[l,u]=a.useState(1),[p,c]=a.useState(!1),[d,f]=a.useState(!1),[h,m]=a.useState(null),[x,T]=a.useState(""),[k,E]=a.useState(""),[b,j]=a.useState(!1),[w,L]=a.useState([]),[z,F]=a.useState(""),[B,P]=a.useState(""),O=a.useRef(0),N=a.useRef(null);a.useEffect(()=>{Vs(e,t).then(({current:I,branches:D})=>{F(I),L(D)}).catch(()=>{})},[e,t]);const C=a.useCallback(async(I,D,K,H,ne)=>{f(!0),m(null);try{const ae=await Gs(e,t,{page:I,file:D||void 0,all:H||void 0,branch:ne||void 0});ae.error&&m(ae.error),i(xe=>K?[...xe,...ae.commits]:ae.commits),c(ae.hasMore),u(I)}catch(ae){m(ae instanceof Error?ae.message:"Failed to load")}finally{f(!1)}},[e,t]);a.useEffect(()=>{C(1,x,!1,b,B)},[x,b,B,C]);const S=a.useCallback(I=>{const D=I.target.value;E(D),O.current&&clearTimeout(O.current),O.current=window.setTimeout(()=>T(D),300)},[]);a.useEffect(()=>()=>{O.current&&clearTimeout(O.current)},[]);const X=a.useCallback(()=>{!d&&p&&C(l+1,x,!0,b,B)},[d,p,l,x,b,B,C]),V=a.useRef(0),W=a.useCallback(()=>{V.current||(V.current=requestAnimationFrame(()=>{V.current=0;const I=N.current;!I||d||!p||I.scrollTop+I.clientHeight>=I.scrollHeight-50&&X()}))},[d,p,X]);a.useEffect(()=>()=>{V.current&&cancelAnimationFrame(V.current)},[]);const J=a.useMemo(()=>qs(o),[o]),ee=a.useMemo(()=>{let I=0;for(const D of J.values()){let K=D.lane+1;for(let H=0;H<D.activeLanes.length;H++){const ne=D.activeLanes[H].lane+1;ne>K&&(K=ne)}K>I&&(I=K)}return Math.min(I,15)},[J]),Y=r-2;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",gap:6,borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[s.jsxs("select",{value:b?"__all__":B,onChange:I=>{const D=I.target.value;D==="__all__"?(j(!0),P("")):(j(!1),P(D))},style:{fontSize:Y,padding:"1px 2px",border:"1px solid var(--border)",borderRadius:3,backgroundColor:"var(--bg-primary)",color:"var(--text-primary)",outline:"none",flexShrink:0,maxWidth:130},title:"Select branch",children:[s.jsx("option",{value:"",children:z||"HEAD"}),w.filter(I=>I!==z).map(I=>s.jsx("option",{value:I,children:I},I)),s.jsx("option",{value:"__all__",children:"-- All branches --"})]}),s.jsx("input",{type:"text",value:k,onChange:S,placeholder:"Filter by file...",style:{flex:1,fontSize:Y,padding:"2px 6px",border:"1px solid var(--border)",borderRadius:3,backgroundColor:"var(--bg-primary)",color:"var(--text-primary)",outline:"none",minWidth:0}})]}),h&&s.jsx("div",{style:{padding:"4px 8px",fontSize:Y,color:"var(--accent-red)",backgroundColor:"var(--bg-secondary)"},children:h}),s.jsxs("div",{ref:N,onScroll:W,style:{flex:1,overflowY:"auto",minHeight:0},children:[o.map(I=>s.jsx(oo,{commit:I,sessionId:e,token:t,fontSize:r,laneNode:J.get(I.hash),maxLanes:ee},I.hash)),d&&s.jsx("div",{style:{padding:12,textAlign:"center",color:"var(--text-secondary)",fontSize:r},children:"Loading..."}),!d&&o.length===0&&!h&&s.jsx("div",{style:{padding:12,textAlign:"center",color:"var(--text-secondary)",fontSize:r},children:"No commits found"}),!d&&p&&s.jsx("div",{style:{padding:8,textAlign:"center"},children:s.jsx("button",{className:"pane-btn",onClick:X,style:{fontSize:Y},children:"Load more"})})]})]})});async function io(n,e){try{return(await pe.get(n,e,"draft")).content??""}catch{return""}}async function xn(n,e,t){try{await pe.put(n,e,"draft",{content:t})}catch{}}const zt="chat-history",bn=50;function Wn(){try{const n=localStorage.getItem(zt);return n?JSON.parse(n):[]}catch{return[]}}function lo(n){const t=Wn().filter(r=>r.text!==n);t.unshift({text:n,ts:Date.now()}),t.length>bn&&(t.length=bn),localStorage.setItem(zt,JSON.stringify(t))}const yn=[{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:"/moonview:ai-cli-task",desc:"Task lifecycle management (13 skills)"},{cmd:"/moonview:init",desc:"Initialize task module + branch"},{cmd:"/moonview:plan",desc:"Generate implementation plan"},{cmd:"/moonview:research",desc:"Collect external references"},{cmd:"/moonview:check",desc:"Check feasibility (post-plan/mid/post-exec)"},{cmd:"/moonview:verify",desc:"Run domain-adapted tests"},{cmd:"/moonview:exec",desc:"Execute implementation plan"},{cmd:"/moonview:merge",desc:"Merge task branch to main"},{cmd:"/moonview:report",desc:"Generate completion report"},{cmd:"/moonview:auto",desc:"Autonomous full lifecycle loop"},{cmd:"/moonview:cancel",desc:"Cancel task + optional cleanup"},{cmd:"/moonview:list",desc:"Query task status (read-only)"},{cmd:"/moonview:annotate",desc:"Process Plan panel annotations"},{cmd:"/moonview:summarize",desc:"Regenerate context summary"}],co=a.forwardRef(function({onSend:e,onContentChange:t,sessionId:r,token:o},i){const l=$(v=>v.fontSize),[u,p]=a.useState(""),c=a.useRef(null),d=a.useRef(void 0),f=a.useRef(!1),h=a.useRef(!1),{pushUndo:m,popUndo:x}=Nt(),T=a.useRef(u);T.current=u;const k=a.useCallback(()=>m(T.current),[m]),[E,b]=a.useState(!1),[j,w]=a.useState(""),[L,z]=a.useState(0),[F,B]=a.useState(!1),[P,O]=a.useState([]),[N,C]=a.useState(0),[S,X]=a.useState(""),V=a.useRef(null),W=a.useMemo(()=>{if(!S)return P;const v=S.toLowerCase();return P.filter(R=>R.text.toLowerCase().includes(v))},[P,S]),[J,ee]=a.useState(!1),[Y,I]=a.useState(""),[D,K]=a.useState(""),[H,ne]=a.useState(0),[ae,xe]=a.useState([]),[ze,_]=a.useState(!1),U=a.useRef(""),Z=a.useRef(null),Q=a.useMemo(()=>{if(!j)return yn;const v=j.toLowerCase();return yn.filter(R=>R.cmd.toLowerCase().includes(v)||R.desc.toLowerCase().includes(v))},[j]),q=a.useMemo(()=>{let v=ae;if(Y){const R=Y.toLowerCase();v=v.filter(G=>G.name.toLowerCase().includes(R))}return[...v].sort((R,G)=>R.type==="directory"&&G.type!=="directory"?-1:R.type!=="directory"&&G.type==="directory"?1:R.name.localeCompare(G.name))},[ae,Y]),te=$(v=>v.latency),ye=`chat-draft-${r}`,je=a.useRef(!1),Ie=a.useRef(void 0);a.useEffect(()=>{try{const R=localStorage.getItem(ye);R&&!h.current&&p(R)}catch{}let v=!1;return io(o,r).then(R=>{if(v||h.current){f.current=!0;return}if(R){p(R);try{localStorage.setItem(ye,R)}catch{}}f.current=!0}).catch(()=>{f.current=!0}),()=>{v=!0}},[o,r,ye]),a.useEffect(()=>{if(!f.current)return;d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{try{localStorage.setItem(ye,u)}catch{}},50),Ie.current&&clearTimeout(Ie.current);const v=Math.max(200,(te??30)*3);return Ie.current=setTimeout(()=>{je.current||(je.current=!0,xn(o,r,u).catch(()=>{}).finally(()=>{je.current=!1}))},v),()=>{d.current&&clearTimeout(d.current),Ie.current&&clearTimeout(Ie.current)}},[u,o,r,te,ye]),a.useEffect(()=>{var v;(v=c.current)==null||v.focus()},[]),a.useEffect(()=>{if(!J)return;let v=!1;return _(!0),(async()=>{try{if(D){if(!U.current){const se=await Le(o,r);if(v)return;U.current=se.cwd}const R=`${U.current}/${D.replace(/\/$/,"")}`,G=await Le(o,r,R);if(v)return;xe(G.files)}else{const R=await Le(o,r);if(v)return;U.current=R.cwd,xe(R.files)}_(!1)}catch{if(v)return;xe([]),_(!1)}})(),()=>{v=!0}},[J,D,o,r]),a.useEffect(()=>{if(!J||!Z.current)return;const v=Z.current.querySelector(".file-item--active");v==null||v.scrollIntoView({block:"nearest"})},[H,J]);const _e=a.useCallback(()=>{const v=T.current.trim();if(v){lo(v),e(v),p("");try{localStorage.removeItem(ye)}catch{}xn(o,r,"").catch(()=>{})}},[e,o,r,ye]),ce=a.useCallback(v=>{k(),p(v),h.current=!0},[k]),Se=a.useCallback(v=>{const R=c.current;k();const G=T.current;if(R){const se=R.selectionStart,ie=R.selectionEnd,ke=G.slice(0,se)+v+G.slice(ie);p(ke);const de=se+v.length;requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=de,R.focus()})}else p(G+v)},[k]);a.useImperativeHandle(i,()=>({send:_e,fillContent:ce,insertAtCursor:Se}),[_e,ce,Se]),a.useEffect(()=>{t==null||t(u.trim().length>0)},[u,t]);const me=a.useCallback(()=>{const v=c.current;if(!v)return;const{selectionStart:R,selectionEnd:G}=v;if(R!==G){const se=v.value.substring(R,G);se&&navigator.clipboard.writeText(se).catch(()=>{})}},[]),Je=a.useCallback(()=>{const v=Wn();b(!1),w("");const R=c.current;if(R){const G=R.selectionStart,se=u.slice(0,G),ie=u.slice(G),ke=se.match(/(?:^|\s)(\/history)\s*$/);if(ke){const de=se.length-ke[1].length;p(u.slice(0,de)+ie)}}v.length!==0&&(O(v),C(0),X(""),B(!0))},[u]),Be=a.useCallback(v=>{k(),p(v.text),B(!1),requestAnimationFrame(()=>{const R=c.current;R&&(R.selectionStart=R.selectionEnd=v.text.length,R.focus())})},[k]),Pe=a.useCallback(v=>{const R=W[v];if(!R)return;const G=P.filter(ie=>ie.ts!==R.ts||ie.text!==R.text);O(G),localStorage.setItem(zt,JSON.stringify(G));const se=S?G.filter(ie=>ie.text.toLowerCase().includes(S.toLowerCase())):G;N>=se.length&&C(Math.max(0,se.length-1))},[W,P,N,S]);a.useEffect(()=>{if(!F||!V.current)return;const v=V.current.querySelector(".history-item--active");v==null||v.scrollIntoView({block:"nearest"})},[N,F]);const Me=a.useCallback(v=>{if(v==="/history"){Je();return}const R=c.current;if(!R)return;k();const G=R.selectionStart,se=u.slice(0,G),ie=u.slice(G),de=se.lastIndexOf(`
|
|
32
|
-
`)+1,ge=se.slice(de).match(/\/[a-zA-Z:-]*$/);if(ge){const ue=de+(ge.index??0),we=v+" ",Ve=u.slice(0,ue)+we+ie;p(Ve);const We=ue+we.length;requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=We,R.focus()})}else{const ue=se+v+ie;p(ue);const we=G+v.length;requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=we,R.focus()})}b(!1),w(""),
|
|
33
|
-
`),de=se.slice(ie+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(de)b(!0),w(de[1]),z(0),ee(!1);else{b(!1);const be=se.match(/@([a-zA-Z0-9_.\-/]*)$/);if(be){const ge=be[1],ue=ge.lastIndexOf("/"),we=ue>=0?ge.slice(0,ue+1):"",Ve=ue>=0?ge.slice(ue+1):ge;I(Ve),ne(0),K(we),ee(!0)}else ee(!1)}},[F]),yt=a.useCallback(v=>{if(E&&Q.length>0){if(v.key==="ArrowDown"){v.preventDefault(),z(R=>(R+1)%Q.length);return}if(v.key==="ArrowUp"){v.preventDefault(),z(R=>(R-1+Q.length)%Q.length);return}if(v.key==="Enter"||v.key==="Tab"){v.preventDefault(),Me(Q[L].cmd);return}if(v.key==="Escape"){v.preventDefault(),b(!1);return}}if(J&&q.length>0){if(v.key==="ArrowDown"){v.preventDefault(),ne(R=>(R+1)%q.length);return}if(v.key==="ArrowUp"){v.preventDefault(),ne(R=>(R-1+q.length)%q.length);return}if(v.key==="Tab"||v.key==="Enter"){v.preventDefault(),Ne(q[H]);return}if(v.key==="Escape"){v.preventDefault(),ee(!1);return}}if(F&&W.length>0){if(v.key==="ArrowDown"){v.preventDefault(),C(R=>(R+1)%W.length);return}if(v.key==="ArrowUp"){v.preventDefault(),C(R=>(R-1+W.length)%W.length);return}if(v.key==="Enter"){v.preventDefault(),Be(W[N]);return}if(v.key==="Delete"||v.key==="Backspace"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),Pe(N);return}if(v.key==="Escape"){v.preventDefault(),B(!1);return}}if(v.key==="Tab"){Dt(v,p,m);return}v.key==="Enter"&&(v.ctrlKey||v.metaKey)&&(v.preventDefault(),_e())},[_e,E,Q,L,Me,J,q,H,Ne,m,x,F,W,N,Be,Pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[E&&Q.length>0&&s.jsx("div",{className:"slash-dropdown",children:Q.map((v,R)=>s.jsxs("div",{className:`slash-item${R===L?" slash-item--active":""}`,onMouseDown:G=>{G.preventDefault(),Me(v.cmd)},onMouseEnter:()=>z(R),children:[s.jsx("span",{className:"slash-cmd",children:v.cmd}),s.jsx("span",{className:"slash-desc",children:v.desc})]},v.cmd))}),J&&(ze||q.length>0)&&s.jsx("div",{className:"file-dropdown",ref:Z,children:ze?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):q.map((v,R)=>s.jsxs("div",{className:`file-item${R===H?" file-item--active":""}`,onMouseDown:G=>{G.preventDefault(),Ne(v)},onMouseEnter:()=>ne(R),children:[s.jsx("span",{className:"file-icon",children:v.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:v.name})]},v.name))}),F&&s.jsx("div",{className:"history-dropdown",ref:V,children:W.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):W.map((v,R)=>s.jsxs("div",{className:`history-item${R===N?" history-item--active":""}`,onMouseDown:G=>{G.preventDefault(),Be(v)},onMouseEnter:()=>C(R),children:[s.jsx("span",{className:"history-text",children:v.text.length>120?v.text.slice(0,120)+"...":v.text}),s.jsx("span",{className:"history-time",children:new Date(v.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:G=>{G.preventDefault(),G.stopPropagation(),Pe(R)},title:"Delete (Del key)",children:"×"})]},`${v.ts}-${R}`))}),s.jsx("textarea",{ref:c,className:"md-editor-textarea",value:u,onChange:et,onKeyDown:yt,onMouseUp:me,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${l}px`}})]})});function uo({token:n,sessionId:e,onClose:t}){const[r,o]=a.useState([]),[i,l]=a.useState(""),[u,p]=a.useState([]),[c,d]=a.useState(!0),[f,h]=a.useState(!1),m=a.useRef(null);a.useEffect(()=>{let b=!1;return(async()=>{try{const j=await Le(n,e);b||(l(j.cwd),o(j.files))}catch{b||t()}finally{b||d(!1)}})(),()=>{b=!0}},[n,e,t]),a.useEffect(()=>{const b=L=>{L.key==="Escape"&&t()},j=L=>{m.current&&!m.current.contains(L.target)&&t()};document.addEventListener("keydown",b);const w=setTimeout(()=>document.addEventListener("mousedown",j),50);return()=>{document.removeEventListener("keydown",b),document.removeEventListener("mousedown",j),clearTimeout(w)}},[t]);const x=a.useCallback(async b=>{d(!0);try{const j=await Le(n,e,b);p(w=>[...w,i]),l(b),o(j.files)}catch{}finally{d(!1)}},[n,e,i]),T=a.useCallback(async()=>{if(u.length===0)return;const b=u[u.length-1];d(!0);try{const j=await Le(n,e,b);p(w=>w.slice(0,-1)),l(b),o(j.files)}catch{}finally{d(!1)}},[n,e,u]),k=a.useCallback(async b=>{try{await Bs(n,e,b)}catch(j){alert(`Download failed: ${j instanceof Error?j.message:"Unknown error"}`)}},[n,e]),E=a.useCallback(async()=>{h(!0),t();try{await Fs(n,e)}catch(b){alert(`Download failed: ${b instanceof Error?b.message:"Unknown error"}`)}finally{h(!1)}},[n,e,t]);return s.jsxs("div",{ref:m,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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[u.length>0&&s.jsx("button",{className:"pane-btn",onClick:T,disabled:c,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),s.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:i.split("/").slice(-2).join("/")||i}),s.jsx("button",{className:"pane-btn",onClick:t,style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:c?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(b=>s.jsxs("div",{onClick:()=>{const j=i+"/"+b.name;b.type==="directory"?x(j):k(j)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{flexShrink:0,fontSize:13},children:b.type==="directory"?"📁":Ps(b.name,b.type)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.name}),b.type==="directory"?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):b.size!=null?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:Bn(b.size)}):null]},b.name))}),s.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{className:"pane-btn",onClick:E,disabled:f,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:f?"Downloading...":"Download All (tar.gz)"})})]})}function vn(n,e,{containerRef:t,axis:r,offset:o=0,min:i,max:l,invert:u=!1,bodyClass:p}){const[c,d]=a.useState(()=>{const m=localStorage.getItem(n);if(m){const x=Number(m);if(Number.isFinite(x)&&x>=i&&x<=l)return x}return e}),f=a.useRef(c);if(c!==f.current){f.current=c;try{localStorage.setItem(n,String(Math.round(c)))}catch{}}const h=a.useCallback(m=>{m.preventDefault();const x=t.current;if(!x)return;const T=x.getBoundingClientRect(),k=r==="x"?T.width:T.height-o,E=r==="x"?T.left:T.top+o;document.body.classList.add(p);const b=w=>{let z=((r==="x"?w.clientX:w.clientY)-E)/k*100;u&&(z=100-z),d(Math.min(l,Math.max(i,z)))},j=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",j)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",j)},[t,r,o,i,l,u,p]);return[c,h]}const fo=600,Ke=typeof window<"u"?window.matchMedia(`(max-width: ${fo-1}px)`):null;function po(){const[n,e]=a.useState(()=>(Ke==null?void 0:Ke.matches)??!1);return a.useEffect(()=>{if(!Ke)return;const t=r=>e(r.matches);return Ke.addEventListener("change",t),()=>Ke.removeEventListener("change",t)},[]),n}const mo=a.memo(function({terminal:e}){const t=po(),r=$(I=>I.splitTerminal),o=$(I=>I.token),i=$(I=>I.toggleChat),l=$(I=>I.togglePlan),u=$(I=>I.toggleGitHistory),{chatOpen:p,planOpen:c,gitHistoryOpen:d}=e.panels,f=a.useRef(null),h=a.useRef(null),m=a.useRef(null),x=a.useRef(null),T=a.useRef(null),[k,E]=vn(`plan-width-${e.id}`,50,{containerRef:h,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[b,j]=vn(`doc-height-${e.id}`,35,{containerRef:f,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[w,L]=a.useState("");a.useEffect(()=>{if(!o||!e.connected)return;let I=!1;const D=async()=>{try{const H=await hn(o,e.id);I||L(H)}catch{}};D();const K=setInterval(D,5e3);return()=>{I=!0,clearInterval(K)}},[o,e.id,e.connected]);const z=a.useCallback(async I=>{let D;if(o)try{D=await hn(o,e.id)}catch{}r(e.id,I,D)},[o,e.id,r]),[F,B]=a.useState(!1),[P,O]=a.useState(0),[N,C]=a.useState(!1),[S,X]=a.useState(!1),V=async I=>{const D=I.target.files;if(!(!D||D.length===0||!o)){B(!0),O(0);try{await $s(o,e.id,D,K=>{O(K)})}catch(K){alert(`Upload failed: ${K instanceof Error?K.message:"Unknown error"}`)}finally{B(!1),O(0),m.current&&(m.current.value="")}}},W=a.useRef(void 0),J=a.useCallback(I=>{if(x.current){const D=I.replace(/\r?\n/g," ").trimEnd();x.current.sendInput(D),W.current=window.setTimeout(()=>{var K;return(K=x.current)==null?void 0:K.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{W.current&&clearTimeout(W.current)},[]);const ee=a.useCallback(I=>{if(x.current){const D=I.replace(/\r?\n/g," ").trimEnd();x.current.sendInput(D),setTimeout(()=>{var K;return(K=x.current)==null?void 0:K.sendInput("\r")},50)}},[]),Y=a.useCallback(()=>X(!1),[]);return s.jsxs("div",{ref:f,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),s.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]}),w&&s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:w,children:w})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:m,type:"file",multiple:!0,style:{display:"none"},onChange:V}),s.jsx("button",{className:"pane-btn",onClick:()=>{var I;return(I=m.current)==null?void 0:I.click()},disabled:F,style:F?{color:"var(--accent-yellow)"}:void 0,title:F?`Uploading ${P}%`:"Upload files","aria-label":"Upload files",children:F?`${P}%`:"↑"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>X(!0),title:"Download files","aria-label":"Download files",children:"↓"}),S&&o&&s.jsx(uo,{token:o,sessionId:e.id,onClose:Y})]}),s.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${c?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),s.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>u(e.id),title:"Toggle Git history panel","aria-label":"Toggle Git history panel",children:"Git"}),s.jsx("button",{className:"pane-btn",onClick:()=>z(t?"vertical":"horizontal"),title:t?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>z("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{ref:h,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[(c||d)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{width:`${k}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:[c&&s.jsx(Ks,{sessionId:e.id,token:o||"",connected:e.connected,onRequestFileStream:I=>{var D;return(D=x.current)==null?void 0:D.requestFileStream(I)},onSendToTerminal:ee}),d&&s.jsx(ao,{sessionId:e.id,token:o||""})]}),s.jsx("div",{className:"md-editor-divider-h",onMouseDown:E,style:{width:"3px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[s.jsx(ps,{ref:x,sessionId:e.id}),!e.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:j}),s.jsxs("div",{style:{height:`${b}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.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:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),s.jsx("button",{className:"pane-btn",onClick:()=>{var I;return(I=T.current)==null?void 0:I.send()},disabled:!N,title:"Send to terminal (Ctrl+Enter)",style:N?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(co,{ref:T,onSend:J,onContentChange:C,sessionId:e.id,token:o||""})})]})]})]})]}),e.error&&s.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 Hn extends a.Component{constructor(){super(...arguments);Ht(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){}render(){var t,r;return this.state.hasError?this.props.inline?s.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:[s.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),s.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"}),s.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"})]}):s.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:[s.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),s.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 ho=4,wn=10;function go(){const n=$(o=>o.layout),e=$(o=>o.terminalIds.length),t=$(o=>o.addTerminal);if(!n)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:s.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 r=e>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(Un,{node:n,canClose:r})})}const Un=a.memo(function({node:e,canClose:t}){return e.type==="leaf"?s.jsx(xo,{terminalId:e.terminalId,canClose:t}):s.jsx(bo,{node:e,canClose:t})}),xo=a.memo(function({terminalId:e,canClose:t}){const r=$(i=>i.terminalsMap[e]),o=$(i=>i.reconnectTerminal);return r?s.jsx(Hn,{inline:!0,children:s.jsx(mo,{terminal:r,canClose:t})}):s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:s.jsxs("button",{onClick:()=>o(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]})})}),bo=a.memo(function({node:e,canClose:t}){const r=$(c=>c.setSplitSizes),o=a.useRef(null),i=e.direction==="horizontal",l=a.useRef(e.sizes);l.current=e.sizes;const u=a.useCallback((c,d)=>{d.preventDefault();const f=i?"resizing-panes":"resizing-panes-v";document.body.classList.add(f);const h=i?d.clientX:d.clientY,m=[...l.current],x=o.current,T=i?(x==null?void 0:x.clientWidth)||1:(x==null?void 0:x.clientHeight)||1;let k=null;const E=j=>{k||(k=requestAnimationFrame(()=>{k=null;const z=((i?j.clientX:j.clientY)-h)/T*100,F=m[c]+z,B=m[c+1]-z;if(F>=wn&&B>=wn){const P=[...m];P[c]=F,P[c+1]=B,r(e.id,P)}}))},b=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(f),document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",E),document.addEventListener("mouseup",b)},[i,e.id,r]),p=[];return e.children.forEach((c,d)=>{const f=c.type==="leaf"?c.terminalId:c.id;p.push(s.jsx("div",{style:{flex:`${e.sizes[d]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(Un,{node:c,canClose:t})},f)),d<e.children.length-1&&p.push(s.jsx("div",{onMouseDown:h=>u(d,h),style:{flex:`0 0 ${ho}px`,cursor:i?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${d}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:i?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function yo({tabId:n}){const e=$(C=>C.tabs.find(S=>S.id===n)),t=$(C=>C.activeTabId),r=$(C=>C.switchTab),o=$(C=>C.closeTab),i=$(C=>C.reopenTab),l=$(C=>C.deleteTab),u=$(C=>C.renameTab),p=$(C=>e?e.terminalIds.map(S=>{const X=C.terminalsMap[S];return X?{id:S,connected:X.connected,active:!0}:{id:S,connected:!1,active:!1}}):[]),c=$(C=>C.disconnectTerminal),d=$(C=>C.reconnectTerminal),f=$(C=>C.killServerSession),[h,m]=a.useState(!1),[x,T]=a.useState(""),[k,E]=a.useState(!1),b=a.useRef(null);if(!e)return null;const j=t===n,w=e.status==="open",L=()=>{w&&r(n)},z=C=>{w&&(C.stopPropagation(),T(e.name),m(!0),setTimeout(()=>{var S;return(S=b.current)==null?void 0:S.focus()},0))},F=()=>{const C=x.trim();C&&u(n,C),m(!1)},B=C=>{C.stopPropagation(),i(n)},P=C=>{C.stopPropagation(),o(n)},O=async C=>{C.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await l(n)},N=C=>{C.stopPropagation(),E(!k)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:w?"pointer":"default",borderLeft:j?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:j?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:w?1:.5},onMouseEnter:C=>{w&&!j&&(C.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:C=>{j||(C.currentTarget.style.backgroundColor="transparent")},children:[w&&e.terminalIds.length>0&&s.jsx("button",{onClick:N,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:k?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[h?s.jsx("input",{ref:b,value:x,onChange:C=>T(C.target.value),onBlur:F,onKeyDown:C=>{C.key==="Enter"&&F(),C.key==="Escape"&&m(!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"}}):s.jsx("div",{onDoubleClick:z,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:w?"Double-click to rename":e.name,children:e.name}),s.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",Pn(Math.floor(e.createdAt/1e3))]})]}),w?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:P,style:{flexShrink:0},title:"Close tab",children:"×"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:B,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:O,title:"Delete tab",children:"×"})]})]}),w&&k&&p.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(C=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${C.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:C.id}),s.jsx("span",{style:{marginLeft:"8px",color:C.active?C.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:C.active?C.connected?"●":"◐":"○"}),C.active?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),c(C.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:S=>{S.stopPropagation(),d(C.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),window.confirm(`Kill terminal "${C.id}"? This will destroy the tmux session.`)&&f(C.id)},title:"Kill session",children:"×"})]})]},C.id))})]})}function vo({sessionId:n,active:e,createdAt:t}){const r=$(u=>u.addTerminal),o=$(u=>u.killServerSession),i=()=>{r("horizontal",n)},l=u=>{u.stopPropagation(),window.confirm(`Delete orphaned session "${n}"? This will kill the tmux session.`)&&o(n)};return s.jsxs("div",{onClick:i,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s"},onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:Pn(t)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:l,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function wo(){const n=$(c=>c.sidebarOpen),e=$(c=>c.toggleSidebar),t=$(c=>c.fetchSessions),r=$(c=>n?c.serverSessions:[]),o=$(c=>n?c.tabs:[]),i=$(c=>c.terminalIds.length),l=$(c=>c.tabsLoading),u=new Set(o.flatMap(c=>c.terminalIds)),p=r.filter(c=>!u.has(c.sessionId));return a.useEffect(()=>{if(!n)return;t();let c=setInterval(t,5e3);const d=()=>{document.hidden?c&&(clearInterval(c),c=null):(t(),c||(c=setInterval(t,5e3)))};return document.addEventListener("visibilitychange",d),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",d)}},[n,t]),a.useEffect(()=>{if(!n)return;const c=setTimeout(t,800);return()=>clearTimeout(c)},[i,n,t]),s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),s.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:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.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"}),o.length===0?s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(c=>s.jsx(yo,{tabId:c.id},c.id))]}),!l&&p.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.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"}),p.map(c=>s.jsx(vo,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const Kn=$t.memo(()=>{const n=$(w=>w.tabs),e=$(w=>w.activeTabId),t=$(w=>w.addTab),r=$(w=>w.switchTab),o=$(w=>w.closeTab),i=$(w=>w.renameTab),[l,u]=a.useState(null),[p,c]=a.useState(""),d=a.useRef(null),f=n.filter(w=>w.status==="open");a.useEffect(()=>{l&&d.current&&(d.current.focus(),d.current.select())},[l]);const h=w=>{u(w.id),c(w.name)},m=()=>{l&&p.trim()&&i(l,p.trim()),u(null),c("")},x=()=>{u(null),c("")},T=w=>{w.key==="Enter"?m():w.key==="Escape"&&x()},k=w=>{l||r(w)},E=(w,L)=>{w.stopPropagation(),o(L)},b=(w,L)=>{w.button===1&&(w.preventDefault(),o(L))},j=f.length>1;return s.jsxs("div",{className:"tab-bar",children:[f.map(w=>{const L=w.id===e,z=l===w.id,F=w.terminalIds.length;return s.jsx("div",{className:`tab-item ${L?"tab-item--active":""}`,onClick:()=>k(w.id),onDoubleClick:()=>h(w),onMouseDown:B=>b(B,w.id),children:z?s.jsx("input",{ref:d,type:"text",value:p,onChange:B=>c(B.target.value),onBlur:m,onKeyDown:T,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[w.name," ",F>0&&`(${F})`]}),j&&s.jsx("button",{className:"tab-item__close",onClick:B=>E(B,w.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},w.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>t(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});Kn.displayName="TabBar";function So(){return localStorage.getItem("ai-cli-online-token")}function ko(){const n=$(d=>d.token),e=$(d=>d.setToken),t=$(d=>d.tabs),r=$(d=>d.addTab),o=$(d=>d.toggleSidebar),i=$(d=>d.fontSize),l=$(d=>d.setFontSize),u=$(d=>d.tabsLoading),p=$(d=>d.theme),c=$(d=>d.toggleTheme);return a.useEffect(()=>{const d=So();d&&!n&&e(d)},[]),a.useEffect(()=>{n&&!u&&t.filter(d=>d.status==="open").length===0&&r("Default")},[n,u]),n?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.16"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>l(i-1),disabled:i<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),s.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:i}),s.jsx("button",{className:"header-btn",onClick:()=>l(i+1),disabled:i>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(To,{}),s.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"☀":"🌙"}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(go,{})}),s.jsx(wo,{})]}),s.jsx(Kn,{})]}):s.jsx(Vr,{})}const Co=[1,2,3,4];function To(){const n=$(r=>r.latency);if(n===null)return s.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),s.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:[Co.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=t?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[n,"ms"]})]})}Lt.createRoot(document.getElementById("root")).render(s.jsx($t.StrictMode,{children:s.jsx(Hn,{children:s.jsx(ko,{})})}));
|
|
27
|
+
`);let i=0;for(let m=0;m<e-1&&m<n.length;m++)i+=n[m].length+1;let l=0;for(let m=0;m<t&&m<n.length;m++)l+=n[m].length+1;let u=i,p=Math.min(o.length,l);if(r){const m=Math.max(0,i-10),x=Math.min(o.length,l+10),k=o.slice(m,x).indexOf(r);k>=0&&(u=m+k,p=u+r.length)}const c=Math.max(0,u-20),d=o.slice(c,u).replace(/\n/g,"↵"),f=Math.min(o.length,p+20),h=o.slice(p,f).replace(/\n/g,"↵");return{before:d,after:h}}function an(n,e){const t=[],r=[],o=[],i=[];for(const l of n.additions){const{before:u,after:p}=at(e,l.sourceLine,l.sourceLine);t.push([`Line${l.sourceLine}:...${u}`,l.content,`${p}...`])}for(const l of n.deletions){const{before:u,after:p}=at(e,l.startLine,l.endLine,l.selectedText);r.push([`Line${l.startLine}:...${u}`,l.selectedText,`${p}...`])}for(const l of n.replacements){const{before:u,after:p}=at(e,l.startLine,l.endLine,l.selectedText);o.push([`Line${l.startLine}:...${u}`,l.selectedText,l.content,`${p}...`])}for(const l of n.comments){const{before:u,after:p}=at(e,l.startLine,l.endLine,l.selectedText);i.push([`Line${l.startLine}:...${u}`,l.selectedText,l.content,`${p}...`])}return{"Insert Annotations":t,"Delete Annotations":r,"Replace Annotations":o,"Comment Annotations":i}}function ln(n){return n.additions.length>0||n.deletions.length>0||n.replacements.length>0||n.comments.length>0}function cn(n){return/^[a-zA-Z0-9_./:@=-]+$/.test(n)?n:"'"+n.replace(/'/g,"'\\''")+"'"}function dn(n,e){return`/moonview:annotate ${cn(n)} ${cn(e)} --silent`}function un(n){const e=n.split("/"),t=e.indexOf("AiTasks");return t>=0&&t+1<e.length?e.slice(0,t+2).join("/"):n.substring(0,n.lastIndexOf("/"))}function ft(n){const e=new Set;return n.additions.forEach(t=>e.add(t.id)),n.deletions.forEach(t=>e.add(t.id)),n.replacements.forEach(t=>e.add(t.id)),n.comments.forEach(t=>e.add(t.id)),e}function fn(n){return n.replacements||(n.replacements=[]),n.comments||(n.comments=[]),n}function Ts({sessionId:n,filePath:e,token:t,annotations:r,annLoadedRef:o,setAnnotations:i,baselineIdsRef:l}){const u=z(f=>f.latency),p=a.useRef(void 0),c=a.useRef(void 0),d=a.useRef(!1);a.useEffect(()=>{if(!o.current)return;const f=Qe(n,e),h=JSON.stringify(r);p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(f,h)}catch{}},50),c.current&&clearTimeout(c.current);const m=Math.max(200,(u??30)*3);return c.current=setTimeout(()=>{d.current||(d.current=!0,_n(t,n,e,h,Date.now()).catch(()=>{}).finally(()=>{d.current=!1}))},m),()=>{p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current)}},[r,n,e,t,u,o]),a.useEffect(()=>{o.current=!1;let f=At,h=0;try{const x=localStorage.getItem(Qe(n,e));x&&(f=fn(JSON.parse(x)),h=Date.now())}catch{}i(f),l.current=ft(f);let m=!1;return Ss(t,n,e).then(x=>{if(!m&&x&&x.updatedAt>h)try{const T=fn(JSON.parse(x.content));i(T);try{localStorage.setItem(Qe(n,e),x.content)}catch{}l.current=ft(T)}catch{}}).catch(()=>{}).finally(()=>{o.current=!0}),o.current=!0,()=>{m=!0}},[n,e,t,o,i,l])}async function it(n,e,t,r){const o={path:t};return r&&(o.since=String(r)),pe.getOptional(n,e,"file-content",o)}async function pn(n,e,t,r){return pe.putJson(n,e,"file-content",{path:t,content:r})}function On(n,e){let t=n.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");t||(t="heading");const r=e.get(t)||0;return r>0&&(t=`${t}-${r}`),e.set(t,r+1),t}function Fn(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 Es(n){if(!n)return[];const e=[],t=new Map,r=n.split(`
|
|
28
|
+
`);let o=!1;for(const i of r){if(/^```/.test(i.trim())){o=!o;continue}if(o)continue;const l=i.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(l){const u=l[1].length,p=Fn(l[2]),c=On(p,t);e.push({id:c,text:p,level:u})}}return e}const js=160,Is=22;function Rs({headings:n,scrollRef:e}){const[t,r]=a.useState(null),[o,i]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),l=a.useRef(null),u=a.useRef(!1),p=a.useMemo(()=>Math.min(...n.map(f=>f.level)),[n]),c=a.useCallback(()=>{i(f=>{const h=!f;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);a.useEffect(()=>{const f=e.current;if(!f||n.length===0)return;const h=()=>{u.current=!1;const x=f.scrollTop,T=50;let k=null;for(const E of n){const b=f.querySelector(`[id="${CSS.escape(E.id)}"]`);b&&b.offsetTop<=x+T&&(k=E.id)}r(k)},m=()=>{u.current||(u.current=!0,requestAnimationFrame(h))};return h(),f.addEventListener("scroll",m,{passive:!0}),()=>f.removeEventListener("scroll",m)},[n,e]);const d=a.useCallback(f=>{const h=e.current;if(!h)return;const m=h.querySelector(`[id="${CSS.escape(f)}"]`);m&&(m.scrollIntoView({behavior:"smooth",block:"start"}),r(f))},[e]);return a.useEffect(()=>{if(!t||o)return;const f=l.current;if(!f)return;const h=f.querySelector(`[data-toc-id="${CSS.escape(t)}"]`);if(h){const m=h.offsetTop-f.offsetTop,x=m+h.offsetHeight;(m<f.scrollTop||x>f.scrollTop+f.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[t,o]),n.length<2?null:o?s.jsx("div",{style:{width:Is,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:s.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:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):s.jsxs("div",{ref:l,style:{width:js,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),s.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:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:n.map((f,h)=>s.jsx("div",{"data-toc-id":f.id,onClick:()=>d(f.id),style:{padding:`2px 6px 2px ${(f.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:t===f.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:t===f.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:f.level<=2?500:400,transition:"color 0.1s"},title:f.text,onMouseEnter:m=>{t!==f.id&&(m.currentTarget.style.color="var(--text-primary)"),m.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:m=>{t!==f.id&&(m.currentTarget.style.color="var(--text-secondary)"),m.currentTarget.style.backgroundColor="transparent"},children:f.text},`${f.id}-${h}`))})]})}const Ls={add:{symbol:"+",color:"var(--accent-yellow)",field:"content"},del:{symbol:"−",color:"var(--accent-red)",field:"selectedText"},rep:{symbol:"⇄",color:"var(--accent-blue)",field:"content"},com:{symbol:"?",color:"var(--accent-green)",field:"content"}};function Ms({annotations:n,annCounts:e,isSent:t,onSendAll:r,onSendSingle:o,onDelete:i}){const[l,u]=a.useState(!1),p=a.useRef(null);a.useEffect(()=>{if(!l)return;const f=h=>{p.current&&!p.current.contains(h.target)&&u(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[l]);const c=a.useCallback((f,h,m)=>{const x=Ls[h],T=t(f);return s.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[s.jsx("span",{className:"plan-anno-dropdown__type",style:{color:x.color},children:x.symbol}),s.jsxs("span",{className:"plan-anno-dropdown__text",children:[m.slice(0,60),m.length>60?"...":""]}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!T&&o(f,h),disabled:T,title:T?"Already sent":"Send to terminal",style:T?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(f,h),title:"Delete",children:"×"})]},f)},[t,o,i]),d=(()=>{const f=n.additions[0],h=n.deletions[0],m=n.replacements[0],x=n.comments[0],T=f?f.content:h?h.selectedText:m?m.content:x?x.content:"";return T?T.slice(0,40)+(T.length>40?"...":""):""})();return s.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[s.jsxs("div",{className:`plan-anno-dropdown-trigger${l?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>u(f=>!f),title:e.total>0?`${e.total} annotations (${e.unsent} unsent)`:"No annotations",children:[s.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:d}),s.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),l&&s.jsxs("div",{className:"plan-anno-dropdown",children:[e.unsent>0&&s.jsx("div",{className:"plan-anno-dropdown__header",children:s.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",e.unsent,")"]})}),s.jsxs("div",{className:"plan-anno-dropdown__list",children:[n.additions.map(f=>c(f.id,"add",f.content)),n.deletions.map(f=>c(f.id,"del",f.selectedText)),n.replacements.map(f=>c(f.id,"rep",f.content)),n.comments.map(f=>c(f.id,"com",f.content)),e.total===0&&s.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const Ns={del:{className:"plan-deletion-card",icon:"",color:"var(--accent-red)"},rep:{className:"plan-replace-card",icon:"⇄",color:"var(--accent-blue)"},com:{className:"plan-comment-card",icon:"?",color:"var(--accent-green)"}};function jt({type:n,annotation:e,fontSize:t,onEdit:r,onRemove:o,onSend:i,isSent:l}){const u=Ns[n],[p,c]=a.useState(!1),[d,f]=a.useState(""),h=a.useRef(null),m=n==="del"?e.selectedText:e.content,x=a.useCallback(()=>{c(!0),f(m)},[m]),T=a.useCallback(()=>{const k=d.trim();k?r(e.id,k):o(e.id),c(!1)},[d,e.id,r,o]);return a.useEffect(()=>{p&&requestAnimationFrame(()=>{const k=h.current;k&&(k.focus(),k.selectionStart=k.selectionEnd=k.value.length)})},[p]),p?s.jsx("div",{className:u.className,children:s.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:d,onChange:k=>f(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),T()),k.key==="Escape"&&(k.preventDefault(),c(!1))},onBlur:T,rows:ut(d),style:{fontSize:`${t}px`,flex:1}})}):s.jsxs("div",{className:u.className,children:[u.icon&&s.jsx("span",{style:{color:u.color,flexShrink:0},children:u.icon}),n==="del"?s.jsx("span",{style:{flex:1,fontSize:`${t}px`,color:u.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:e.selectedText}):n==="rep"?s.jsxs("span",{style:{flex:1,fontSize:`${t}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:e.selectedText}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),s.jsx("span",{style:{color:"var(--accent-blue)"},children:e.content})]}):s.jsxs("span",{style:{flex:1,fontSize:`${t}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',e.selectedText,'"']}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),s.jsx("span",{style:{color:"var(--accent-green)"},children:e.content})]}),i&&s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!l&&i(e.id),disabled:l,title:l?"Already sent":"Send to terminal",style:l?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:x,style:{color:"var(--accent-blue)"},title:`Edit ${n==="del"?"deletion":n==="rep"?"replacement":"comment"}`,children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>o(e.id),title:`Remove ${n==="del"?"deletion":n==="rep"?"replacement":"comment"}`,children:"×"})]})}function Ds({x:n,y:e,onDelete:t,onReplace:r,onComment:o}){return s.jsxs("div",{className:"plan-selection-float",style:{top:e,left:n},children:[s.jsx("button",{className:"plan-selection-float__delete",onMouseDown:i=>{i.preventDefault(),t()},title:"Delete selection",children:"−"}),s.jsx("button",{className:"plan-selection-float__replace",onMouseDown:i=>{i.preventDefault(),r()},title:"Replace selection",children:"⇄"}),s.jsx("button",{className:"plan-selection-float__comment",onMouseDown:i=>{i.preventDefault(),o()},title:"Comment on selection",children:"?"})]})}const As=a.forwardRef(function({markdown:e,filePath:t,sessionId:r,token:o,onExecute:i,onSend:l,onRefresh:u,onClose:p,onContentSaved:c,expanded:d,readOnly:f},h){const m=z(g=>g.fontSize),[x,T]=a.useState(null),k=a.useRef(void 0),E=a.useCallback((g,y)=>{clearTimeout(k.current),T({type:g,msg:y}),k.current=setTimeout(()=>T(null),g==="ok"?2500:5e3)},[]);a.useEffect(()=>()=>clearTimeout(k.current),[]);const[b,j]=a.useState(!1),[w,N]=a.useState(""),[L,_]=a.useState(!1),B=a.useRef(null),P=z(g=>g.latency),F=`plan-edit:${r}:${t}`,D=a.useRef(void 0),C=a.useRef(void 0),S=a.useRef(!1);a.useEffect(()=>{if(!b)return;clearTimeout(D.current),D.current=setTimeout(()=>{try{localStorage.setItem(F,w)}catch{}},50),clearTimeout(C.current);const g=Math.max(200,(P??30)*3);return C.current=setTimeout(()=>{S.current||(S.current=!0,pn(o,r,t,w).then(y=>{c==null||c(w,y.mtime)}).catch(()=>{}).finally(()=>{S.current=!1}))},g),()=>{clearTimeout(D.current),clearTimeout(C.current)}},[w,b,F,o,r,t,P,c]),a.useEffect(()=>{j(!1)},[t]),a.useEffect(()=>{b&&requestAnimationFrame(()=>{var g;return(g=B.current)==null?void 0:g.focus()})},[b]);const X=a.useCallback(()=>{if(f||b)return;const g=localStorage.getItem(`plan-edit:${r}:${t}`);N(g??e),j(!0)},[f,b,e,r,t]),V=a.useCallback(()=>{j(!1),N(""),localStorage.removeItem(`plan-edit:${r}:${t}`)},[r,t]),W=a.useCallback(async()=>{if(!L){_(!0);try{const g=await pn(o,r,t,w);c==null||c(w,g.mtime),j(!1),N(""),localStorage.removeItem(`plan-edit:${r}:${t}`),E("ok","Saved")}catch(g){const y=g instanceof Error?g.message:"Failed to save";E("err",y)}finally{_(!1)}}},[L,o,r,t,w,c,E]),J=a.useMemo(()=>e?Tn.lexer(e):[],[e]),ee=a.useMemo(()=>e.split(`
|
|
29
|
+
`),[e]),Y=a.useMemo(()=>Es(e),[e]),I=a.useMemo(()=>{const g=new Map,y=new Map;return J.forEach(($,M)=>{if($.type==="heading"){const oe=Fn($.text||""),re=On(oe,y);g.set(M,re)}}),g},[J]),A=a.useRef(new Set),K=a.useRef(!1),[H,ne]=a.useState(()=>{try{const g=localStorage.getItem(Qe(r,t)),y=g?JSON.parse(g):At;return A.current=ft(y),y.replacements||(y.replacements=[]),y.comments||(y.comments=[]),y}catch{return At}});Ts({sessionId:r,filePath:t,token:o,annotations:H,annLoadedRef:K,setAnnotations:ne,baselineIdsRef:A});const[ae,xe]=a.useState(0),ze=a.useMemo(()=>{const g=A.current,y=H.additions.length+H.deletions.length+H.replacements.length+H.comments.length;let $=0;return H.additions.forEach(M=>{g.has(M.id)&&$++}),H.deletions.forEach(M=>{g.has(M.id)&&$++}),H.replacements.forEach(M=>{g.has(M.id)&&$++}),H.comments.forEach(M=>{g.has(M.id)&&$++}),{total:y,sent:$,unsent:y-$}},[H,ae]),[O,U]=a.useState(null),[Z,Q]=a.useState(""),q=a.useRef(null),[te,ye]=a.useState(null),[je,Ie]=a.useState(""),_e=a.useRef(null),[ce,Se]=a.useState(null),me=a.useRef(null),Je=a.useRef(0),Be=a.useRef(null);a.useEffect(()=>{const g=me.current;if(!g)return;let y;const $=()=>{clearTimeout(y),y=setTimeout(()=>{const M=on(r,t);if(g.scrollTop>0)try{localStorage.setItem(M,String(g.scrollTop))}catch{}else localStorage.removeItem(M)},50)};return g.addEventListener("scroll",$,{passive:!0}),()=>{clearTimeout(y),g.removeEventListener("scroll",$)}},[r,t]),a.useEffect(()=>{if(!J.length)return;const g=localStorage.getItem(on(r,t));if(!g)return;const y=Number(g),$=me.current;if(!$||($.scrollTop=y,$.scrollTop>=y-10))return;let M;const oe=()=>{$.scrollTop=y,re.disconnect()},re=new MutationObserver(()=>{clearTimeout(M),M=setTimeout(oe,80)});re.observe($,{childList:!0,subtree:!0});const le=setTimeout(oe,500);return()=>{clearTimeout(M),clearTimeout(le),re.disconnect()}},[r,t,J.length]),a.useEffect(()=>{O!=null&&requestAnimationFrame(()=>{var g;return(g=q.current)==null?void 0:g.focus()})},[O]),a.useEffect(()=>{te&&requestAnimationFrame(()=>{var g;return(g=_e.current)==null?void 0:g.focus()})},[te]);const Pe=a.useRef({annotations:H,activeInsert:O,insertText:Z,pendingAction:te,pendingText:je,tokens:J,filePath:t,sessionId:r,token:o});Pe.current={annotations:H,activeInsert:O,insertText:Z,pendingAction:te,pendingText:je,tokens:J,filePath:t,sessionId:r,token:o},a.useEffect(()=>()=>{const g=Pe.current;let y=g.annotations,$=!1;if(g.activeInsert!=null&&g.insertText.trim()){const M=ot(g.tokens,g.activeInsert+1);y={...y,additions:[...y.additions,{id:Ce(),afterTokenIndex:g.activeInsert,sourceLine:M,content:g.insertText.trim()}]},$=!0}if(g.pendingAction&&g.pendingText.trim()){const M=g.pendingAction,oe=g.pendingText.trim();M.type==="replace"?y={...y,replacements:[...y.replacements,{id:Ce(),tokenIndices:M.tokenIndices,startLine:M.startLine,endLine:M.endLine,selectedText:M.text,content:oe}]}:y={...y,comments:[...y.comments,{id:Ce(),tokenIndices:M.tokenIndices,startLine:M.startLine,endLine:M.endLine,selectedText:M.text,content:oe}]},$=!0}if($){const M=JSON.stringify(y);try{localStorage.setItem(Qe(g.sessionId,g.filePath),M)}catch{}_n(g.token,g.sessionId,g.filePath,M,Date.now()).catch(()=>{})}},[]);const Me=a.useCallback(g=>{if(!Z.trim()){U(null),Q("");return}const y=ot(J,g+1);ne($=>({...$,additions:[...$.additions,{id:Ce(),afterTokenIndex:g,sourceLine:y,content:Z.trim()}]})),U(null),Q("")},[Z,J]),Ne=a.useCallback(g=>{ne(y=>({...y,additions:y.additions.filter($=>$.id!==g)}))},[]),et=a.useCallback((g,y)=>{ne($=>({...$,additions:$.additions.map(M=>M.id===g?{...M,id:Ce(),content:y}:M)}))},[]),yt=a.useCallback(()=>{var g;ce&&(ne(y=>({...y,deletions:[...y.deletions,{id:Ce(),tokenIndices:ce.tokenIndices,startLine:ce.startLine,endLine:ce.endLine,selectedText:ce.text.slice(0,80)}]})),Se(null),(g=window.getSelection())==null||g.removeAllRanges())},[ce]),v=a.useCallback(g=>{var y;ce&&(ye({type:g,tokenIndices:ce.tokenIndices,startLine:ce.startLine,endLine:ce.endLine,text:ce.text.slice(0,80)}),Ie(""),Se(null),(y=window.getSelection())==null||y.removeAllRanges())},[ce]),R=a.useCallback(()=>{if(!te)return;const g=je.trim();if(!g){ye(null),Ie("");return}te.type==="replace"?ne(y=>({...y,replacements:[...y.replacements,{id:Ce(),tokenIndices:te.tokenIndices,startLine:te.startLine,endLine:te.endLine,selectedText:te.text,content:g}]})):ne(y=>({...y,comments:[...y.comments,{id:Ce(),tokenIndices:te.tokenIndices,startLine:te.startLine,endLine:te.endLine,selectedText:te.text,content:g}]})),ye(null),Ie("")},[te,je]),G=a.useCallback(g=>{ne(y=>({...y,replacements:y.replacements.filter($=>$.id!==g)}))},[]),se=a.useCallback((g,y)=>{ne($=>({...$,replacements:$.replacements.map(M=>M.id===g?{...M,id:Ce(),content:y}:M)}))},[]),ie=a.useCallback(g=>{ne(y=>({...y,comments:y.comments.filter($=>$.id!==g)}))},[]),ke=a.useCallback((g,y)=>{ne($=>({...$,comments:$.comments.map(M=>M.id===g?{...M,id:Ce(),content:y}:M)}))},[]),de=a.useCallback(g=>{ne(y=>({...y,deletions:y.deletions.filter($=>$.id!==g)}))},[]),be=a.useCallback((g,y)=>{ne($=>({...$,deletions:$.deletions.map(M=>M.id===g?{...M,id:Ce(),selectedText:y}:M)}))},[]),ge=a.useCallback(g=>{let y=g instanceof Element?g:g.parentElement;for(;y&&y!==me.current;){if(y.hasAttribute("data-token-index"))return y;y=y.parentElement}return null},[]),ue=a.useCallback(()=>{const g=window.getSelection();if(!g||g.isCollapsed||!me.current){Se(null);return}const y=g.toString().trim();if(!y){Se(null);return}const $=g.getRangeAt(0);if(!me.current.contains($.commonAncestorContainer)){Se(null);return}const M=ge($.startContainer),oe=ge($.endContainer);if(!M||!oe){Se(null);return}const re=parseInt(M.getAttribute("data-token-index")||"0",10),le=parseInt(oe.getAttribute("data-token-index")||"0",10),Ft=[];for(let kt=Math.min(re,le);kt<=Math.max(re,le);kt++)Ft.push(kt);const Yn=ot(J,Math.min(re,le)),Xn=ot(J,Math.max(re,le)+1),Bt=$.getBoundingClientRect(),St=me.current,Pt=St.getBoundingClientRect();navigator.clipboard.writeText(y).catch(()=>{});const tt=Be.current,Wt=tt&&Date.now()-tt.time<500;Je.current=Date.now(),Se({x:(Wt?tt.x:Bt.right)-Pt.left+St.scrollLeft+6,y:(Wt?tt.y:Bt.top)-Pt.top+St.scrollTop-44,tokenIndices:Ft,startLine:Yn,endLine:Xn,text:y})},[J,ge]),we=a.useRef(void 0);a.useEffect(()=>{const g=()=>{we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{const y=window.getSelection();if(!y||y.isCollapsed||!me.current){if(Date.now()-Je.current<300)return;Se(null);return}const $=y.anchorNode;$&&me.current.contains($)&&ue()},120)};return document.addEventListener("selectionchange",g),()=>{document.removeEventListener("selectionchange",g),we.current&&clearTimeout(we.current)}},[ue]);const Ve=z(g=>g.theme);ws(me,J,Ve);const We=a.useCallback(()=>{const g=A.current;return{additions:H.additions.filter(y=>!g.has(y.id)),deletions:H.deletions.filter(y=>!g.has(y.id)),replacements:H.replacements.filter(y=>!g.has(y.id)),comments:H.comments.filter(y=>!g.has(y.id))}},[H]),vt=a.useCallback(async()=>{const g=We();if(!ln(g))return;const y=an(g,ee),$=un(t);try{const{path:M}=await sn(o,r,$,y),oe=dn(t,M);i(oe),A.current=ft(H),xe(le=>le+1);const re=g.additions.length+g.deletions.length+g.replacements.length+g.comments.length;E("ok",`Sent ${re} annotation(s)`)}catch(M){const oe=M instanceof Error?M.message:"Failed to send";E("err",oe)}},[We,H,ee,i,t,o,r,E]),He=a.useCallback(async(g,y)=>{if(!l)return;const $={additions:[],deletions:[],replacements:[],comments:[]};if(y==="add"){const re=H.additions.find(le=>le.id===g);if(!re)return;$.additions.push(re)}else if(y==="del"){const re=H.deletions.find(le=>le.id===g);if(!re)return;$.deletions.push(re)}else if(y==="rep"){const re=H.replacements.find(le=>le.id===g);if(!re)return;$.replacements.push(re)}else{const re=H.comments.find(le=>le.id===g);if(!re)return;$.comments.push(re)}const M=an($,ee),oe=un(t);try{const{path:re}=await sn(o,r,oe,M);l(dn(t,re)),A.current.add(g),xe(le=>le+1),E("ok","Sent 1 annotation")}catch(re){const le=re instanceof Error?re.message:"Failed to send";E("err",le)}},[l,t,H,ee,o,r,E]),Gn=a.useCallback((g,y)=>{y==="add"?Ne(g):y==="del"?de(g):y==="rep"?G(g):ie(g)},[Ne,de,G,ie]);a.useImperativeHandle(h,()=>({getSummary:()=>{const g=We();return ln(g)?"[pending annotations]":""},handleEscape:()=>b?(V(),!0):te?(R(),!0):O!=null?(Me(O),!0):!1,getScrollTop:()=>{var g;return((g=me.current)==null?void 0:g.scrollTop)??0},setScrollTop:g=>{requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=g)})}}),[We,b,V,O,Me,te,R]);const Jn=a.useMemo(()=>{const g=new Set;return H.deletions.forEach(y=>y.tokenIndices.forEach($=>g.add($))),g},[H.deletions]),Vn=a.useMemo(()=>{const g=new Set;return H.replacements.forEach(y=>y.tokenIndices.forEach($=>g.add($))),g},[H.replacements]),qn=a.useMemo(()=>{const g=new Set;return H.comments.forEach(y=>y.tokenIndices.forEach($=>g.add($))),g},[H.comments]),_t=a.useMemo(()=>{const g=new Map;return H.additions.forEach(y=>{const $=g.get(y.afterTokenIndex)||[];$.push(y),g.set(y.afterTokenIndex,$)}),g},[H.additions]),Ot=ze.unsent>0,wt=a.useCallback(g=>A.current.has(g),[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:t,children:t.split("/").pop()||t}),x&&s.jsx("span",{style:{fontSize:"10px",color:x.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:x.type==="err"?"pointer":void 0},title:x.type==="err"?"Click to copy":x.msg,onClick:x.type==="err"?()=>{navigator.clipboard.writeText(x.msg).catch(()=>{}),E("ok","Copied")}:void 0,children:x.msg}),b?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"pane-btn",onClick:W,disabled:L,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:L?"Saving...":"Save"}),s.jsx("button",{className:"pane-btn",onClick:V,disabled:L,title:"Cancel (Esc)",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[u&&s.jsx("button",{className:"pane-btn",onClick:u,title:"Refresh current file",children:"↻"}),!f&&s.jsx("button",{className:"pane-btn",onClick:X,title:"Edit file (double-click content)",children:"Edit"}),s.jsx("button",{className:"pane-btn",onClick:vt,disabled:!Ot,title:"Send all annotations",style:Ot?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),s.jsx(Ms,{annotations:H,annCounts:ze,isSent:wt,onSendAll:vt,onSendSingle:He,onDelete:Gn}),p&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await vt(),p()},title:"Send annotations & close file",children:"×"})]})]}),s.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[b?s.jsx("textarea",{ref:B,className:"plan-edit-textarea",style:{fontSize:`${m}px`},value:w,onChange:g=>N(g.target.value),onKeyDown:g=>{if(g.key==="s"&&(g.ctrlKey||g.metaKey)){g.preventDefault(),W();return}if(g.key==="Escape"){g.preventDefault(),V();return}},spellCheck:!1}):s.jsxs("div",{ref:me,className:`plan-anno-content md-preview${O!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${m}px`,minWidth:0},onMouseUp:g=>{Be.current={x:g.clientX,y:g.clientY,time:Date.now()},ue()},onDoubleClick:g=>{f||g.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||X()},children:[!f&&s.jsx(mn,{index:-1,active:O===-1,additions:_t.get(-1),onOpen:()=>{U(-1),Q("")},onSubmit:()=>Me(-1),onRemoveAddition:Ne,onEditAddition:et,onSendSingle:l?g=>He(g,"add"):void 0,isSent:wt,insertText:Z,setInsertText:Q,textareaRef:O===-1?q:void 0,expanded:d,alwaysShow:J.length===0,fontSize:m}),J.map((g,y)=>{const $=Cs(g);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":y,id:I.get(y),className:Jn.has(y)?"plan-block--deleted":Vn.has(y)?"plan-block--replaced":qn.has(y)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:$}}),H.deletions.filter(M=>M.tokenIndices[0]===y).map(M=>s.jsx(jt,{type:"del",annotation:M,fontSize:m,onEdit:be,onRemove:de,onSend:l?oe=>He(oe,"del"):void 0,isSent:A.current.has(M.id)},M.id)),H.replacements.filter(M=>M.tokenIndices[0]===y).map(M=>s.jsx(jt,{type:"rep",annotation:M,fontSize:m,onEdit:se,onRemove:G,onSend:l?oe=>He(oe,"rep"):void 0,isSent:A.current.has(M.id)},M.id)),H.comments.filter(M=>M.tokenIndices[0]===y).map(M=>s.jsx(jt,{type:"com",annotation:M,fontSize:m,onEdit:ke,onRemove:ie,onSend:l?oe=>He(oe,"com"):void 0,isSent:A.current.has(M.id)},M.id)),te&&te.tokenIndices[0]===y&&s.jsxs("div",{className:te.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[s.jsx("span",{style:{color:te.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:te.type==="replace"?"⇄":"?"}),s.jsx("textarea",{ref:_e,className:"plan-annotation-textarea",value:je,onChange:M=>Ie(M.target.value),onKeyDown:M=>{if(M.key==="Enter"&&(M.ctrlKey||M.metaKey)){M.preventDefault(),R();return}if(M.key==="Escape"){M.preventDefault(),R();return}},onBlur:R,placeholder:te.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:ut(je),style:{fontSize:`${m}px`,flex:1}})]}),!f&&s.jsx(mn,{index:y,active:O===y,additions:_t.get(y),onOpen:()=>{U(y),Q("")},onSubmit:()=>Me(y),onRemoveAddition:Ne,onEditAddition:et,onSendSingle:l?M=>He(M,"add"):void 0,isSent:wt,insertText:Z,setInsertText:Q,textareaRef:O===y?q:void 0,expanded:d,fontSize:m})]},y)}),!f&&ce&&s.jsx(Ds,{x:ce.x,y:ce.y,onDelete:yt,onReplace:()=>v("replace"),onComment:()=>v("comment")})]}),!b&&s.jsx(Rs,{headings:Y,scrollRef:me})]})]})});function mn({index:n,active:e,additions:t,onOpen:r,onSubmit:o,onRemoveAddition:i,onEditAddition:l,onSendSingle:u,isSent:p,insertText:c,setInsertText:d,textareaRef:f,expanded:h,alwaysShow:m,fontSize:x=14}){const[T,k]=a.useState(null),[E,b]=a.useState(""),j=a.useRef(null),w=Nt(),N=Nt();a.useEffect(()=>{T&&(w.clearUndo(),requestAnimationFrame(()=>{const D=j.current;D&&(D.focus(),D.selectionStart=D.selectionEnd=D.value.length)}))},[T]),a.useEffect(()=>{e&&N.clearUndo()},[e]);const L=a.useCallback(D=>{b(C=>(w.pushUndo(C),D))},[w]),_=a.useCallback(D=>{N.pushUndo(c),d(D)},[c,d,N]),B=a.useCallback(D=>{k(D.id),b(D.content)},[]),P=a.useCallback(()=>{if(!T)return;const D=E.trim();D?l(T,D):i(T),k(null),b("")},[T,E,l,i]),F=a.useCallback(()=>{k(null),b("")},[]);return s.jsxs("div",{className:`plan-insert-zone${m?" plan-insert-zone--empty":""}`,"data-zone-index":n,children:[t==null?void 0:t.map(D=>s.jsx("div",{className:"plan-annotation-card",children:T===D.id?s.jsx("textarea",{ref:j,className:"plan-annotation-textarea",value:E,onChange:C=>L(C.target.value),onKeyDown:C=>{if(C.key==="Enter"&&(C.ctrlKey||C.metaKey)){C.preventDefault(),P();return}if(C.key==="Escape"){C.preventDefault(),F();return}if(C.key==="Tab"){Dt(C,L);return}},onBlur:P,rows:ut(E),style:{fontSize:`${x}px`,flex:1,...h?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${x}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>B(D),title:"Double-click to edit",children:D.content}),u&&(()=>{const C=(p==null?void 0:p(D.id))??!1;return s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!C&&u(D.id),disabled:C,title:C?"Already sent":"Send to terminal",style:C?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>B(D),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(D.id),children:"×"})]})},D.id)),e?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:f,className:"plan-annotation-textarea",value:c,onChange:D=>_(D.target.value),onKeyDown:D=>{if(D.key==="Enter"&&(D.ctrlKey||D.metaKey)){D.preventDefault(),o();return}if(D.key==="Escape"){D.preventDefault(),o();return}if(D.key==="Tab"){Dt(D,_);return}},onBlur:o,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:ut(c),style:{fontSize:`${x}px`,...h?{minWidth:300}:void 0}})}):m&&!(t!=null&&t.length)?s.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:r,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function Le(n,e,t){const r=t?{path:t}:void 0;return pe.get(n,e,"files",r)}function $s(n,e,t,r){return new Promise((o,i)=>{const l=new FormData;for(const p of t)l.append("files",p);const u=new XMLHttpRequest;u.open("POST",`${$e}/api/sessions/${encodeURIComponent(e)}/upload`),u.setRequestHeader("Authorization",`Bearer ${n}`),u.upload.addEventListener("progress",p=>{p.lengthComputable&&r&&r(Math.round(p.loaded/p.total*100))}),u.addEventListener("load",()=>{u.status>=200&&u.status<300?o():i(new Error(`Upload failed: ${u.status}`))}),u.addEventListener("error",()=>i(new Error("Upload network error"))),u.addEventListener("abort",()=>i(new Error("Upload aborted"))),u.send(l)})}async function hn(n,e){return(await pe.get(n,e,"cwd")).cwd}async function zs(n,e,t){return pe.post(n,e,"touch",{name:t})}async function _s(n,e,t){return pe.post(n,e,"mkdir",{path:t})}async function Os(n,e,t){return pe.del(n,e,"rm",{path:t})}async function Fs(n,e){const t=await pe.getBlob(n,e,"download-cwd"),r=await t.blob(),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o;const l=t.headers.get("Content-Disposition"),u=l==null?void 0:l.match(/filename="(.+)"/);i.download=u?decodeURIComponent(u[1]):"cwd.tar.gz",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}async function Bs(n,e,t){const o=await(await pe.getBlob(n,e,"download",{path:t})).blob(),i=URL.createObjectURL(o),l=document.createElement("a");l.href=i,l.download=t.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}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 Ps(n,e){if(e==="directory")return"📁";const t=n.slice(n.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}function Pn(n){const e=new Date(n*1e3),t=r=>String(r).padStart(2,"0");return`${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}function Ws({sessionId:n,token:e,planDir:t,selectedFile:r,onSelectFile:o,onCreateFile:i,onDeleteFile:l}){const[u,p]=a.useState([]),[c,d]=a.useState(!0),[f,h]=a.useState(""),[m,x]=a.useState(!1),T=a.useRef(null),[k,E]=a.useState(()=>{if(r&&r.startsWith(t+"/")){const S=r.substring(0,r.lastIndexOf("/"));if(S.startsWith(t))return S}return t});a.useEffect(()=>{if(r&&r.startsWith(t+"/")){const S=r.substring(0,r.lastIndexOf("/"));if(S.startsWith(t)){E(S);return}}E(t)},[r,t]);const b=a.useCallback(async()=>{if(!(!e||!k)){d(!0);try{const X=(await Le(e,n,k)).files.filter(V=>V.type==="file"&&(V.name.toLowerCase().endsWith(".md")||V.name===".index.json")||V.type==="directory").sort((V,W)=>{const J=V.type==="file"&&V.name===".index.json",ee=W.type==="file"&&W.name===".index.json";return J&&!ee?-1:!J&&ee?1:V.type==="directory"&&W.type!=="directory"?-1:V.type!=="directory"&&W.type==="directory"?1:V.name.localeCompare(W.name)});p(X)}catch{p([])}finally{d(!1)}}},[e,n,k]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const S=setInterval(b,5e3);return()=>clearInterval(S)},[b]);const j=a.useCallback(()=>{const S=t.substring(0,t.lastIndexOf("/")+1);return k.startsWith(S)?k.substring(S.length):k},[t,k]),w=a.useCallback(async()=>{const S=f.trim();if(!S)return;const X=S.endsWith(".md")?S:`${S}.md`;x(!0);try{const V=await zs(e,n,`${j()}/${X}`);V.ok&&(h(""),await b(),i(V.path))}catch{}finally{x(!1)}},[f,e,n,j,b,i]),N=a.useCallback(async()=>{const S=f.trim().replace(/\/+$/,"");if(S){x(!0);try{await _s(e,n,`${j()}/${S}`),h(""),await b()}catch{}finally{x(!1)}}},[f,e,n,j,b]),L=a.useCallback(async S=>{const X=`${k}/${S.name}`,V=S.type==="directory"?`folder "${S.name}" and all its contents`:`"${S.name}"`;if(window.confirm(`Delete ${V}?`))try{await Os(e,n,X),l==null||l(X),await b()}catch{}},[e,n,k,b,l]),_=a.useCallback(S=>{E(X=>`${X}/${S}`)},[]),B=a.useCallback(()=>{k!==t&&E(S=>S.substring(0,S.lastIndexOf("/")))},[k,t]),P=t.split("/").pop()||"AiTasks",F=(()=>{const S=t.split("/");return S.length>=2?S[S.length-2]+"/":""})(),D=k===t?F+P+"/":F+P+"/"+k.substring(t.length+1)+"/",C=r?r.split("/").pop():null;return s.jsxs("div",{className:"plan-file-browser",children:[s.jsxs("div",{className:"plan-file-browser__header",children:[s.jsx("span",{className:"plan-file-browser__title",title:D,children:D}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:b,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),s.jsxs("div",{className:"plan-file-browser__create",children:[s.jsx("input",{ref:T,className:"plan-file-browser__input",value:f,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),w())},placeholder:"name",disabled:m}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:w,disabled:m||!f.trim(),title:"Create new .md file",style:f.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:N,disabled:m||!f.trim(),title:"Create new folder",style:f.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),s.jsxs("div",{className:"plan-file-browser__list",children:[c&&u.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&u.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),k!==t&&s.jsxs("div",{className:"plan-file-browser__item",onClick:B,title:"Go up to parent directory",style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),s.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),u.map(S=>{const X=`${k}/${S.name}`,V=S.type==="file"&&S.name===C,W=S.type==="directory";return s.jsxs("div",{className:`plan-file-browser__item${V?" plan-file-browser__item--active":""}`,onClick:()=>W?_(S.name):o(X),title:W?`Open folder ${S.name}`:S.name,style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",children:W?"📁":S.name===".index.json"?"🔒":"□"}),s.jsxs("span",{className:"plan-file-browser__name",children:[S.name,W?"/":""]}),!W&&s.jsx("span",{className:"plan-file-browser__size",children:Bn(S.size)}),!S.name.startsWith(".")&&s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:J=>{J.stopPropagation(),L(S)},title:`Delete ${S.name}`,children:"×"})]},S.name)})]})]})}const It={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},Hs=200;function Us(){const[n,e]=a.useState(It),t=a.useRef("lines"),r=a.useRef([]),o=a.useRef(""),i=a.useRef(""),l=a.useRef([]),u=a.useRef(0),p=a.useRef(0),c=a.useRef(null),d=a.useRef(null),f=a.useCallback(()=>{const E=t.current;e(b=>({...b,receivedBytes:u.current,...E==="lines"?{lines:[...r.current]}:{},...E==="content"?{content:i.current}:{}}))},[]),h=a.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,f()},Hs))},[f]),m=a.useCallback(E=>{t.current=E,r.current=[],o.current="",i.current="",l.current=[],u.current=0,p.current=0,d.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...It,mode:E,status:"streaming"})},[]),x=a.useCallback(E=>{u.current+=E.length;const b=t.current;if(b==="lines"){const w=d.current.decode(E,{stream:!0}).split(`
|
|
30
|
+
`);w[0]=o.current+w[0],o.current=w.pop(),w.length>0&&r.current.push(...w)}else if(b==="content"){const j=d.current.decode(E,{stream:!0});i.current+=j}else l.current.push(new Uint8Array(E));h()},[h]),T=a.useCallback(E=>{switch(E.type){case"file-stream-start":p.current=E.size,e(b=>({...b,totalSize:E.size,mtime:E.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const b=t.current;let j=r.current,w=i.current,N=null;if(b==="lines"){const L=d.current.decode(),_=o.current+L;_&&(j=[...j,_],r.current=j),o.current=""}else if(b==="content"){const L=d.current.decode();w=i.current+L,i.current=w}else{const L=l.current.reduce((B,P)=>B+P.length,0);N=new Uint8Array(L);let _=0;for(const B of l.current)N.set(B,_),_+=B.length;l.current=[]}e({status:"complete",mode:b,lines:b==="lines"?[...j]:[],content:b==="content"?w:"",buffer:b==="binary"?N:null,totalSize:p.current,receivedBytes:u.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(b=>({...b,status:"error",error:E.error}));break}},[]),k=a.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),r.current=[],o.current="",i.current="",l.current=[],u.current=0,p.current=0,d.current=null,e(It)},[]);return{state:n,startStream:m,handleChunk:x,handleControl:T,reset:k}}function gn({label:n,percent:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:n}),e!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function Ks({sessionId:n,token:e,connected:t,onRequestFileStream:r,onSendToTerminal:o}){const i=Us(),[l,u]=a.useState(!1),[p,c]=a.useState(null),[d,f]=a.useState(null),[h,m]=a.useState(""),[x,T]=a.useState(!1),[k,E]=a.useState(!1),b=a.useRef(null),j="plan-selected-file",w=a.useRef(void 0);a.useEffect(()=>{if(d)return clearTimeout(w.current),w.current=setTimeout(()=>{try{localStorage.setItem(j,d)}catch{}},50),()=>clearTimeout(w.current)},[d]);const N=a.useRef(null);a.useEffect(()=>{N.current=null;let O=!1;return T(!0),E(!1),(async()=>{let U="";try{const Z=await Le(e,n);if(O)return;if(U=Z.home||"",Z.files.find(q=>q.name==="AiTasks"&&q.type==="directory")){const q=Z.cwd+"/AiTasks";c(q);const te=localStorage.getItem(j);te&&te.startsWith(q+"/")&&f(te)}else c(null),f(null),E(!0)}catch{c(null)}finally{O||T(!1)}try{if(O)return;if(U){const Z=`${U}/.claude/plugins/installed_plugins.json`,Q=await it(e,n,Z,0);if(!O&&Q)try{const q=JSON.parse(Q.content);"ai-cli-task@moonview"in(q.plugins||q)||u(!0)}catch{u(!0)}}}catch{}})(),()=>{O=!0}},[n,e]),a.useEffect(()=>{if(!k||!t)return;const O=setInterval(async()=>{try{const U=await Le(e,n);if(U.files.find(Q=>Q.name==="AiTasks"&&Q.type==="directory")){const Q=U.cwd+"/AiTasks";c(Q),E(!1);const q=localStorage.getItem(j);q&&q.startsWith(Q+"/")&&f(q)}}catch{}},3e3);return()=>clearInterval(O)},[k,t,e,n,j]),a.useEffect(()=>(qr(n,i.handleChunk,i.handleControl),()=>Yr(n)),[n,i.handleChunk,i.handleControl]),a.useEffect(()=>{!d||!t||N.current===d&&h||(N.current=d,i.reset(),i.startStream("content"),r==null||r(d))},[d,t]);const L=a.useRef(0);a.useEffect(()=>{i.state.status==="complete"&&d&&(m(i.state.content),L.current=Date.now())},[i.state.status,i.state.content,d]),a.useEffect(()=>{if(!d||!t||!h)return;const O=setInterval(async()=>{if(L.current)try{const U=await it(e,n,d,L.current);U&&(m(U.content),L.current=U.mtime)}catch{}},3e3);return()=>clearInterval(O)},[d,t,h,e,n]);const _=a.useRef(new Map),B=a.useCallback(()=>{var U,Z;if(!d)return;const O=((Z=(U=b.current)==null?void 0:U.getScrollTop)==null?void 0:Z.call(U))??0;O>0&&_.current.set(d,O)},[d]);a.useEffect(()=>{if(!d||!h)return;const O=_.current.get(d);O!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var U,Z;(Z=(U=b.current)==null?void 0:U.setScrollTop)==null||Z.call(U,O)})})},[d,h]);const P=a.useCallback(O=>{O!==d&&(B(),f(O),m(""),N.current=null)},[d,B]),F=a.useCallback(O=>{d&&(d===O||d.startsWith(O+"/"))&&(f(null),m(""),N.current=null)},[d]),D=a.useCallback(O=>{f(O),m(""),N.current=null},[]),C=a.useCallback(O=>{O&&(o==null||o(O))},[o]),S=a.useCallback((O,U)=>{m(O),L.current=U},[]),X=a.useCallback(()=>{B(),f(null),m(""),N.current=null},[B]),V=a.useCallback(()=>{!d||!t||(N.current=null,m(""),i.reset(),i.startStream("content"),r==null||r(d),N.current=d)},[d,t,i,r]),[W,J]=a.useState(()=>{const O=localStorage.getItem(`plan-fb-width-${n}`);if(O){const U=Number(O);if(Number.isFinite(U)&&U>=60&&U<=300)return U}return 130}),ee=a.useRef(W);if(W!==ee.current){ee.current=W;try{localStorage.setItem(`plan-fb-width-${n}`,String(Math.round(W)))}catch{}}const Y=a.useCallback(O=>{O.preventDefault();const U=O.clientX,Z=W;document.body.classList.add("resizing-panes");const Q=te=>{const ye=te.clientX-U;J(Math.min(300,Math.max(60,Z+ye)))},q=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",Q),document.removeEventListener("mouseup",q)};document.addEventListener("mousemove",Q),document.addEventListener("mouseup",q)},[W]),I=a.useMemo(()=>{if(!p||!d||!d.startsWith(p+"/"))return null;const O=d.substring(p.length+1),U=O.indexOf("/");if(U<0)return null;const Z=O.substring(0,U);return!Z||Z.startsWith(".")?null:{name:Z,dir:`${p}/${Z}`}},[p,d]),A=I==null?void 0:I.dir,[K,H]=a.useState(null),ne=a.useRef(0);a.useEffect(()=>{H(null),ne.current=0},[A]),a.useEffect(()=>{if(!A||!t)return;let O=!1;const U=async()=>{try{const Q=await it(e,n,`${A}/.index.json`,ne.current||void 0);if(O)return;if(Q){ne.current=Q.mtime;try{const q=JSON.parse(Q.content);H({status:q.status||"draft",phase:q.phase||"",type:q.type||"",completed_steps:q.completed_steps||0,title:q.title||""})}catch{}}}catch{}};U();const Z=setInterval(U,3e3);return()=>{O=!0,clearInterval(Z)}},[A,t,e,n]);const[ae,xe]=a.useState(null);a.useEffect(()=>{xe(null)},[A]),a.useEffect(()=>{if(!A||!t)return;let O=!1;const U=async()=>{try{const Q=await it(e,n,`${A}/.auto-signal`);if(O)return;if(Q)try{const q=JSON.parse(Q.content);xe({step:q.step,result:q.result,next:q.next,iteration:q.iteration})}catch{xe(null)}}catch{O||xe(null)}};U();const Z=setInterval(U,2e3);return()=>{O=!0,clearInterval(Z)}},[A,t,e,n]);const ze=a.useCallback(()=>{!I||!o||o(`/moonview:auto AiTasks/${I.name}`)},[I,o]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[l&&s.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:[s.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),s.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{o&&o("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),u(!1)},children:"Install"}),s.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>u(!1),children:"×"})]}),s.jsxs("div",{className:"plan-overlay-body",children:[p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:W,flexShrink:0,overflow:"hidden"},children:s.jsx(Ws,{sessionId:n,token:e,planDir:p,selectedFile:d,onSelectFile:P,onCreateFile:D,onDeleteFile:F})}),s.jsx("div",{onMouseDown:Y,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:O=>{O.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:O=>{O.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsx("div",{className:"plan-overlay-center",children:x?s.jsx(gn,{label:"Loading AiTasks/..."}):k?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),s.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",s.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/moonview:init <name>"})," in the terminal to create a task"]})]}):d&&!h&&(i.state.status==="streaming"||i.state.status==="idle")?s.jsx(gn,{label:`Loading ${d.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):d?s.jsx(As,{ref:b,markdown:h,filePath:d,sessionId:n,token:e,onExecute:C,onSend:o,onRefresh:V,onClose:X,onContentSaved:S,readOnly:d.endsWith("/.index.json")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]}),I&&K&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--border)",fontSize:11,flexShrink:0,minHeight:22},children:[s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:500},title:K.title,children:I.name}),s.jsx("span",{style:{color:K.status==="complete"?"var(--accent-green)":K.status==="executing"||K.status==="review"?"var(--accent-blue)":K.status==="blocked"?"var(--accent-red)":K.status==="cancelled"?"var(--text-secondary)":"var(--accent-yellow)",fontWeight:500},children:K.status}),K.phase&&s.jsxs("span",{style:{color:"var(--text-secondary)"},children:["(",K.phase,")"]}),ae?s.jsxs("span",{style:{color:"var(--accent-yellow)"},children:[ae.step,":",ae.result," → ",ae.next,ae.iteration!=null&&` #${ae.iteration}`]}):s.jsx("button",{className:"pane-btn",onClick:ze,disabled:!t||K.status==="complete"||K.status==="cancelled",style:{color:"var(--accent-green)",fontWeight:500,fontSize:11,...!t||K.status==="complete"||K.status==="cancelled"?{opacity:.4}:{}},title:"Start auto mode for this task",children:"Auto ▶"}),K.completed_steps>0&&s.jsxs("span",{style:{color:"var(--text-secondary)",marginLeft:"auto"},children:["step ",K.completed_steps]})]})]})}async function Gs(n,e,t={}){const r={};return t.page&&(r.page=String(t.page)),t.limit&&(r.limit=String(t.limit)),t.file&&(r.file=t.file),t.all&&(r.all="true"),t.branch&&(r.branch=t.branch),pe.get(e,n,"git-log",r)}async function Js(n,e,t,r){const o={commit:t};return r&&(o.file=r),(await pe.get(e,n,"git-diff",o)).diff}async function Vs(n,e){return pe.get(e,n,"git-branches")}const pt=["#0085d9","#d9008f","#3fb950","#d98500","#a300d9","#56d4dd","#e05050","#00d9a3"];function qs(n){const e=new Map;if(n.length===0)return e;const t=[],r=[];let o=1;const i=new Map,l=new Map;function u(p){for(let d=0;d<t.length;d++)if(t[d]===null)return t[d]=p,r[d]=d===0?0:o++%pt.length,d;const c=t.length;return t.push(p),r[c]=c===0?0:o++%pt.length,c}for(const p of n){const{hash:c,parents:d}=p,f=d.length>1,h=t.indexOf(c)!==-1;let m=h?t.indexOf(c):u(c);const x=r[m],T=[],k=[];for(let b=0;b<t.length;b++)b!==m&&t[b]===c&&(T.push({fromLane:b,toLane:m,colorIndex:r[b],type:"merge-in"}),t[b]=null);if(d.length===0)t[m]=null;else{t[m]=d[0];for(let b=1;b<d.length;b++){const j=d[b],w=t.indexOf(j);if(w!==-1)T.push({fromLane:w,toLane:m,colorIndex:r[w],type:"merge-in"});else if(i.has(j)){const N=i.get(j),L=l.get(j);T.push({fromLane:N,toLane:m,colorIndex:L,type:"merge-in"})}else{const N=u(j);k.push(N),T.push({fromLane:m,toLane:N,colorIndex:r[N],type:"branch-out"})}}}for(;t.length>0&&t[t.length-1]===null;)t.pop(),r.pop();const E=[];for(let b=0;b<t.length;b++)t[b]!==null&&E.push({lane:b,colorIndex:r[b]});i.set(c,m),l.set(c,x),e.set(c,{lane:m,activeLanes:E,connections:T,colorIndex:x,isMerge:f,newLanes:k,wasExpected:h})}return e}function Ys(n){const e=Date.now()-new Date(n).getTime(),t=Math.floor(e/6e4);if(t<1)return"now";if(t<60)return`${t}m`;const r=Math.floor(t/60);if(r<24)return`${r}h`;const o=Math.floor(r/24);if(o<30)return`${o}d`;const i=Math.floor(o/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}const mt=20,Ae=32,Xs=4,Zs=5,Te=Ae/2;function Re(n){return n*mt+mt/2}function qe(n){return pt[n%pt.length]}function Qs(n){if(n.type==="branch-out"){const e=Re(n.fromLane),t=Re(n.toLane);if(e===t)return`M ${e} ${Te} L ${e} ${Ae}`;const r=(Ae-Te)*.8;return`M ${e} ${Te} C ${e} ${Te+r}, ${t} ${Ae-r}, ${t} ${Ae}`}else{const e=Re(n.fromLane),t=Re(n.toLane);if(e===t)return`M ${e} 0 L ${e} ${Te}`;const r=Te*.8;return`M ${e} 0 C ${e} ${r}, ${t} ${Te-r}, ${t} ${Te}`}}const eo=a.memo(function({laneNode:e,maxLanes:t}){const r=t*mt,o=e.newLanes;return s.jsxs("svg",{width:r,height:Ae,style:{flexShrink:0,display:"block"},children:[e.activeLanes.map(i=>o.includes(i.lane)?null:s.jsx("line",{x1:Re(i.lane),y1:0,x2:Re(i.lane),y2:Ae,stroke:qe(i.colorIndex),strokeWidth:2,strokeLinecap:"round"},`active-${i.lane}`)),e.connections.map((i,l)=>s.jsx("path",{d:Qs(i),stroke:qe(i.colorIndex),strokeWidth:2,fill:"none",strokeLinecap:"round"},`conn-${l}`)),e.wasExpected&&!e.activeLanes.some(i=>i.lane===e.lane)&&!o.includes(e.lane)&&s.jsx("line",{x1:Re(e.lane),y1:0,x2:Re(e.lane),y2:Te,stroke:qe(e.colorIndex),strokeWidth:2,strokeLinecap:"round"}),e.isMerge?s.jsx("circle",{cx:Re(e.lane),cy:Te,r:Zs,fill:"var(--bg-primary)",stroke:qe(e.colorIndex),strokeWidth:2}):s.jsx("circle",{cx:Re(e.lane),cy:Te,r:Xs,fill:qe(e.colorIndex)})]})}),to={head:{bg:"var(--accent-red)",color:"#fff"},branch:{bg:"var(--accent-blue)",color:"#fff"},remote:{bg:"var(--accent-purple)",color:"#fff"},tag:{bg:"var(--accent-green)",color:"#fff"}};function no({refs:n,fontSize:e}){if(n.length===0)return null;const t=e-4;return s.jsx(s.Fragment,{children:n.map((r,o)=>{const i=to[r.type];return s.jsx("span",{style:{display:"inline-block",padding:"0 4px",borderRadius:3,fontSize:t,lineHeight:`${t+6}px`,backgroundColor:i.bg,color:i.color,whiteSpace:"nowrap",flexShrink:0,fontFamily:"'JetBrains Mono', monospace"},children:r.type==="head"&&r.name!=="HEAD"?`HEAD → ${r.name}`:r.name},o)})})}function ro(n){const e=n.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return e?[parseInt(e[1],10),parseInt(e[2],10)]:[1,1]}const so=a.memo(function({diff:e,fontSize:t}){if(!e.trim())return s.jsx("div",{style:{padding:8,color:"var(--text-secondary)",fontSize:t},children:"No diff available"});const r=[];let o=null,i=1,l=1;for(const p of e.split(`
|
|
31
|
+
`))if(p.startsWith("@@")){const[c,d]=ro(p);i=c,l=d,o={header:p,lines:[]},r.push(o)}else p.startsWith("diff ")||p.startsWith("index ")||p.startsWith("---")||p.startsWith("+++")||o&&(p.startsWith("+")?o.lines.push({type:"add",text:p,oldNum:null,newNum:l++}):p.startsWith("-")?o.lines.push({type:"del",text:p,oldNum:i++,newNum:null}):o.lines.push({type:"context",text:p,oldNum:i++,newNum:l++}));const u=t*2.6;return s.jsx("div",{style:{fontSize:t,fontFamily:"'JetBrains Mono', monospace",overflow:"auto"},children:r.map((p,c)=>s.jsxs("div",{children:[s.jsx("div",{style:{padding:"2px 8px",paddingLeft:u*2+12,backgroundColor:"var(--bg-secondary)",color:"var(--accent-cyan)",fontSize:t-1,borderTop:c>0?"1px solid var(--border)":void 0},children:p.header}),p.lines.map((d,f)=>s.jsxs("div",{style:{display:"flex",whiteSpace:"pre",backgroundColor:d.type==="add"?"rgba(63, 185, 80, 0.12)":d.type==="del"?"rgba(248, 81, 73, 0.12)":"transparent"},children:[s.jsx("span",{style:{display:"inline-block",width:u,textAlign:"right",paddingRight:4,color:"var(--text-secondary)",opacity:.5,flexShrink:0,userSelect:"none"},children:d.oldNum??""}),s.jsx("span",{style:{display:"inline-block",width:u,textAlign:"right",paddingRight:6,color:"var(--text-secondary)",opacity:.5,flexShrink:0,userSelect:"none",borderRight:"1px solid var(--border)",marginRight:6},children:d.newNum??""}),s.jsx("span",{style:{flex:1,color:d.type==="add"?"var(--accent-green)":d.type==="del"?"var(--accent-red)":"var(--text-primary)"},children:d.text})]},f))]},c))})}),oo=a.memo(function({commit:e,sessionId:t,token:r,fontSize:o,laneNode:i,maxLanes:l}){const[u,p]=a.useState(!1),[c,d]=a.useState(null),[f,h]=a.useState(""),[m,x]=a.useState(!1),[T,k]=a.useState(!1),E=a.useRef(c);E.current=c;const b=a.useCallback(async L=>{if(E.current===L){d(null);return}d(L),x(!0);try{const _=await Js(t,r,e.hash,L);h(_)}catch{h("Failed to load diff")}finally{x(!1)}},[t,r,e.hash]),j=o-2,w=o-4,N=l*mt;return s.jsxs("div",{children:[s.jsxs("div",{onClick:()=>p(!u),style:{padding:"2px 8px",cursor:"pointer",display:"flex",flexDirection:"row",alignItems:"center",gap:4,height:Ae},onMouseEnter:L=>{L.currentTarget.style.backgroundColor="var(--bg-hover)"},onMouseLeave:L=>{L.currentTarget.style.backgroundColor="transparent"},children:[i&&l>0&&s.jsx(eo,{laneNode:i,maxLanes:l}),s.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:6},children:[s.jsx(no,{refs:e.refs,fontSize:o}),s.jsx("span",{style:{fontSize:j,color:"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:e.message}),s.jsxs("span",{style:{fontSize:w,color:"var(--text-secondary)",flexShrink:0,whiteSpace:"nowrap"},children:[e.author.split(" ")[0]," · ",Ys(e.date)]}),s.jsx("span",{title:"Click to copy full hash",style:{fontSize:w,color:T?"var(--accent-green)":"var(--accent-yellow)",fontFamily:"'JetBrains Mono', monospace",flexShrink:0,opacity:T?1:.6,cursor:"pointer",transition:"color 0.2s, opacity 0.2s"},onClick:L=>{L.stopPropagation(),navigator.clipboard.writeText(e.hash).then(()=>{k(!0),setTimeout(()=>k(!1),1500)})},children:T?"Copied":e.shortHash}),s.jsx("span",{style:{fontSize:w,color:"var(--text-secondary)",flexShrink:0},children:u?"▼":"▶"})]})]}),u&&s.jsx("div",{style:{padding:"0 10px 6px",marginLeft:N+10},children:e.files.length===0?s.jsx("div",{style:{fontSize:j,color:"var(--text-secondary)",padding:"4px 0"},children:"No files changed"}):e.files.map(L=>s.jsxs("div",{children:[s.jsxs("div",{onClick:()=>b(L.path),style:{display:"flex",alignItems:"center",gap:6,padding:"2px 4px",cursor:"pointer",fontSize:o,borderRadius:3},onMouseEnter:_=>{_.currentTarget.style.backgroundColor="var(--bg-hover)"},onMouseLeave:_=>{_.currentTarget.style.backgroundColor="transparent"},children:[s.jsxs("span",{style:{fontSize:w,color:"var(--accent-green)",fontFamily:"'JetBrains Mono', monospace",minWidth:28,textAlign:"right"},children:["+",L.additions]}),s.jsxs("span",{style:{fontSize:w,color:"var(--accent-red)",fontFamily:"'JetBrains Mono', monospace",minWidth:28,textAlign:"right"},children:["-",L.deletions]}),s.jsx("span",{style:{color:c===L.path?"var(--accent-blue)":"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:L.path})]}),c===L.path&&s.jsx("div",{style:{margin:"2px 0 4px",border:"1px solid var(--border)",borderRadius:4,overflow:"hidden",maxHeight:400,overflowY:"auto"},children:m?s.jsx("div",{style:{padding:8,color:"var(--text-secondary)",fontSize:o},children:"Loading..."}):s.jsx(so,{diff:f,fontSize:o})})]},L.path))})]})}),ao=a.memo(function({sessionId:e,token:t}){const r=z(I=>I.fontSize),[o,i]=a.useState([]),[l,u]=a.useState(1),[p,c]=a.useState(!1),[d,f]=a.useState(!1),[h,m]=a.useState(null),[x,T]=a.useState(""),[k,E]=a.useState(""),[b,j]=a.useState(!1),[w,N]=a.useState([]),[L,_]=a.useState(""),[B,P]=a.useState(""),F=a.useRef(0),D=a.useRef(null);a.useEffect(()=>{Vs(e,t).then(({current:I,branches:A})=>{_(I),N(A)}).catch(()=>{})},[e,t]);const C=a.useCallback(async(I,A,K,H,ne)=>{f(!0),m(null);try{const ae=await Gs(e,t,{page:I,file:A||void 0,all:H||void 0,branch:ne||void 0});ae.error&&m(ae.error),i(xe=>K?[...xe,...ae.commits]:ae.commits),c(ae.hasMore),u(I)}catch(ae){m(ae instanceof Error?ae.message:"Failed to load")}finally{f(!1)}},[e,t]);a.useEffect(()=>{C(1,x,!1,b,B)},[x,b,B,C]);const S=a.useCallback(I=>{const A=I.target.value;E(A),F.current&&clearTimeout(F.current),F.current=window.setTimeout(()=>T(A),300)},[]);a.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]);const X=a.useCallback(()=>{!d&&p&&C(l+1,x,!0,b,B)},[d,p,l,x,b,B,C]),V=a.useRef(0),W=a.useCallback(()=>{V.current||(V.current=requestAnimationFrame(()=>{V.current=0;const I=D.current;!I||d||!p||I.scrollTop+I.clientHeight>=I.scrollHeight-50&&X()}))},[d,p,X]);a.useEffect(()=>()=>{V.current&&cancelAnimationFrame(V.current)},[]);const J=a.useMemo(()=>qs(o),[o]),ee=a.useMemo(()=>{let I=0;for(const A of J.values()){let K=A.lane+1;for(let H=0;H<A.activeLanes.length;H++){const ne=A.activeLanes[H].lane+1;ne>K&&(K=ne)}K>I&&(I=K)}return Math.min(I,15)},[J]),Y=r-2;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",gap:6,borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[s.jsxs("select",{value:b?"__all__":B,onChange:I=>{const A=I.target.value;A==="__all__"?(j(!0),P("")):(j(!1),P(A))},style:{fontSize:Y,padding:"1px 2px",border:"1px solid var(--border)",borderRadius:3,backgroundColor:"var(--bg-primary)",color:"var(--text-primary)",outline:"none",flexShrink:0,maxWidth:130},title:"Select branch",children:[s.jsx("option",{value:"",children:L||"HEAD"}),w.filter(I=>I!==L).map(I=>s.jsx("option",{value:I,children:I},I)),s.jsx("option",{value:"__all__",children:"-- All branches --"})]}),s.jsx("input",{type:"text",value:k,onChange:S,placeholder:"Filter by file...",style:{flex:1,fontSize:Y,padding:"2px 6px",border:"1px solid var(--border)",borderRadius:3,backgroundColor:"var(--bg-primary)",color:"var(--text-primary)",outline:"none",minWidth:0}})]}),h&&s.jsx("div",{style:{padding:"4px 8px",fontSize:Y,color:"var(--accent-red)",backgroundColor:"var(--bg-secondary)"},children:h}),s.jsxs("div",{ref:D,onScroll:W,style:{flex:1,overflowY:"auto",minHeight:0},children:[o.map(I=>s.jsx(oo,{commit:I,sessionId:e,token:t,fontSize:r,laneNode:J.get(I.hash),maxLanes:ee},I.hash)),d&&s.jsx("div",{style:{padding:12,textAlign:"center",color:"var(--text-secondary)",fontSize:r},children:"Loading..."}),!d&&o.length===0&&!h&&s.jsx("div",{style:{padding:12,textAlign:"center",color:"var(--text-secondary)",fontSize:r},children:"No commits found"}),!d&&p&&s.jsx("div",{style:{padding:8,textAlign:"center"},children:s.jsx("button",{className:"pane-btn",onClick:X,style:{fontSize:Y},children:"Load more"})})]})]})});async function io(n,e){try{return(await pe.get(n,e,"draft")).content??""}catch{return""}}async function xn(n,e,t){try{await pe.put(n,e,"draft",{content:t})}catch{}}const zt="chat-history",bn=50;function Wn(){try{const n=localStorage.getItem(zt);return n?JSON.parse(n):[]}catch{return[]}}function lo(n){const t=Wn().filter(r=>r.text!==n);t.unshift({text:n,ts:Date.now()}),t.length>bn&&(t.length=bn),localStorage.setItem(zt,JSON.stringify(t))}const yn=[{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:"/moonview:ai-cli-task",desc:"Task lifecycle management (13 skills)"},{cmd:"/moonview:init",desc:"Initialize task module + branch"},{cmd:"/moonview:plan",desc:"Generate implementation plan"},{cmd:"/moonview:research",desc:"Collect external references"},{cmd:"/moonview:check",desc:"Check feasibility (post-plan/mid/post-exec)"},{cmd:"/moonview:verify",desc:"Run domain-adapted tests"},{cmd:"/moonview:exec",desc:"Execute implementation plan"},{cmd:"/moonview:merge",desc:"Merge task branch to main"},{cmd:"/moonview:report",desc:"Generate completion report"},{cmd:"/moonview:auto",desc:"Autonomous full lifecycle loop"},{cmd:"/moonview:cancel",desc:"Cancel task + optional cleanup"},{cmd:"/moonview:list",desc:"Query task status (read-only)"},{cmd:"/moonview:annotate",desc:"Process Plan panel annotations"},{cmd:"/moonview:summarize",desc:"Regenerate context summary"}],co=a.forwardRef(function({onSend:e,onContentChange:t,sessionId:r,token:o},i){const l=z(v=>v.fontSize),[u,p]=a.useState(""),c=a.useRef(null),d=a.useRef(void 0),f=a.useRef(!1),h=a.useRef(!1),{pushUndo:m,popUndo:x}=Nt(),T=a.useRef(u);T.current=u;const k=a.useCallback(()=>m(T.current),[m]),[E,b]=a.useState(!1),[j,w]=a.useState(""),[N,L]=a.useState(0),[_,B]=a.useState(!1),[P,F]=a.useState([]),[D,C]=a.useState(0),[S,X]=a.useState(""),V=a.useRef(null),W=a.useMemo(()=>{if(!S)return P;const v=S.toLowerCase();return P.filter(R=>R.text.toLowerCase().includes(v))},[P,S]),[J,ee]=a.useState(!1),[Y,I]=a.useState(""),[A,K]=a.useState(""),[H,ne]=a.useState(0),[ae,xe]=a.useState([]),[ze,O]=a.useState(!1),U=a.useRef(""),Z=a.useRef(null),Q=a.useMemo(()=>{if(!j)return yn;const v=j.toLowerCase();return yn.filter(R=>R.cmd.toLowerCase().includes(v)||R.desc.toLowerCase().includes(v))},[j]),q=a.useMemo(()=>{let v=ae;if(Y){const R=Y.toLowerCase();v=v.filter(G=>G.name.toLowerCase().includes(R))}return[...v].sort((R,G)=>R.type==="directory"&&G.type!=="directory"?-1:R.type!=="directory"&&G.type==="directory"?1:R.name.localeCompare(G.name))},[ae,Y]),te=z(v=>v.latency),ye=`chat-draft-${r}`,je=a.useRef(!1),Ie=a.useRef(void 0);a.useEffect(()=>{try{const R=localStorage.getItem(ye);R&&!h.current&&p(R)}catch{}let v=!1;return io(o,r).then(R=>{if(v||h.current){f.current=!0;return}if(R){p(R);try{localStorage.setItem(ye,R)}catch{}}f.current=!0}).catch(()=>{f.current=!0}),()=>{v=!0}},[o,r,ye]),a.useEffect(()=>{if(!f.current)return;d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{try{localStorage.setItem(ye,u)}catch{}},50),Ie.current&&clearTimeout(Ie.current);const v=Math.max(200,(te??30)*3);return Ie.current=setTimeout(()=>{je.current||(je.current=!0,xn(o,r,u).catch(()=>{}).finally(()=>{je.current=!1}))},v),()=>{d.current&&clearTimeout(d.current),Ie.current&&clearTimeout(Ie.current)}},[u,o,r,te,ye]),a.useEffect(()=>{var v;(v=c.current)==null||v.focus()},[]),a.useEffect(()=>{if(!J)return;let v=!1;return O(!0),(async()=>{try{if(A){if(!U.current){const se=await Le(o,r);if(v)return;U.current=se.cwd}const R=`${U.current}/${A.replace(/\/$/,"")}`,G=await Le(o,r,R);if(v)return;xe(G.files)}else{const R=await Le(o,r);if(v)return;U.current=R.cwd,xe(R.files)}O(!1)}catch{if(v)return;xe([]),O(!1)}})(),()=>{v=!0}},[J,A,o,r]),a.useEffect(()=>{if(!J||!Z.current)return;const v=Z.current.querySelector(".file-item--active");v==null||v.scrollIntoView({block:"nearest"})},[H,J]);const _e=a.useCallback(()=>{const v=T.current.trim();if(v){lo(v),e(v),p("");try{localStorage.removeItem(ye)}catch{}xn(o,r,"").catch(()=>{})}},[e,o,r,ye]),ce=a.useCallback(v=>{k(),p(v),h.current=!0},[k]),Se=a.useCallback(v=>{const R=c.current;k();const G=T.current;if(R){const se=R.selectionStart,ie=R.selectionEnd,ke=G.slice(0,se)+v+G.slice(ie);p(ke);const de=se+v.length;requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=de,R.focus()})}else p(G+v)},[k]);a.useImperativeHandle(i,()=>({send:_e,fillContent:ce,insertAtCursor:Se}),[_e,ce,Se]),a.useEffect(()=>{t==null||t(u.trim().length>0)},[u,t]);const me=a.useCallback(()=>{const v=c.current;if(!v)return;const{selectionStart:R,selectionEnd:G}=v;if(R!==G){const se=v.value.substring(R,G);se&&navigator.clipboard.writeText(se).catch(()=>{})}},[]),Je=a.useCallback(()=>{const v=Wn();b(!1),w("");const R=c.current;if(R){const G=R.selectionStart,se=u.slice(0,G),ie=u.slice(G),ke=se.match(/(?:^|\s)(\/history)\s*$/);if(ke){const de=se.length-ke[1].length;p(u.slice(0,de)+ie)}}v.length!==0&&(F(v),C(0),X(""),B(!0))},[u]),Be=a.useCallback(v=>{k(),p(v.text),B(!1),requestAnimationFrame(()=>{const R=c.current;R&&(R.selectionStart=R.selectionEnd=v.text.length,R.focus())})},[k]),Pe=a.useCallback(v=>{const R=W[v];if(!R)return;const G=P.filter(ie=>ie.ts!==R.ts||ie.text!==R.text);F(G),localStorage.setItem(zt,JSON.stringify(G));const se=S?G.filter(ie=>ie.text.toLowerCase().includes(S.toLowerCase())):G;D>=se.length&&C(Math.max(0,se.length-1))},[W,P,D,S]);a.useEffect(()=>{if(!_||!V.current)return;const v=V.current.querySelector(".history-item--active");v==null||v.scrollIntoView({block:"nearest"})},[D,_]);const Me=a.useCallback(v=>{if(v==="/history"){Je();return}const R=c.current;if(!R)return;k();const G=R.selectionStart,se=u.slice(0,G),ie=u.slice(G),de=se.lastIndexOf(`
|
|
32
|
+
`)+1,ge=se.slice(de).match(/\/[a-zA-Z:-]*$/);if(ge){const ue=de+(ge.index??0),we=v+" ",Ve=u.slice(0,ue)+we+ie;p(Ve);const We=ue+we.length;requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=We,R.focus()})}else{const ue=se+v+ie;p(ue);const we=G+v.length;requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=we,R.focus()})}b(!1),w(""),L(0)},[u,k,Je]),Ne=a.useCallback(v=>{const R=c.current;if(!R)return;k();const G=R.selectionStart,se=u.slice(0,G),ie=u.slice(G),ke=se.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!ke)return;const de=se.length-ke[0].length;if(v.type==="directory"){const be="@"+A+v.name+"/",ge=u.slice(0,de)+be+ie;p(ge);const ue=de+be.length;K(A+v.name+"/"),I(""),ne(0),requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=ue,R.focus()})}else{const be=v.name+" ",ge=u.slice(0,de)+be+ie;p(ge);const ue=de+be.length;ee(!1),I(""),K(""),ne(0),xe([]),U.current="",requestAnimationFrame(()=>{R.selectionStart=R.selectionEnd=ue,R.focus()})}},[u,A,k]),et=a.useCallback(v=>{const R=v.target.value;if(p(R),_){const be=R.trim();be?(X(be),C(0)):X("");return}const G=v.target.selectionStart,se=R.slice(0,G),ie=se.lastIndexOf(`
|
|
33
|
+
`),de=se.slice(ie+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(de)b(!0),w(de[1]),L(0),ee(!1);else{b(!1);const be=se.match(/@([a-zA-Z0-9_.\-/]*)$/);if(be){const ge=be[1],ue=ge.lastIndexOf("/"),we=ue>=0?ge.slice(0,ue+1):"",Ve=ue>=0?ge.slice(ue+1):ge;I(Ve),ne(0),K(we),ee(!0)}else ee(!1)}},[_]),yt=a.useCallback(v=>{if(E&&Q.length>0){if(v.key==="ArrowDown"){v.preventDefault(),L(R=>(R+1)%Q.length);return}if(v.key==="ArrowUp"){v.preventDefault(),L(R=>(R-1+Q.length)%Q.length);return}if(v.key==="Enter"||v.key==="Tab"){v.preventDefault(),Me(Q[N].cmd);return}if(v.key==="Escape"){v.preventDefault(),b(!1);return}}if(J&&q.length>0){if(v.key==="ArrowDown"){v.preventDefault(),ne(R=>(R+1)%q.length);return}if(v.key==="ArrowUp"){v.preventDefault(),ne(R=>(R-1+q.length)%q.length);return}if(v.key==="Tab"||v.key==="Enter"){v.preventDefault(),Ne(q[H]);return}if(v.key==="Escape"){v.preventDefault(),ee(!1);return}}if(_&&W.length>0){if(v.key==="ArrowDown"){v.preventDefault(),C(R=>(R+1)%W.length);return}if(v.key==="ArrowUp"){v.preventDefault(),C(R=>(R-1+W.length)%W.length);return}if(v.key==="Enter"){v.preventDefault(),Be(W[D]);return}if(v.key==="Delete"||v.key==="Backspace"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),Pe(D);return}if(v.key==="Escape"){v.preventDefault(),B(!1);return}}if(v.key==="Tab"){Dt(v,p,m);return}v.key==="Enter"&&(v.ctrlKey||v.metaKey)&&(v.preventDefault(),_e())},[_e,E,Q,N,Me,J,q,H,Ne,m,x,_,W,D,Be,Pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[E&&Q.length>0&&s.jsx("div",{className:"slash-dropdown",children:Q.map((v,R)=>s.jsxs("div",{className:`slash-item${R===N?" slash-item--active":""}`,onMouseDown:G=>{G.preventDefault(),Me(v.cmd)},onMouseEnter:()=>L(R),children:[s.jsx("span",{className:"slash-cmd",children:v.cmd}),s.jsx("span",{className:"slash-desc",children:v.desc})]},v.cmd))}),J&&(ze||q.length>0)&&s.jsx("div",{className:"file-dropdown",ref:Z,children:ze?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):q.map((v,R)=>s.jsxs("div",{className:`file-item${R===H?" file-item--active":""}`,onMouseDown:G=>{G.preventDefault(),Ne(v)},onMouseEnter:()=>ne(R),children:[s.jsx("span",{className:"file-icon",children:v.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:v.name})]},v.name))}),_&&s.jsx("div",{className:"history-dropdown",ref:V,children:W.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):W.map((v,R)=>s.jsxs("div",{className:`history-item${R===D?" history-item--active":""}`,onMouseDown:G=>{G.preventDefault(),Be(v)},onMouseEnter:()=>C(R),children:[s.jsx("span",{className:"history-text",children:v.text.length>120?v.text.slice(0,120)+"...":v.text}),s.jsx("span",{className:"history-time",children:new Date(v.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:G=>{G.preventDefault(),G.stopPropagation(),Pe(R)},title:"Delete (Del key)",children:"×"})]},`${v.ts}-${R}`))}),s.jsx("textarea",{ref:c,className:"md-editor-textarea",value:u,onChange:et,onKeyDown:yt,onMouseUp:me,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${l}px`}})]})});function uo({token:n,sessionId:e,onClose:t}){const[r,o]=a.useState([]),[i,l]=a.useState(""),[u,p]=a.useState([]),[c,d]=a.useState(!0),[f,h]=a.useState(!1),m=a.useRef(null);a.useEffect(()=>{let b=!1;return(async()=>{try{const j=await Le(n,e);b||(l(j.cwd),o(j.files))}catch{b||t()}finally{b||d(!1)}})(),()=>{b=!0}},[n,e,t]),a.useEffect(()=>{const b=N=>{N.key==="Escape"&&t()},j=N=>{m.current&&!m.current.contains(N.target)&&t()};document.addEventListener("keydown",b);const w=setTimeout(()=>document.addEventListener("mousedown",j),50);return()=>{document.removeEventListener("keydown",b),document.removeEventListener("mousedown",j),clearTimeout(w)}},[t]);const x=a.useCallback(async b=>{d(!0);try{const j=await Le(n,e,b);p(w=>[...w,i]),l(b),o(j.files)}catch{}finally{d(!1)}},[n,e,i]),T=a.useCallback(async()=>{if(u.length===0)return;const b=u[u.length-1];d(!0);try{const j=await Le(n,e,b);p(w=>w.slice(0,-1)),l(b),o(j.files)}catch{}finally{d(!1)}},[n,e,u]),k=a.useCallback(async b=>{try{await Bs(n,e,b)}catch(j){alert(`Download failed: ${j instanceof Error?j.message:"Unknown error"}`)}},[n,e]),E=a.useCallback(async()=>{h(!0),t();try{await Fs(n,e)}catch(b){alert(`Download failed: ${b instanceof Error?b.message:"Unknown error"}`)}finally{h(!1)}},[n,e,t]);return s.jsxs("div",{ref:m,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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[u.length>0&&s.jsx("button",{className:"pane-btn",onClick:T,disabled:c,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),s.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:i.split("/").slice(-2).join("/")||i}),s.jsx("button",{className:"pane-btn",onClick:t,style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:c?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(b=>s.jsxs("div",{onClick:()=>{const j=i+"/"+b.name;b.type==="directory"?x(j):k(j)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{flexShrink:0,fontSize:13},children:b.type==="directory"?"📁":Ps(b.name,b.type)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.name}),b.type==="directory"?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):b.size!=null?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:Bn(b.size)}):null]},b.name))}),s.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{className:"pane-btn",onClick:E,disabled:f,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:f?"Downloading...":"Download All (tar.gz)"})})]})}function vn(n,e,{containerRef:t,axis:r,offset:o=0,min:i,max:l,invert:u=!1,bodyClass:p}){const[c,d]=a.useState(()=>{const m=localStorage.getItem(n);if(m){const x=Number(m);if(Number.isFinite(x)&&x>=i&&x<=l)return x}return e}),f=a.useRef(c);if(c!==f.current){f.current=c;try{localStorage.setItem(n,String(Math.round(c)))}catch{}}const h=a.useCallback(m=>{m.preventDefault();const x=t.current;if(!x)return;const T=x.getBoundingClientRect(),k=r==="x"?T.width:T.height-o,E=r==="x"?T.left:T.top+o;document.body.classList.add(p);const b=w=>{let L=((r==="x"?w.clientX:w.clientY)-E)/k*100;u&&(L=100-L),d(Math.min(l,Math.max(i,L)))},j=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",j)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",j)},[t,r,o,i,l,u,p]);return[c,h]}const fo=600,Ke=typeof window<"u"?window.matchMedia(`(max-width: ${fo-1}px)`):null;function po(){const[n,e]=a.useState(()=>(Ke==null?void 0:Ke.matches)??!1);return a.useEffect(()=>{if(!Ke)return;const t=r=>e(r.matches);return Ke.addEventListener("change",t),()=>Ke.removeEventListener("change",t)},[]),n}const mo=a.memo(function({terminal:e}){const t=po(),r=z(I=>I.splitTerminal),o=z(I=>I.token),i=z(I=>I.toggleChat),l=z(I=>I.togglePlan),u=z(I=>I.toggleGitHistory),{chatOpen:p,planOpen:c,gitHistoryOpen:d}=e.panels,f=a.useRef(null),h=a.useRef(null),m=a.useRef(null),x=a.useRef(null),T=a.useRef(null),[k,E]=vn(`plan-width-${e.id}`,50,{containerRef:h,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[b,j]=vn(`doc-height-${e.id}`,35,{containerRef:f,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[w,N]=a.useState("");a.useEffect(()=>{if(!o||!e.connected)return;let I=!1;const A=async()=>{try{const H=await hn(o,e.id);I||N(H)}catch{}};A();const K=setInterval(A,5e3);return()=>{I=!0,clearInterval(K)}},[o,e.id,e.connected]);const L=a.useCallback(async I=>{let A;if(o)try{A=await hn(o,e.id)}catch{}r(e.id,I,A)},[o,e.id,r]),[_,B]=a.useState(!1),[P,F]=a.useState(0),[D,C]=a.useState(!1),[S,X]=a.useState(!1),V=async I=>{const A=I.target.files;if(!(!A||A.length===0||!o)){B(!0),F(0);try{await $s(o,e.id,A,K=>{F(K)})}catch(K){alert(`Upload failed: ${K instanceof Error?K.message:"Unknown error"}`)}finally{B(!1),F(0),m.current&&(m.current.value="")}}},W=a.useRef(void 0),J=a.useCallback(I=>{if(x.current){const A=I.replace(/\r?\n/g," ").trimEnd();x.current.sendInput(A),W.current=window.setTimeout(()=>{var K;return(K=x.current)==null?void 0:K.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{W.current&&clearTimeout(W.current)},[]);const ee=a.useCallback(I=>{if(x.current){const A=I.replace(/\r?\n/g," ").trimEnd();x.current.sendInput(A),setTimeout(()=>{var K;return(K=x.current)==null?void 0:K.sendInput("\r")},50)}},[]),Y=a.useCallback(()=>X(!1),[]);return s.jsxs("div",{ref:f,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),s.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]}),w&&s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:w,children:w})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:m,type:"file",multiple:!0,style:{display:"none"},onChange:V}),s.jsx("button",{className:"pane-btn",onClick:()=>{var I;return(I=m.current)==null?void 0:I.click()},disabled:_,style:_?{color:"var(--accent-yellow)"}:void 0,title:_?`Uploading ${P}%`:"Upload files","aria-label":"Upload files",children:_?`${P}%`:"↑"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>X(!0),title:"Download files","aria-label":"Download files",children:"↓"}),S&&o&&s.jsx(uo,{token:o,sessionId:e.id,onClose:Y})]}),s.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${c?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),s.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>u(e.id),title:"Toggle Git history panel","aria-label":"Toggle Git history panel",children:"Git"}),s.jsx("button",{className:"pane-btn",onClick:()=>L(t?"vertical":"horizontal"),title:t?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>L("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{ref:h,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[(c||d)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{width:`${k}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:[c&&s.jsx(Ks,{sessionId:e.id,token:o||"",connected:e.connected,onRequestFileStream:I=>{var A;return(A=x.current)==null?void 0:A.requestFileStream(I)},onSendToTerminal:ee}),d&&s.jsx(ao,{sessionId:e.id,token:o||""})]}),s.jsx("div",{className:"md-editor-divider-h",onMouseDown:E,style:{width:"3px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[s.jsx(ps,{ref:x,sessionId:e.id}),!e.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:j}),s.jsxs("div",{style:{height:`${b}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.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:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),s.jsx("button",{className:"pane-btn",onClick:()=>{var I;return(I=T.current)==null?void 0:I.send()},disabled:!D,title:"Send to terminal (Ctrl+Enter)",style:D?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(co,{ref:T,onSend:J,onContentChange:C,sessionId:e.id,token:o||""})})]})]})]})]}),e.error&&s.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 Hn extends a.Component{constructor(){super(...arguments);Ht(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){}render(){var t,r;return this.state.hasError?this.props.inline?s.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:[s.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),s.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"}),s.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"})]}):s.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:[s.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),s.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 ho=4,wn=10;function go(){const n=z(o=>o.layout),e=z(o=>o.terminalIds.length),t=z(o=>o.addTerminal);if(!n)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:s.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 r=e>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(Un,{node:n,canClose:r})})}const Un=a.memo(function({node:e,canClose:t}){return e.type==="leaf"?s.jsx(xo,{terminalId:e.terminalId,canClose:t}):s.jsx(bo,{node:e,canClose:t})}),xo=a.memo(function({terminalId:e,canClose:t}){const r=z(i=>i.terminalsMap[e]),o=z(i=>i.reconnectTerminal);return r?s.jsx(Hn,{inline:!0,children:s.jsx(mo,{terminal:r,canClose:t})}):s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:s.jsxs("button",{onClick:()=>o(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]})})}),bo=a.memo(function({node:e,canClose:t}){const r=z(c=>c.setSplitSizes),o=a.useRef(null),i=e.direction==="horizontal",l=a.useRef(e.sizes);l.current=e.sizes;const u=a.useCallback((c,d)=>{d.preventDefault();const f=i?"resizing-panes":"resizing-panes-v";document.body.classList.add(f);const h=i?d.clientX:d.clientY,m=[...l.current],x=o.current,T=i?(x==null?void 0:x.clientWidth)||1:(x==null?void 0:x.clientHeight)||1;let k=null;const E=j=>{k||(k=requestAnimationFrame(()=>{k=null;const L=((i?j.clientX:j.clientY)-h)/T*100,_=m[c]+L,B=m[c+1]-L;if(_>=wn&&B>=wn){const P=[...m];P[c]=_,P[c+1]=B,r(e.id,P)}}))},b=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(f),document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",E),document.addEventListener("mouseup",b)},[i,e.id,r]),p=[];return e.children.forEach((c,d)=>{const f=c.type==="leaf"?c.terminalId:c.id;p.push(s.jsx("div",{style:{flex:`${e.sizes[d]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(Un,{node:c,canClose:t})},f)),d<e.children.length-1&&p.push(s.jsx("div",{onMouseDown:h=>u(d,h),style:{flex:`0 0 ${ho}px`,cursor:i?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${d}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:i?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function yo({tabId:n}){const e=z(C=>C.tabs.find(S=>S.id===n)),t=z(C=>C.activeTabId),r=z(C=>C.switchTab),o=z(C=>C.closeTab),i=z(C=>C.reopenTab),l=z(C=>C.deleteTab),u=z(C=>C.renameTab),p=z(C=>e?e.terminalIds.map(S=>{const X=C.terminalsMap[S];return X?{id:S,connected:X.connected,active:!0}:{id:S,connected:!1,active:!1}}):[]),c=z(C=>C.disconnectTerminal),d=z(C=>C.reconnectTerminal),f=z(C=>C.killServerSession),[h,m]=a.useState(!1),[x,T]=a.useState(""),[k,E]=a.useState(!1),b=a.useRef(null);if(!e)return null;const j=t===n,w=e.status==="open",N=()=>{w&&r(n)},L=C=>{w&&(C.stopPropagation(),T(e.name),m(!0),setTimeout(()=>{var S;return(S=b.current)==null?void 0:S.focus()},0))},_=()=>{const C=x.trim();C&&u(n,C),m(!1)},B=C=>{C.stopPropagation(),i(n)},P=C=>{C.stopPropagation(),o(n)},F=async C=>{C.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await l(n)},D=C=>{C.stopPropagation(),E(!k)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:N,style:{padding:"8px 12px",cursor:w?"pointer":"default",borderLeft:j?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:j?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:w?1:.5},onMouseEnter:C=>{w&&!j&&(C.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:C=>{j||(C.currentTarget.style.backgroundColor="transparent")},children:[w&&e.terminalIds.length>0&&s.jsx("button",{onClick:D,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:k?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[h?s.jsx("input",{ref:b,value:x,onChange:C=>T(C.target.value),onBlur:_,onKeyDown:C=>{C.key==="Enter"&&_(),C.key==="Escape"&&m(!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"}}):s.jsx("div",{onDoubleClick:L,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:w?"Double-click to rename":e.name,children:e.name}),s.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",Pn(Math.floor(e.createdAt/1e3))]})]}),w?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:P,style:{flexShrink:0},title:"Close tab",children:"×"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:B,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:F,title:"Delete tab",children:"×"})]})]}),w&&k&&p.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(C=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${C.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:C.id}),s.jsx("span",{style:{marginLeft:"8px",color:C.active?C.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:C.active?C.connected?"●":"◐":"○"}),C.active?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),c(C.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:S=>{S.stopPropagation(),d(C.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:S=>{S.stopPropagation(),window.confirm(`Kill terminal "${C.id}"? This will destroy the tmux session.`)&&f(C.id)},title:"Kill session",children:"×"})]})]},C.id))})]})}function vo({sessionId:n,active:e,createdAt:t}){const r=z(u=>u.addTerminal),o=z(u=>u.killServerSession),i=()=>{r("horizontal",n)},l=u=>{u.stopPropagation(),window.confirm(`Delete orphaned session "${n}"? This will kill the tmux session.`)&&o(n)};return s.jsxs("div",{onClick:i,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s"},onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:Pn(t)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:l,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function wo(){const n=z(c=>c.sidebarOpen),e=z(c=>c.toggleSidebar),t=z(c=>c.fetchSessions),r=z(c=>n?c.serverSessions:[]),o=z(c=>n?c.tabs:[]),i=z(c=>c.terminalIds.length),l=z(c=>c.tabsLoading),u=new Set(o.flatMap(c=>c.terminalIds)),p=r.filter(c=>!u.has(c.sessionId));return a.useEffect(()=>{if(!n)return;t();let c=setInterval(t,5e3);const d=()=>{document.hidden?c&&(clearInterval(c),c=null):(t(),c||(c=setInterval(t,5e3)))};return document.addEventListener("visibilitychange",d),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",d)}},[n,t]),a.useEffect(()=>{if(!n)return;const c=setTimeout(t,800);return()=>clearTimeout(c)},[i,n,t]),s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),s.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:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.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"}),o.length===0?s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(c=>s.jsx(yo,{tabId:c.id},c.id))]}),!l&&p.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.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"}),p.map(c=>s.jsx(vo,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const Kn=$t.memo(()=>{const n=z(w=>w.tabs),e=z(w=>w.activeTabId),t=z(w=>w.addTab),r=z(w=>w.switchTab),o=z(w=>w.closeTab),i=z(w=>w.renameTab),[l,u]=a.useState(null),[p,c]=a.useState(""),d=a.useRef(null),f=n.filter(w=>w.status==="open");a.useEffect(()=>{l&&d.current&&(d.current.focus(),d.current.select())},[l]);const h=w=>{u(w.id),c(w.name)},m=()=>{l&&p.trim()&&i(l,p.trim()),u(null),c("")},x=()=>{u(null),c("")},T=w=>{w.key==="Enter"?m():w.key==="Escape"&&x()},k=w=>{l||r(w)},E=(w,N)=>{w.stopPropagation(),o(N)},b=(w,N)=>{w.button===1&&(w.preventDefault(),o(N))},j=f.length>1;return s.jsxs("div",{className:"tab-bar",children:[f.map(w=>{const N=w.id===e,L=l===w.id,_=w.terminalIds.length;return s.jsx("div",{className:`tab-item ${N?"tab-item--active":""}`,onClick:()=>k(w.id),onDoubleClick:()=>h(w),onMouseDown:B=>b(B,w.id),children:L?s.jsx("input",{ref:d,type:"text",value:p,onChange:B=>c(B.target.value),onBlur:m,onKeyDown:T,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[w.name," ",_>0&&`(${_})`]}),j&&s.jsx("button",{className:"tab-item__close",onClick:B=>E(B,w.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},w.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>t(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});Kn.displayName="TabBar";function So(){return localStorage.getItem("ai-cli-online-token")}function ko(){const n=z(d=>d.token),e=z(d=>d.setToken),t=z(d=>d.tabs),r=z(d=>d.addTab),o=z(d=>d.toggleSidebar),i=z(d=>d.fontSize),l=z(d=>d.setFontSize),u=z(d=>d.tabsLoading),p=z(d=>d.theme),c=z(d=>d.toggleTheme);return a.useEffect(()=>{const d=So();d&&!n&&e(d)},[]),a.useEffect(()=>{n&&!u&&t.filter(d=>d.status==="open").length===0&&r("Default")},[n,u]),n?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.17"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>l(i-1),disabled:i<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),s.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:i}),s.jsx("button",{className:"header-btn",onClick:()=>l(i+1),disabled:i>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(To,{}),s.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"☀":"🌙"}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(go,{})}),s.jsx(wo,{})]}),s.jsx(Kn,{})]}):s.jsx(Vr,{})}const Co=[1,2,3,4];function To(){const n=z(r=>r.latency);if(n===null)return s.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),s.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:[Co.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=t?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[n,"ms"]})]})}Lt.createRoot(document.getElementById("root")).render(s.jsx($t.StrictMode,{children:s.jsx(Hn,{children:s.jsx(ko,{})})}));
|
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-Dyh0m1Vc.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">
|