ai-cli-online 3.0.4 → 3.0.6
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
|
@@ -26,7 +26,7 @@ var Kn=Object.defineProperty;var Jn=(t,e,n)=>e in t?Kn(t,e,{enumerable:!0,config
|
|
|
26
26
|
`&&n++}return n}function nt(t,e,n,r){const s=t.join(`
|
|
27
27
|
`);let i=0;for(let g=0;g<e-1&&g<t.length;g++)i+=t[g].length+1;let l=0;for(let g=0;g<n&&g<t.length;g++)l+=t[g].length+1;let d=i,p=Math.min(s.length,l);if(r){const g=Math.max(0,i-10),b=Math.min(s.length,l+10),k=s.slice(g,b).indexOf(r);k>=0&&(d=g+k,p=d+r.length)}const c=Math.max(0,d-20),f=s.slice(c,d).replace(/\n/g,"↵"),u=Math.min(s.length,p+20),h=s.slice(p,u).replace(/\n/g,"↵");return{before:f,after:h}}function Zt(t,e){const n=[],r=[],s=[],i=[];for(const l of t.additions){const{before:d,after:p}=nt(e,l.sourceLine,l.sourceLine);n.push([`Line${l.sourceLine}:...${d}`,l.content,`${p}...`])}for(const l of t.deletions){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);r.push([`Line${l.startLine}:...${d}`,l.selectedText,`${p}...`])}for(const l of t.replacements){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);s.push([`Line${l.startLine}:...${d}`,l.selectedText,l.content,`${p}...`])}for(const l of t.comments){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);i.push([`Line${l.startLine}:...${d}`,l.selectedText,l.content,`${p}...`])}return{"Insert Annotations":n,"Delete Annotations":r,"Replace Annotations":s,"Comment Annotations":i}}function Qt(t){return t.additions.length>0||t.deletions.length>0||t.replacements.length>0||t.comments.length>0}function en(t){return/^[a-zA-Z0-9_./:@=-]+$/.test(t)?t:"'"+t.replace(/'/g,"'\\''")+"'"}function tn(t,e){return`/ai-cli-task:ai-cli-task plan ${en(t)} ${en(e)} --silent`}function nn(t){const e=t.split("/"),n=e.indexOf("AiTasks");return n>=0&&n+1<e.length?e.slice(0,n+2).join("/"):t.substring(0,t.lastIndexOf("/"))}function it(t){const e=new Set;return t.additions.forEach(n=>e.add(n.id)),t.deletions.forEach(n=>e.add(n.id)),t.replacements.forEach(n=>e.add(n.id)),t.comments.forEach(n=>e.add(n.id)),e}function rn(t){return t.replacements||(t.replacements=[]),t.comments||(t.comments=[]),t}function xs({sessionId:t,filePath:e,token:n,annotations:r,annLoadedRef:s,setAnnotations:i,baselineIdsRef:l}){const d=A(u=>u.latency),p=o.useRef(void 0),c=o.useRef(void 0),f=o.useRef(!1);o.useEffect(()=>{if(!s.current)return;const u=qe(t,e),h=JSON.stringify(r);p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(u,h)}catch{}},50),c.current&&clearTimeout(c.current);const g=Math.max(200,(d??30)*3);return c.current=setTimeout(()=>{f.current||(f.current=!0,Nn(n,t,e,h,Date.now()).catch(()=>{}).finally(()=>{f.current=!1}))},g),()=>{p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current)}},[r,t,e,n,d,s]),o.useEffect(()=>{s.current=!1;let u=Et,h=0;try{const b=localStorage.getItem(qe(t,e));b&&(u=rn(JSON.parse(b)),h=Date.now())}catch{}i(u),l.current=it(u);let g=!1;return hs(n,t,e).then(b=>{if(!g&&b&&b.updatedAt>h)try{const j=rn(JSON.parse(b.content));i(j);try{localStorage.setItem(qe(t,e),b.content)}catch{}l.current=it(j)}catch{}}).catch(()=>{}).finally(()=>{s.current=!0}),s.current=!0,()=>{g=!0}},[t,e,n,s,i,l])}async function sn(t,e,n,r){const s={path:n};return r&&(s.since=String(r)),pe.getOptional(t,e,"file-content",s)}async function on(t,e,n,r){return pe.putJson(t,e,"file-content",{path:n,content:r})}function Ln(t,e){let n=t.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");n||(n="heading");const r=e.get(n)||0;return r>0&&(n=`${n}-${r}`),e.set(n,r+1),n}function Dn(t){return t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function ys(t){if(!t)return[];const e=[],n=new Map,r=t.split(`
|
|
28
28
|
`);let s=!1;for(const i of r){if(/^```/.test(i.trim())){s=!s;continue}if(s)continue;const l=i.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(l){const d=l[1].length,p=Dn(l[2]),c=Ln(p,n);e.push({id:c,text:p,level:d})}}return e}const vs=160,ws=22;function Ss({headings:t,scrollRef:e}){const[n,r]=o.useState(null),[s,i]=o.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),l=o.useRef(null),d=o.useRef(!1),p=o.useMemo(()=>Math.min(...t.map(u=>u.level)),[t]),c=o.useCallback(()=>{i(u=>{const h=!u;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);o.useEffect(()=>{const u=e.current;if(!u||t.length===0)return;const h=()=>{d.current=!1;const b=u.scrollTop,j=50;let k=null;for(const C of t){const v=u.querySelector(`[id="${CSS.escape(C.id)}"]`);v&&v.offsetTop<=b+j&&(k=C.id)}r(k)},g=()=>{d.current||(d.current=!0,requestAnimationFrame(h))};return h(),u.addEventListener("scroll",g,{passive:!0}),()=>u.removeEventListener("scroll",g)},[t,e]);const f=o.useCallback(u=>{const h=e.current;if(!h)return;const g=h.querySelector(`[id="${CSS.escape(u)}"]`);g&&(g.scrollIntoView({behavior:"smooth",block:"start"}),r(u))},[e]);return o.useEffect(()=>{if(!n||s)return;const u=l.current;if(!u)return;const h=u.querySelector(`[data-toc-id="${CSS.escape(n)}"]`);if(h){const g=h.offsetTop-u.offsetTop,b=g+h.offsetHeight;(g<u.scrollTop||b>u.scrollTop+u.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[n,s]),t.length<2?null:s?a.jsx("div",{style:{width:ws,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:a.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:u=>{u.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:u=>{u.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):a.jsxs("div",{ref:l,style:{width:vs,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[a.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),a.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:u=>{u.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:u=>{u.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),a.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:t.map((u,h)=>a.jsx("div",{"data-toc-id":u.id,onClick:()=>f(u.id),style:{padding:`2px 6px 2px ${(u.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:n===u.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:n===u.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:u.level<=2?500:400,transition:"color 0.1s"},title:u.text,onMouseEnter:g=>{n!==u.id&&(g.currentTarget.style.color="var(--text-primary)"),g.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:g=>{n!==u.id&&(g.currentTarget.style.color="var(--text-secondary)"),g.currentTarget.style.backgroundColor="transparent"},children:u.text},`${u.id}-${h}`))})]})}const ks={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 Ts({annotations:t,annCounts:e,isSent:n,onSendAll:r,onSendSingle:s,onDelete:i}){const[l,d]=o.useState(!1),p=o.useRef(null);o.useEffect(()=>{if(!l)return;const u=h=>{p.current&&!p.current.contains(h.target)&&d(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[l]);const c=o.useCallback((u,h,g)=>{const b=ks[h],j=n(u);return a.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[a.jsx("span",{className:"plan-anno-dropdown__type",style:{color:b.color},children:b.symbol}),a.jsxs("span",{className:"plan-anno-dropdown__text",children:[g.slice(0,60),g.length>60?"...":""]}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!j&&s(u,h),disabled:j,title:j?"Already sent":"Send to terminal",style:j?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(u,h),title:"Delete",children:"×"})]},u)},[n,s,i]),f=(()=>{const u=t.additions[0],h=t.deletions[0],g=t.replacements[0],b=t.comments[0],j=u?u.content:h?h.selectedText:g?g.content:b?b.content:"";return j?j.slice(0,40)+(j.length>40?"...":""):""})();return a.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[a.jsxs("div",{className:`plan-anno-dropdown-trigger${l?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>d(u=>!u),title:e.total>0?`${e.total} annotations (${e.unsent} unsent)`:"No annotations",children:[a.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:f}),a.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),l&&a.jsxs("div",{className:"plan-anno-dropdown",children:[e.unsent>0&&a.jsx("div",{className:"plan-anno-dropdown__header",children:a.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",e.unsent,")"]})}),a.jsxs("div",{className:"plan-anno-dropdown__list",children:[t.additions.map(u=>c(u.id,"add",u.content)),t.deletions.map(u=>c(u.id,"del",u.selectedText)),t.replacements.map(u=>c(u.id,"rep",u.content)),t.comments.map(u=>c(u.id,"com",u.content)),e.total===0&&a.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const Cs={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 yt({type:t,annotation:e,fontSize:n,onEdit:r,onRemove:s,onSend:i,isSent:l}){const d=Cs[t],[p,c]=o.useState(!1),[f,u]=o.useState(""),h=o.useRef(null),g=t==="del"?e.selectedText:e.content,b=o.useCallback(()=>{c(!0),u(g)},[g]),j=o.useCallback(()=>{const k=f.trim();k?r(e.id,k):s(e.id),c(!1)},[f,e.id,r,s]);return o.useEffect(()=>{p&&requestAnimationFrame(()=>{const k=h.current;k&&(k.focus(),k.selectionStart=k.selectionEnd=k.value.length)})},[p]),p?a.jsx("div",{className:d.className,children:a.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:f,onChange:k=>u(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),j()),k.key==="Escape"&&(k.preventDefault(),c(!1))},onBlur:j,rows:at(f),style:{fontSize:`${n}px`,flex:1}})}):a.jsxs("div",{className:d.className,children:[d.icon&&a.jsx("span",{style:{color:d.color,flexShrink:0},children:d.icon}),t==="del"?a.jsx("span",{style:{flex:1,fontSize:`${n}px`,color:d.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:e.selectedText}):t==="rep"?a.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:[a.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:e.selectedText}),a.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),a.jsx("span",{style:{color:"var(--accent-blue)"},children:e.content})]}):a.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:[a.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',e.selectedText,'"']}),a.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),a.jsx("span",{style:{color:"var(--accent-green)"},children:e.content})]}),i&&a.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"}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:b,style:{color:"var(--accent-blue)"},title:`Edit ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"✎"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>s(e.id),title:`Remove ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"×"})]})}function Es({x:t,y:e,onDelete:n,onReplace:r,onComment:s}){return a.jsxs("div",{className:"plan-selection-float",style:{top:e,left:t},children:[a.jsx("button",{className:"plan-selection-float__delete",onMouseDown:i=>{i.preventDefault(),n()},title:"Delete selection",children:"−"}),a.jsx("button",{className:"plan-selection-float__replace",onMouseDown:i=>{i.preventDefault(),r()},title:"Replace selection",children:"⇄"}),a.jsx("button",{className:"plan-selection-float__comment",onMouseDown:i=>{i.preventDefault(),s()},title:"Comment on selection",children:"?"})]})}const js=o.forwardRef(function({markdown:e,filePath:n,sessionId:r,token:s,onExecute:i,onSend:l,onRefresh:d,onClose:p,onContentSaved:c,expanded:f,readOnly:u},h){const g=A(m=>m.fontSize),[b,j]=o.useState(null),k=o.useRef(void 0),C=o.useCallback((m,x)=>{clearTimeout(k.current),j({type:m,msg:x}),k.current=setTimeout(()=>j(null),m==="ok"?2500:5e3)},[]);o.useEffect(()=>()=>clearTimeout(k.current),[]);const[v,I]=o.useState(!1),[T,L]=o.useState(""),[$,O]=o.useState(!1),W=o.useRef(null),B=A(m=>m.latency),F=`plan-edit:${r}:${n}`,N=o.useRef(void 0),S=o.useRef(void 0),w=o.useRef(!1);o.useEffect(()=>{if(!v)return;clearTimeout(N.current),N.current=setTimeout(()=>{try{localStorage.setItem(F,T)}catch{}},50),clearTimeout(S.current);const m=Math.max(200,(B??30)*3);return S.current=setTimeout(()=>{w.current||(w.current=!0,on(s,r,n,T).then(x=>{c==null||c(T,x.mtime)}).catch(()=>{}).finally(()=>{w.current=!1}))},m),()=>{clearTimeout(N.current),clearTimeout(S.current)}},[T,v,F,s,r,n,B,c]),o.useEffect(()=>{I(!1)},[n]),o.useEffect(()=>{v&&requestAnimationFrame(()=>{var m;return(m=W.current)==null?void 0:m.focus()})},[v]);const q=o.useCallback(()=>{if(u||v)return;const m=localStorage.getItem(`plan-edit:${r}:${n}`);L(m??e),I(!0)},[u,v,e,r,n]),V=o.useCallback(()=>{I(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${n}`)},[r,n]),U=o.useCallback(async()=>{if(!$){O(!0);try{const m=await on(s,r,n,T);c==null||c(T,m.mtime),I(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${n}`),C("ok","Saved")}catch(m){const x=m instanceof Error?m.message:"Failed to save";C("err",x)}finally{O(!1)}}},[$,s,r,n,T,c,C]),J=o.useMemo(()=>e?xn.lexer(e):[],[e]),_=o.useMemo(()=>e.split(`
|
|
29
|
-
`),[e]),H=o.useMemo(()=>ys(e),[e]),D=o.useMemo(()=>{const m=new Map,x=new Map;return J.forEach((M,R)=>{if(M.type==="heading"){const ee=Dn(M.text||""),Y=Ln(ee,x);m.set(R,Y)}}),m},[J]),z=o.useRef(new Set),Q=o.useRef(!1),[P,G]=o.useState(()=>{try{const m=localStorage.getItem(qe(r,n)),x=m?JSON.parse(m):Et;return z.current=it(x),x.replacements||(x.replacements=[]),x.comments||(x.comments=[]),x}catch{return Et}});xs({sessionId:r,filePath:n,token:s,annotations:P,annLoadedRef:Q,setAnnotations:G,baselineIdsRef:z});const[be,je]=o.useState(0),Ue=o.useMemo(()=>{const m=z.current,x=P.additions.length+P.deletions.length+P.replacements.length+P.comments.length;let M=0;return P.additions.forEach(R=>{m.has(R.id)&&M++}),P.deletions.forEach(R=>{m.has(R.id)&&M++}),P.replacements.forEach(R=>{m.has(R.id)&&M++}),P.comments.forEach(R=>{m.has(R.id)&&M++}),{total:x,sent:M,unsent:x-M}},[P,be]),[ae,Te]=o.useState(null),[xe,ce]=o.useState(""),he=o.useRef(null),[X,ye]=o.useState(null),[Ce,Ee]=o.useState(""),Me=o.useRef(null),[re,ve]=o.useState(null),ie=o.useRef(null),He=o.useRef(0),$e=o.useRef(null);o.useEffect(()=>{const m=ie.current;if(!m)return;let x;const M=()=>{clearTimeout(x),x=setTimeout(()=>{const R=Xt(r,n);if(m.scrollTop>0)try{localStorage.setItem(R,String(m.scrollTop))}catch{}else localStorage.removeItem(R)},50)};return m.addEventListener("scroll",M,{passive:!0}),()=>{clearTimeout(x),m.removeEventListener("scroll",M)}},[r,n]),o.useEffect(()=>{if(!J.length)return;const m=localStorage.getItem(Xt(r,n));if(!m)return;const x=Number(m),M=ie.current;if(!M||(M.scrollTop=x,M.scrollTop>=x-10))return;let R;const ee=()=>{M.scrollTop=x,Y.disconnect()},Y=new MutationObserver(()=>{clearTimeout(R),R=setTimeout(ee,80)});Y.observe(M,{childList:!0,subtree:!0});const ne=setTimeout(ee,500);return()=>{clearTimeout(R),clearTimeout(ne),Y.disconnect()}},[r,n,J.length]),o.useEffect(()=>{ae!=null&&requestAnimationFrame(()=>{var m;return(m=he.current)==null?void 0:m.focus()})},[ae]),o.useEffect(()=>{X&&requestAnimationFrame(()=>{var m;return(m=Me.current)==null?void 0:m.focus()})},[X]);const _e=o.useRef({annotations:P,activeInsert:ae,insertText:xe,pendingAction:X,pendingText:Ce,tokens:J,filePath:n,sessionId:r,token:s});_e.current={annotations:P,activeInsert:ae,insertText:xe,pendingAction:X,pendingText:Ce,tokens:J,filePath:n,sessionId:r,token:s},o.useEffect(()=>()=>{const m=_e.current;let x=m.annotations,M=!1;if(m.activeInsert!=null&&m.insertText.trim()){const R=tt(m.tokens,m.activeInsert+1);x={...x,additions:[...x.additions,{id:Se(),afterTokenIndex:m.activeInsert,sourceLine:R,content:m.insertText.trim()}]},M=!0}if(m.pendingAction&&m.pendingText.trim()){const R=m.pendingAction,ee=m.pendingText.trim();R.type==="replace"?x={...x,replacements:[...x.replacements,{id:Se(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ee}]}:x={...x,comments:[...x.comments,{id:Se(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ee}]},M=!0}if(M){const R=JSON.stringify(x);try{localStorage.setItem(qe(m.sessionId,m.filePath),R)}catch{}Nn(m.token,m.sessionId,m.filePath,R,Date.now()).catch(()=>{})}},[]);const Ne=o.useCallback(m=>{if(!xe.trim()){Te(null),ce("");return}const x=tt(J,m+1);G(M=>({...M,additions:[...M.additions,{id:Se(),afterTokenIndex:m,sourceLine:x,content:xe.trim()}]})),Te(null),ce("")},[xe,J]),Le=o.useCallback(m=>{G(x=>({...x,additions:x.additions.filter(M=>M.id!==m)}))},[]),Ye=o.useCallback((m,x)=>{G(M=>({...M,additions:M.additions.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),ft=o.useCallback(()=>{var m;re&&(G(x=>({...x,deletions:[...x.deletions,{id:Se(),tokenIndices:re.tokenIndices,startLine:re.startLine,endLine:re.endLine,selectedText:re.text.slice(0,80)}]})),ve(null),(m=window.getSelection())==null||m.removeAllRanges())},[re]),y=o.useCallback(m=>{var x;re&&(ye({type:m,tokenIndices:re.tokenIndices,startLine:re.startLine,endLine:re.endLine,text:re.text.slice(0,80)}),Ee(""),ve(null),(x=window.getSelection())==null||x.removeAllRanges())},[re]),E=o.useCallback(()=>{if(!X)return;const m=Ce.trim();if(!m){ye(null),Ee("");return}X.type==="replace"?G(x=>({...x,replacements:[...x.replacements,{id:Se(),tokenIndices:X.tokenIndices,startLine:X.startLine,endLine:X.endLine,selectedText:X.text,content:m}]})):G(x=>({...x,comments:[...x.comments,{id:Se(),tokenIndices:X.tokenIndices,startLine:X.startLine,endLine:X.endLine,selectedText:X.text,content:m}]})),ye(null),Ee("")},[X,Ce]),K=o.useCallback(m=>{G(x=>({...x,replacements:x.replacements.filter(M=>M.id!==m)}))},[]),Z=o.useCallback((m,x)=>{G(M=>({...M,replacements:M.replacements.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),te=o.useCallback(m=>{G(x=>({...x,comments:x.comments.filter(M=>M.id!==m)}))},[]),we=o.useCallback((m,x)=>{G(M=>({...M,comments:M.comments.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),se=o.useCallback(m=>{G(x=>({...x,deletions:x.deletions.filter(M=>M.id!==m)}))},[]),fe=o.useCallback((m,x)=>{G(M=>({...M,deletions:M.deletions.map(R=>R.id===m?{...R,id:Se(),selectedText:x}:R)}))},[]),de=o.useCallback(m=>{let x=m instanceof Element?m:m.parentElement;for(;x&&x!==ie.current;){if(x.hasAttribute("data-token-index"))return x;x=x.parentElement}return null},[]),oe=o.useCallback(()=>{const m=window.getSelection();if(!m||m.isCollapsed||!ie.current){ve(null);return}const x=m.toString().trim();if(!x){ve(null);return}const M=m.getRangeAt(0);if(!ie.current.contains(M.commonAncestorContainer)){ve(null);return}const R=de(M.startContainer),ee=de(M.endContainer);if(!R||!ee){ve(null);return}const Y=parseInt(R.getAttribute("data-token-index")||"0",10),ne=parseInt(ee.getAttribute("data-token-index")||"0",10),Lt=[];for(let gt=Math.min(Y,ne);gt<=Math.max(Y,ne);gt++)Lt.push(gt);const Un=tt(J,Math.min(Y,ne)),Hn=tt(J,Math.max(Y,ne)+1),Dt=M.getBoundingClientRect(),ht=ie.current,Mt=ht.getBoundingClientRect();navigator.clipboard.writeText(x).catch(()=>{});const Xe=$e.current,At=Xe&&Date.now()-Xe.time<500;He.current=Date.now(),ve({x:(At?Xe.x:Dt.right)-Mt.left+ht.scrollLeft+6,y:(At?Xe.y:Dt.top)-Mt.top+ht.scrollTop-44,tokenIndices:Lt,startLine:Un,endLine:Hn,text:x})},[J,de]),ge=o.useRef(void 0);o.useEffect(()=>{const m=()=>{ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{const x=window.getSelection();if(!x||x.isCollapsed||!ie.current){if(Date.now()-He.current<300)return;ve(null);return}const M=x.anchorNode;M&&ie.current.contains(M)&&oe()},120)};return document.addEventListener("selectionchange",m),()=>{document.removeEventListener("selectionchange",m),ge.current&&clearTimeout(ge.current)}},[oe]);const Ke=A(m=>m.theme);ms(ie,J,Ke);const Oe=o.useCallback(()=>{const m=z.current;return{additions:P.additions.filter(x=>!m.has(x.id)),deletions:P.deletions.filter(x=>!m.has(x.id)),replacements:P.replacements.filter(x=>!m.has(x.id)),comments:P.comments.filter(x=>!m.has(x.id))}},[P]),pt=o.useCallback(async()=>{const m=Oe();if(!Qt(m))return;const x=Zt(m,_),M=nn(n);try{const{path:R}=await Yt(s,r,M,x),ee=tn(n,R);i(ee),z.current=it(P),je(ne=>ne+1);const Y=m.additions.length+m.deletions.length+m.replacements.length+m.comments.length;C("ok",`Sent ${Y} annotation(s)`)}catch(R){const ee=R instanceof Error?R.message:"Failed to send";C("err",ee)}},[Oe,P,_,i,n,s,r,C]),Fe=o.useCallback(async(m,x)=>{if(!l)return;const M={additions:[],deletions:[],replacements:[],comments:[]};if(x==="add"){const Y=P.additions.find(ne=>ne.id===m);if(!Y)return;M.additions.push(Y)}else if(x==="del"){const Y=P.deletions.find(ne=>ne.id===m);if(!Y)return;M.deletions.push(Y)}else if(x==="rep"){const Y=P.replacements.find(ne=>ne.id===m);if(!Y)return;M.replacements.push(Y)}else{const Y=P.comments.find(ne=>ne.id===m);if(!Y)return;M.comments.push(Y)}const R=Zt(M,_),ee=nn(n);try{const{path:Y}=await Yt(s,r,ee,R);l(tn(n,Y)),z.current.add(m),je(ne=>ne+1),C("ok","Sent 1 annotation")}catch(Y){const ne=Y instanceof Error?Y.message:"Failed to send";C("err",ne)}},[l,n,P,_,s,r,C]),Fn=o.useCallback((m,x)=>{x==="add"?Le(m):x==="del"?se(m):x==="rep"?K(m):te(m)},[Le,se,K,te]);o.useImperativeHandle(h,()=>({getSummary:()=>{const m=Oe();return Qt(m)?"[pending annotations]":""},handleEscape:()=>v?(V(),!0):X?(E(),!0):ae!=null?(Ne(ae),!0):!1,getScrollTop:()=>{var m;return((m=ie.current)==null?void 0:m.scrollTop)??0},setScrollTop:m=>{requestAnimationFrame(()=>{ie.current&&(ie.current.scrollTop=m)})}}),[Oe,v,V,ae,Ne,X,E]);const Bn=o.useMemo(()=>{const m=new Set;return P.deletions.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.deletions]),Pn=o.useMemo(()=>{const m=new Set;return P.replacements.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.replacements]),Wn=o.useMemo(()=>{const m=new Set;return P.comments.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.comments]),Rt=o.useMemo(()=>{const m=new Map;return P.additions.forEach(x=>{const M=m.get(x.afterTokenIndex)||[];M.push(x),m.set(x.afterTokenIndex,M)}),m},[P.additions]),Nt=Ue.unsent>0,mt=o.useCallback(m=>z.current.has(m),[]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[a.jsxs("div",{className:"plan-anno-toolbar",children:[a.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:n,children:n.split("/").pop()||n}),b&&a.jsx("span",{style:{fontSize:"10px",color:b.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:b.type==="err"?"pointer":void 0},title:b.type==="err"?"Click to copy":b.msg,onClick:b.type==="err"?()=>{navigator.clipboard.writeText(b.msg).catch(()=>{}),C("ok","Copied")}:void 0,children:b.msg}),v?a.jsxs(a.Fragment,{children:[a.jsx("button",{className:"pane-btn",onClick:U,disabled:$,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:$?"Saving...":"Save"}),a.jsx("button",{className:"pane-btn",onClick:V,disabled:$,title:"Cancel (Esc)",children:"Cancel"})]}):a.jsxs(a.Fragment,{children:[d&&a.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),!u&&a.jsx("button",{className:"pane-btn",onClick:q,title:"Edit file (double-click content)",children:"Edit"}),a.jsx("button",{className:"pane-btn",onClick:pt,disabled:!Nt,title:"Send all annotations",style:Nt?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),a.jsx(Ts,{annotations:P,annCounts:Ue,isSent:mt,onSendAll:pt,onSendSingle:Fe,onDelete:Fn}),p&&a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await pt(),p()},title:"Send annotations & close file",children:"×"})]})]}),a.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[v?a.jsx("textarea",{ref:W,className:"plan-edit-textarea",style:{fontSize:`${g}px`},value:T,onChange:m=>L(m.target.value),onKeyDown:m=>{if(m.key==="s"&&(m.ctrlKey||m.metaKey)){m.preventDefault(),U();return}if(m.key==="Escape"){m.preventDefault(),V();return}},spellCheck:!1}):a.jsxs("div",{ref:ie,className:`plan-anno-content md-preview${ae!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${g}px`,minWidth:0},onMouseUp:m=>{$e.current={x:m.clientX,y:m.clientY,time:Date.now()},oe()},onDoubleClick:m=>{u||m.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||q()},children:[!u&&a.jsx(an,{index:-1,active:ae===-1,additions:Rt.get(-1),onOpen:()=>{Te(-1),ce("")},onSubmit:()=>Ne(-1),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?m=>Fe(m,"add"):void 0,isSent:mt,insertText:xe,setInsertText:ce,textareaRef:ae===-1?he:void 0,expanded:f,alwaysShow:J.length===0,fontSize:g}),J.map((m,x)=>{const M=bs(m);return a.jsxs("div",{children:[a.jsx("div",{"data-token-index":x,id:D.get(x),className:Bn.has(x)?"plan-block--deleted":Pn.has(x)?"plan-block--replaced":Wn.has(x)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:M}}),P.deletions.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"del",annotation:R,fontSize:g,onEdit:fe,onRemove:se,onSend:l?ee=>Fe(ee,"del"):void 0,isSent:z.current.has(R.id)},R.id)),P.replacements.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"rep",annotation:R,fontSize:g,onEdit:Z,onRemove:K,onSend:l?ee=>Fe(ee,"rep"):void 0,isSent:z.current.has(R.id)},R.id)),P.comments.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"com",annotation:R,fontSize:g,onEdit:we,onRemove:te,onSend:l?ee=>Fe(ee,"com"):void 0,isSent:z.current.has(R.id)},R.id)),X&&X.tokenIndices[0]===x&&a.jsxs("div",{className:X.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[a.jsx("span",{style:{color:X.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:X.type==="replace"?"⇄":"?"}),a.jsx("textarea",{ref:Me,className:"plan-annotation-textarea",value:Ce,onChange:R=>Ee(R.target.value),onKeyDown:R=>{if(R.key==="Enter"&&(R.ctrlKey||R.metaKey)){R.preventDefault(),E();return}if(R.key==="Escape"){R.preventDefault(),E();return}},onBlur:E,placeholder:X.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:at(Ce),style:{fontSize:`${g}px`,flex:1}})]}),!u&&a.jsx(an,{index:x,active:ae===x,additions:Rt.get(x),onOpen:()=>{Te(x),ce("")},onSubmit:()=>Ne(x),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?R=>Fe(R,"add"):void 0,isSent:mt,insertText:xe,setInsertText:ce,textareaRef:ae===x?he:void 0,expanded:f,fontSize:g})]},x)}),!u&&re&&a.jsx(Es,{x:re.x,y:re.y,onDelete:ft,onReplace:()=>y("replace"),onComment:()=>y("comment")})]}),!v&&a.jsx(Ss,{headings:H,scrollRef:ie})]})]})});function an({index:t,active:e,additions:n,onOpen:r,onSubmit:s,onRemoveAddition:i,onEditAddition:l,onSendSingle:d,isSent:p,insertText:c,setInsertText:f,textareaRef:u,expanded:h,alwaysShow:g,fontSize:b=14}){const[j,k]=o.useState(null),[C,v]=o.useState(""),I=o.useRef(null),T=Tt(),L=Tt();o.useEffect(()=>{j&&(T.clearUndo(),requestAnimationFrame(()=>{const N=I.current;N&&(N.focus(),N.selectionStart=N.selectionEnd=N.value.length)}))},[j]),o.useEffect(()=>{e&&L.clearUndo()},[e]);const $=o.useCallback(N=>{v(S=>(T.pushUndo(S),N))},[T]),O=o.useCallback(N=>{L.pushUndo(c),f(N)},[c,f,L]),W=o.useCallback(N=>{k(N.id),v(N.content)},[]),B=o.useCallback(()=>{if(!j)return;const N=C.trim();N?l(j,N):i(j),k(null),v("")},[j,C,l,i]),F=o.useCallback(()=>{k(null),v("")},[]);return a.jsxs("div",{className:`plan-insert-zone${g?" plan-insert-zone--empty":""}`,"data-zone-index":t,children:[n==null?void 0:n.map(N=>a.jsx("div",{className:"plan-annotation-card",children:j===N.id?a.jsx("textarea",{ref:I,className:"plan-annotation-textarea",value:C,onChange:S=>$(S.target.value),onKeyDown:S=>{if(S.key==="Enter"&&(S.ctrlKey||S.metaKey)){S.preventDefault(),B();return}if(S.key==="Escape"){S.preventDefault(),F();return}if(S.key==="Tab"){Ct(S,$);return}},onBlur:B,rows:at(C),style:{fontSize:`${b}px`,flex:1,...h?{minWidth:300}:void 0}}):a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{flex:1,fontSize:`${b}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>W(N),title:"Double-click to edit",children:N.content}),d&&(()=>{const S=(p==null?void 0:p(N.id))??!1;return a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!S&&d(N.id),disabled:S,title:S?"Already sent":"Send to terminal",style:S?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>W(N),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(N.id),children:"×"})]})},N.id)),e?a.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:a.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:c,onChange:N=>O(N.target.value),onKeyDown:N=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)){N.preventDefault(),s();return}if(N.key==="Escape"){N.preventDefault(),s();return}if(N.key==="Tab"){Ct(N,O);return}},onBlur:s,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:at(c),style:{fontSize:`${b}px`,...h?{minWidth:300}:void 0}})}):g&&!(n!=null&&n.length)?a.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."}):a.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function Re(t,e,n){const r=n?{path:n}:void 0;return pe.get(t,e,"files",r)}function Is(t,e,n,r){return new Promise((s,i)=>{const l=new FormData;for(const p of n)l.append("files",p);const d=new XMLHttpRequest;d.open("POST",`${De}/api/sessions/${encodeURIComponent(e)}/upload`),d.setRequestHeader("Authorization",`Bearer ${t}`),d.upload.addEventListener("progress",p=>{p.lengthComputable&&r&&r(Math.round(p.loaded/p.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?s():i(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>i(new Error("Upload network error"))),d.addEventListener("abort",()=>i(new Error("Upload aborted"))),d.send(l)})}async function ln(t,e){return(await pe.get(t,e,"cwd")).cwd}async function Rs(t,e,n){return pe.post(t,e,"touch",{name:n})}async function Ns(t,e,n){return pe.post(t,e,"mkdir",{path:n})}async function Ls(t,e,n){return pe.del(t,e,"rm",{path:n})}async function Ds(t,e){const n=await pe.getBlob(t,e,"download-cwd"),r=await n.blob(),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s;const l=n.headers.get("Content-Disposition"),d=l==null?void 0:l.match(/filename="(.+)"/);i.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(s)}async function Ms(t,e,n){const s=await(await pe.getBlob(t,e,"download",{path:n})).blob(),i=URL.createObjectURL(s),l=document.createElement("a");l.href=i,l.download=n.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}function Mn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function As(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function An(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function zs({sessionId:t,token:e,planDir:n,selectedFile:r,onSelectFile:s,onCreateFile:i,onDeleteFile:l}){const[d,p]=o.useState([]),[c,f]=o.useState(!0),[u,h]=o.useState(""),[g,b]=o.useState(!1),j=o.useRef(null),[k,C]=o.useState(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n))return w}return n});o.useEffect(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n)){C(w);return}}C(n)},[r,n]);const v=o.useCallback(async()=>{if(!(!e||!k)){f(!0);try{const q=(await Re(e,t,k)).files.filter(V=>V.type==="file"&&(V.name.toLowerCase().endsWith(".md")||V.name===".index.json")||V.type==="directory").sort((V,U)=>{const J=V.type==="file"&&V.name===".index.json",_=U.type==="file"&&U.name===".index.json";return J&&!_?-1:!J&&_?1:V.type==="directory"&&U.type!=="directory"?-1:V.type!=="directory"&&U.type==="directory"?1:V.name.localeCompare(U.name)});p(q)}catch{p([])}finally{f(!1)}}},[e,t,k]);o.useEffect(()=>{v()},[v]),o.useEffect(()=>{const w=setInterval(v,5e3);return()=>clearInterval(w)},[v]);const I=o.useCallback(()=>{const w=n.substring(0,n.lastIndexOf("/")+1);return k.startsWith(w)?k.substring(w.length):k},[n,k]),T=o.useCallback(async()=>{const w=u.trim();if(!w)return;const q=w.endsWith(".md")?w:`${w}.md`;b(!0);try{const V=await Rs(e,t,`${I()}/${q}`);V.ok&&(h(""),await v(),i(V.path))}catch{}finally{b(!1)}},[u,e,t,I,v,i]),L=o.useCallback(async()=>{const w=u.trim().replace(/\/+$/,"");if(w){b(!0);try{await Ns(e,t,`${I()}/${w}`),h(""),await v()}catch{}finally{b(!1)}}},[u,e,t,I,v]),$=o.useCallback(async w=>{const q=`${k}/${w.name}`,V=w.type==="directory"?`folder "${w.name}" and all its contents`:`"${w.name}"`;if(window.confirm(`Delete ${V}?`))try{await Ls(e,t,q),l==null||l(q),await v()}catch{}},[e,t,k,v,l]),O=o.useCallback(w=>{C(q=>`${q}/${w}`)},[]),W=o.useCallback(()=>{k!==n&&C(w=>w.substring(0,w.lastIndexOf("/")))},[k,n]),B=n.split("/").pop()||"AiTasks",F=(()=>{const w=n.split("/");return w.length>=2?w[w.length-2]+"/":""})(),N=k===n?F+B+"/":F+B+"/"+k.substring(n.length+1)+"/",S=r?r.split("/").pop():null;return a.jsxs("div",{className:"plan-file-browser",children:[a.jsxs("div",{className:"plan-file-browser__header",children:[a.jsx("span",{className:"plan-file-browser__title",title:N,children:N}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:v,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),a.jsxs("div",{className:"plan-file-browser__create",children:[a.jsx("input",{ref:j,className:"plan-file-browser__input",value:u,onChange:w=>h(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),T())},placeholder:"name",disabled:g}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:T,disabled:g||!u.trim(),title:"Create new .md file",style:u.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:L,disabled:g||!u.trim(),title:"Create new folder",style:u.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),a.jsxs("div",{className:"plan-file-browser__list",children:[c&&d.length===0&&a.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&d.length===0&&a.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),k!==n&&a.jsxs("div",{className:"plan-file-browser__item",onClick:W,title:"Go up to parent directory",style:{cursor:"pointer"},children:[a.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),a.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(w=>{const q=`${k}/${w.name}`,V=w.type==="file"&&w.name===S,U=w.type==="directory";return a.jsxs("div",{className:`plan-file-browser__item${V?" plan-file-browser__item--active":""}`,onClick:()=>U?O(w.name):s(q),title:U?`Open folder ${w.name}`:w.name,style:{cursor:"pointer"},children:[a.jsx("span",{className:"plan-file-browser__icon",children:U?"📁":w.name===".index.json"?"🔒":"□"}),a.jsxs("span",{className:"plan-file-browser__name",children:[w.name,U?"/":""]}),!U&&a.jsx("span",{className:"plan-file-browser__size",children:Mn(w.size)}),w.name!==".index.json"&&a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:J=>{J.stopPropagation(),$(w)},title:`Delete ${w.name}`,children:"×"})]},w.name)})]})]})}const vt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},$s=200;function _s(){const[t,e]=o.useState(vt),n=o.useRef("lines"),r=o.useRef([]),s=o.useRef(""),i=o.useRef(""),l=o.useRef([]),d=o.useRef(0),p=o.useRef(0),c=o.useRef(null),f=o.useRef(null),u=o.useCallback(()=>{const C=n.current;e(v=>({...v,receivedBytes:d.current,...C==="lines"?{lines:[...r.current]}:{},...C==="content"?{content:i.current}:{}}))},[]),h=o.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,u()},$s))},[u]),g=o.useCallback(C=>{n.current=C,r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...vt,mode:C,status:"streaming"})},[]),b=o.useCallback(C=>{d.current+=C.length;const v=n.current;if(v==="lines"){const T=f.current.decode(C,{stream:!0}).split(`
|
|
29
|
+
`),[e]),H=o.useMemo(()=>ys(e),[e]),D=o.useMemo(()=>{const m=new Map,x=new Map;return J.forEach((M,R)=>{if(M.type==="heading"){const ee=Dn(M.text||""),Y=Ln(ee,x);m.set(R,Y)}}),m},[J]),z=o.useRef(new Set),Q=o.useRef(!1),[P,G]=o.useState(()=>{try{const m=localStorage.getItem(qe(r,n)),x=m?JSON.parse(m):Et;return z.current=it(x),x.replacements||(x.replacements=[]),x.comments||(x.comments=[]),x}catch{return Et}});xs({sessionId:r,filePath:n,token:s,annotations:P,annLoadedRef:Q,setAnnotations:G,baselineIdsRef:z});const[be,je]=o.useState(0),Ue=o.useMemo(()=>{const m=z.current,x=P.additions.length+P.deletions.length+P.replacements.length+P.comments.length;let M=0;return P.additions.forEach(R=>{m.has(R.id)&&M++}),P.deletions.forEach(R=>{m.has(R.id)&&M++}),P.replacements.forEach(R=>{m.has(R.id)&&M++}),P.comments.forEach(R=>{m.has(R.id)&&M++}),{total:x,sent:M,unsent:x-M}},[P,be]),[ae,Te]=o.useState(null),[xe,ce]=o.useState(""),he=o.useRef(null),[X,ye]=o.useState(null),[Ce,Ee]=o.useState(""),Me=o.useRef(null),[re,ve]=o.useState(null),ie=o.useRef(null),He=o.useRef(0),$e=o.useRef(null);o.useEffect(()=>{const m=ie.current;if(!m)return;let x;const M=()=>{clearTimeout(x),x=setTimeout(()=>{const R=Xt(r,n);if(m.scrollTop>0)try{localStorage.setItem(R,String(m.scrollTop))}catch{}else localStorage.removeItem(R)},50)};return m.addEventListener("scroll",M,{passive:!0}),()=>{clearTimeout(x),m.removeEventListener("scroll",M)}},[r,n]),o.useEffect(()=>{if(!J.length)return;const m=localStorage.getItem(Xt(r,n));if(!m)return;const x=Number(m),M=ie.current;if(!M||(M.scrollTop=x,M.scrollTop>=x-10))return;let R;const ee=()=>{M.scrollTop=x,Y.disconnect()},Y=new MutationObserver(()=>{clearTimeout(R),R=setTimeout(ee,80)});Y.observe(M,{childList:!0,subtree:!0});const ne=setTimeout(ee,500);return()=>{clearTimeout(R),clearTimeout(ne),Y.disconnect()}},[r,n,J.length]),o.useEffect(()=>{ae!=null&&requestAnimationFrame(()=>{var m;return(m=he.current)==null?void 0:m.focus()})},[ae]),o.useEffect(()=>{X&&requestAnimationFrame(()=>{var m;return(m=Me.current)==null?void 0:m.focus()})},[X]);const _e=o.useRef({annotations:P,activeInsert:ae,insertText:xe,pendingAction:X,pendingText:Ce,tokens:J,filePath:n,sessionId:r,token:s});_e.current={annotations:P,activeInsert:ae,insertText:xe,pendingAction:X,pendingText:Ce,tokens:J,filePath:n,sessionId:r,token:s},o.useEffect(()=>()=>{const m=_e.current;let x=m.annotations,M=!1;if(m.activeInsert!=null&&m.insertText.trim()){const R=tt(m.tokens,m.activeInsert+1);x={...x,additions:[...x.additions,{id:Se(),afterTokenIndex:m.activeInsert,sourceLine:R,content:m.insertText.trim()}]},M=!0}if(m.pendingAction&&m.pendingText.trim()){const R=m.pendingAction,ee=m.pendingText.trim();R.type==="replace"?x={...x,replacements:[...x.replacements,{id:Se(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ee}]}:x={...x,comments:[...x.comments,{id:Se(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ee}]},M=!0}if(M){const R=JSON.stringify(x);try{localStorage.setItem(qe(m.sessionId,m.filePath),R)}catch{}Nn(m.token,m.sessionId,m.filePath,R,Date.now()).catch(()=>{})}},[]);const Ne=o.useCallback(m=>{if(!xe.trim()){Te(null),ce("");return}const x=tt(J,m+1);G(M=>({...M,additions:[...M.additions,{id:Se(),afterTokenIndex:m,sourceLine:x,content:xe.trim()}]})),Te(null),ce("")},[xe,J]),Le=o.useCallback(m=>{G(x=>({...x,additions:x.additions.filter(M=>M.id!==m)}))},[]),Ye=o.useCallback((m,x)=>{G(M=>({...M,additions:M.additions.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),ft=o.useCallback(()=>{var m;re&&(G(x=>({...x,deletions:[...x.deletions,{id:Se(),tokenIndices:re.tokenIndices,startLine:re.startLine,endLine:re.endLine,selectedText:re.text.slice(0,80)}]})),ve(null),(m=window.getSelection())==null||m.removeAllRanges())},[re]),y=o.useCallback(m=>{var x;re&&(ye({type:m,tokenIndices:re.tokenIndices,startLine:re.startLine,endLine:re.endLine,text:re.text.slice(0,80)}),Ee(""),ve(null),(x=window.getSelection())==null||x.removeAllRanges())},[re]),E=o.useCallback(()=>{if(!X)return;const m=Ce.trim();if(!m){ye(null),Ee("");return}X.type==="replace"?G(x=>({...x,replacements:[...x.replacements,{id:Se(),tokenIndices:X.tokenIndices,startLine:X.startLine,endLine:X.endLine,selectedText:X.text,content:m}]})):G(x=>({...x,comments:[...x.comments,{id:Se(),tokenIndices:X.tokenIndices,startLine:X.startLine,endLine:X.endLine,selectedText:X.text,content:m}]})),ye(null),Ee("")},[X,Ce]),K=o.useCallback(m=>{G(x=>({...x,replacements:x.replacements.filter(M=>M.id!==m)}))},[]),Z=o.useCallback((m,x)=>{G(M=>({...M,replacements:M.replacements.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),te=o.useCallback(m=>{G(x=>({...x,comments:x.comments.filter(M=>M.id!==m)}))},[]),we=o.useCallback((m,x)=>{G(M=>({...M,comments:M.comments.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),se=o.useCallback(m=>{G(x=>({...x,deletions:x.deletions.filter(M=>M.id!==m)}))},[]),fe=o.useCallback((m,x)=>{G(M=>({...M,deletions:M.deletions.map(R=>R.id===m?{...R,id:Se(),selectedText:x}:R)}))},[]),de=o.useCallback(m=>{let x=m instanceof Element?m:m.parentElement;for(;x&&x!==ie.current;){if(x.hasAttribute("data-token-index"))return x;x=x.parentElement}return null},[]),oe=o.useCallback(()=>{const m=window.getSelection();if(!m||m.isCollapsed||!ie.current){ve(null);return}const x=m.toString().trim();if(!x){ve(null);return}const M=m.getRangeAt(0);if(!ie.current.contains(M.commonAncestorContainer)){ve(null);return}const R=de(M.startContainer),ee=de(M.endContainer);if(!R||!ee){ve(null);return}const Y=parseInt(R.getAttribute("data-token-index")||"0",10),ne=parseInt(ee.getAttribute("data-token-index")||"0",10),Lt=[];for(let gt=Math.min(Y,ne);gt<=Math.max(Y,ne);gt++)Lt.push(gt);const Un=tt(J,Math.min(Y,ne)),Hn=tt(J,Math.max(Y,ne)+1),Dt=M.getBoundingClientRect(),ht=ie.current,Mt=ht.getBoundingClientRect();navigator.clipboard.writeText(x).catch(()=>{});const Xe=$e.current,At=Xe&&Date.now()-Xe.time<500;He.current=Date.now(),ve({x:(At?Xe.x:Dt.right)-Mt.left+ht.scrollLeft+6,y:(At?Xe.y:Dt.top)-Mt.top+ht.scrollTop-44,tokenIndices:Lt,startLine:Un,endLine:Hn,text:x})},[J,de]),ge=o.useRef(void 0);o.useEffect(()=>{const m=()=>{ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{const x=window.getSelection();if(!x||x.isCollapsed||!ie.current){if(Date.now()-He.current<300)return;ve(null);return}const M=x.anchorNode;M&&ie.current.contains(M)&&oe()},120)};return document.addEventListener("selectionchange",m),()=>{document.removeEventListener("selectionchange",m),ge.current&&clearTimeout(ge.current)}},[oe]);const Ke=A(m=>m.theme);ms(ie,J,Ke);const Oe=o.useCallback(()=>{const m=z.current;return{additions:P.additions.filter(x=>!m.has(x.id)),deletions:P.deletions.filter(x=>!m.has(x.id)),replacements:P.replacements.filter(x=>!m.has(x.id)),comments:P.comments.filter(x=>!m.has(x.id))}},[P]),pt=o.useCallback(async()=>{const m=Oe();if(!Qt(m))return;const x=Zt(m,_),M=nn(n);try{const{path:R}=await Yt(s,r,M,x),ee=tn(n,R);i(ee),z.current=it(P),je(ne=>ne+1);const Y=m.additions.length+m.deletions.length+m.replacements.length+m.comments.length;C("ok",`Sent ${Y} annotation(s)`)}catch(R){const ee=R instanceof Error?R.message:"Failed to send";C("err",ee)}},[Oe,P,_,i,n,s,r,C]),Fe=o.useCallback(async(m,x)=>{if(!l)return;const M={additions:[],deletions:[],replacements:[],comments:[]};if(x==="add"){const Y=P.additions.find(ne=>ne.id===m);if(!Y)return;M.additions.push(Y)}else if(x==="del"){const Y=P.deletions.find(ne=>ne.id===m);if(!Y)return;M.deletions.push(Y)}else if(x==="rep"){const Y=P.replacements.find(ne=>ne.id===m);if(!Y)return;M.replacements.push(Y)}else{const Y=P.comments.find(ne=>ne.id===m);if(!Y)return;M.comments.push(Y)}const R=Zt(M,_),ee=nn(n);try{const{path:Y}=await Yt(s,r,ee,R);l(tn(n,Y)),z.current.add(m),je(ne=>ne+1),C("ok","Sent 1 annotation")}catch(Y){const ne=Y instanceof Error?Y.message:"Failed to send";C("err",ne)}},[l,n,P,_,s,r,C]),Fn=o.useCallback((m,x)=>{x==="add"?Le(m):x==="del"?se(m):x==="rep"?K(m):te(m)},[Le,se,K,te]);o.useImperativeHandle(h,()=>({getSummary:()=>{const m=Oe();return Qt(m)?"[pending annotations]":""},handleEscape:()=>v?(V(),!0):X?(E(),!0):ae!=null?(Ne(ae),!0):!1,getScrollTop:()=>{var m;return((m=ie.current)==null?void 0:m.scrollTop)??0},setScrollTop:m=>{requestAnimationFrame(()=>{ie.current&&(ie.current.scrollTop=m)})}}),[Oe,v,V,ae,Ne,X,E]);const Bn=o.useMemo(()=>{const m=new Set;return P.deletions.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.deletions]),Pn=o.useMemo(()=>{const m=new Set;return P.replacements.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.replacements]),Wn=o.useMemo(()=>{const m=new Set;return P.comments.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.comments]),Rt=o.useMemo(()=>{const m=new Map;return P.additions.forEach(x=>{const M=m.get(x.afterTokenIndex)||[];M.push(x),m.set(x.afterTokenIndex,M)}),m},[P.additions]),Nt=Ue.unsent>0,mt=o.useCallback(m=>z.current.has(m),[]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[a.jsxs("div",{className:"plan-anno-toolbar",children:[a.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:n,children:n.split("/").pop()||n}),b&&a.jsx("span",{style:{fontSize:"10px",color:b.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:b.type==="err"?"pointer":void 0},title:b.type==="err"?"Click to copy":b.msg,onClick:b.type==="err"?()=>{navigator.clipboard.writeText(b.msg).catch(()=>{}),C("ok","Copied")}:void 0,children:b.msg}),v?a.jsxs(a.Fragment,{children:[a.jsx("button",{className:"pane-btn",onClick:U,disabled:$,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:$?"Saving...":"Save"}),a.jsx("button",{className:"pane-btn",onClick:V,disabled:$,title:"Cancel (Esc)",children:"Cancel"})]}):a.jsxs(a.Fragment,{children:[d&&a.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),!u&&a.jsx("button",{className:"pane-btn",onClick:q,title:"Edit file (double-click content)",children:"Edit"}),a.jsx("button",{className:"pane-btn",onClick:pt,disabled:!Nt,title:"Send all annotations",style:Nt?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),a.jsx(Ts,{annotations:P,annCounts:Ue,isSent:mt,onSendAll:pt,onSendSingle:Fe,onDelete:Fn}),p&&a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await pt(),p()},title:"Send annotations & close file",children:"×"})]})]}),a.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[v?a.jsx("textarea",{ref:W,className:"plan-edit-textarea",style:{fontSize:`${g}px`},value:T,onChange:m=>L(m.target.value),onKeyDown:m=>{if(m.key==="s"&&(m.ctrlKey||m.metaKey)){m.preventDefault(),U();return}if(m.key==="Escape"){m.preventDefault(),V();return}},spellCheck:!1}):a.jsxs("div",{ref:ie,className:`plan-anno-content md-preview${ae!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${g}px`,minWidth:0},onMouseUp:m=>{$e.current={x:m.clientX,y:m.clientY,time:Date.now()},oe()},onDoubleClick:m=>{u||m.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||q()},children:[!u&&a.jsx(an,{index:-1,active:ae===-1,additions:Rt.get(-1),onOpen:()=>{Te(-1),ce("")},onSubmit:()=>Ne(-1),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?m=>Fe(m,"add"):void 0,isSent:mt,insertText:xe,setInsertText:ce,textareaRef:ae===-1?he:void 0,expanded:f,alwaysShow:J.length===0,fontSize:g}),J.map((m,x)=>{const M=bs(m);return a.jsxs("div",{children:[a.jsx("div",{"data-token-index":x,id:D.get(x),className:Bn.has(x)?"plan-block--deleted":Pn.has(x)?"plan-block--replaced":Wn.has(x)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:M}}),P.deletions.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"del",annotation:R,fontSize:g,onEdit:fe,onRemove:se,onSend:l?ee=>Fe(ee,"del"):void 0,isSent:z.current.has(R.id)},R.id)),P.replacements.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"rep",annotation:R,fontSize:g,onEdit:Z,onRemove:K,onSend:l?ee=>Fe(ee,"rep"):void 0,isSent:z.current.has(R.id)},R.id)),P.comments.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"com",annotation:R,fontSize:g,onEdit:we,onRemove:te,onSend:l?ee=>Fe(ee,"com"):void 0,isSent:z.current.has(R.id)},R.id)),X&&X.tokenIndices[0]===x&&a.jsxs("div",{className:X.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[a.jsx("span",{style:{color:X.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:X.type==="replace"?"⇄":"?"}),a.jsx("textarea",{ref:Me,className:"plan-annotation-textarea",value:Ce,onChange:R=>Ee(R.target.value),onKeyDown:R=>{if(R.key==="Enter"&&(R.ctrlKey||R.metaKey)){R.preventDefault(),E();return}if(R.key==="Escape"){R.preventDefault(),E();return}},onBlur:E,placeholder:X.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:at(Ce),style:{fontSize:`${g}px`,flex:1}})]}),!u&&a.jsx(an,{index:x,active:ae===x,additions:Rt.get(x),onOpen:()=>{Te(x),ce("")},onSubmit:()=>Ne(x),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?R=>Fe(R,"add"):void 0,isSent:mt,insertText:xe,setInsertText:ce,textareaRef:ae===x?he:void 0,expanded:f,fontSize:g})]},x)}),!u&&re&&a.jsx(Es,{x:re.x,y:re.y,onDelete:ft,onReplace:()=>y("replace"),onComment:()=>y("comment")})]}),!v&&a.jsx(Ss,{headings:H,scrollRef:ie})]})]})});function an({index:t,active:e,additions:n,onOpen:r,onSubmit:s,onRemoveAddition:i,onEditAddition:l,onSendSingle:d,isSent:p,insertText:c,setInsertText:f,textareaRef:u,expanded:h,alwaysShow:g,fontSize:b=14}){const[j,k]=o.useState(null),[C,v]=o.useState(""),I=o.useRef(null),T=Tt(),L=Tt();o.useEffect(()=>{j&&(T.clearUndo(),requestAnimationFrame(()=>{const N=I.current;N&&(N.focus(),N.selectionStart=N.selectionEnd=N.value.length)}))},[j]),o.useEffect(()=>{e&&L.clearUndo()},[e]);const $=o.useCallback(N=>{v(S=>(T.pushUndo(S),N))},[T]),O=o.useCallback(N=>{L.pushUndo(c),f(N)},[c,f,L]),W=o.useCallback(N=>{k(N.id),v(N.content)},[]),B=o.useCallback(()=>{if(!j)return;const N=C.trim();N?l(j,N):i(j),k(null),v("")},[j,C,l,i]),F=o.useCallback(()=>{k(null),v("")},[]);return a.jsxs("div",{className:`plan-insert-zone${g?" plan-insert-zone--empty":""}`,"data-zone-index":t,children:[n==null?void 0:n.map(N=>a.jsx("div",{className:"plan-annotation-card",children:j===N.id?a.jsx("textarea",{ref:I,className:"plan-annotation-textarea",value:C,onChange:S=>$(S.target.value),onKeyDown:S=>{if(S.key==="Enter"&&(S.ctrlKey||S.metaKey)){S.preventDefault(),B();return}if(S.key==="Escape"){S.preventDefault(),F();return}if(S.key==="Tab"){Ct(S,$);return}},onBlur:B,rows:at(C),style:{fontSize:`${b}px`,flex:1,...h?{minWidth:300}:void 0}}):a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{flex:1,fontSize:`${b}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>W(N),title:"Double-click to edit",children:N.content}),d&&(()=>{const S=(p==null?void 0:p(N.id))??!1;return a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!S&&d(N.id),disabled:S,title:S?"Already sent":"Send to terminal",style:S?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>W(N),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(N.id),children:"×"})]})},N.id)),e?a.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:a.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:c,onChange:N=>O(N.target.value),onKeyDown:N=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)){N.preventDefault(),s();return}if(N.key==="Escape"){N.preventDefault(),s();return}if(N.key==="Tab"){Ct(N,O);return}},onBlur:s,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:at(c),style:{fontSize:`${b}px`,...h?{minWidth:300}:void 0}})}):g&&!(n!=null&&n.length)?a.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."}):a.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function Re(t,e,n){const r=n?{path:n}:void 0;return pe.get(t,e,"files",r)}function Is(t,e,n,r){return new Promise((s,i)=>{const l=new FormData;for(const p of n)l.append("files",p);const d=new XMLHttpRequest;d.open("POST",`${De}/api/sessions/${encodeURIComponent(e)}/upload`),d.setRequestHeader("Authorization",`Bearer ${t}`),d.upload.addEventListener("progress",p=>{p.lengthComputable&&r&&r(Math.round(p.loaded/p.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?s():i(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>i(new Error("Upload network error"))),d.addEventListener("abort",()=>i(new Error("Upload aborted"))),d.send(l)})}async function ln(t,e){return(await pe.get(t,e,"cwd")).cwd}async function Rs(t,e,n){return pe.post(t,e,"touch",{name:n})}async function Ns(t,e,n){return pe.post(t,e,"mkdir",{path:n})}async function Ls(t,e,n){return pe.del(t,e,"rm",{path:n})}async function Ds(t,e){const n=await pe.getBlob(t,e,"download-cwd"),r=await n.blob(),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s;const l=n.headers.get("Content-Disposition"),d=l==null?void 0:l.match(/filename="(.+)"/);i.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(s)}async function Ms(t,e,n){const s=await(await pe.getBlob(t,e,"download",{path:n})).blob(),i=URL.createObjectURL(s),l=document.createElement("a");l.href=i,l.download=n.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}function Mn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function As(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function An(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function zs({sessionId:t,token:e,planDir:n,selectedFile:r,onSelectFile:s,onCreateFile:i,onDeleteFile:l}){const[d,p]=o.useState([]),[c,f]=o.useState(!0),[u,h]=o.useState(""),[g,b]=o.useState(!1),j=o.useRef(null),[k,C]=o.useState(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n))return w}return n});o.useEffect(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n)){C(w);return}}C(n)},[r,n]);const v=o.useCallback(async()=>{if(!(!e||!k)){f(!0);try{const q=(await Re(e,t,k)).files.filter(V=>V.type==="file"&&(V.name.toLowerCase().endsWith(".md")||V.name===".index.json")||V.type==="directory").sort((V,U)=>{const J=V.type==="file"&&V.name===".index.json",_=U.type==="file"&&U.name===".index.json";return J&&!_?-1:!J&&_?1:V.type==="directory"&&U.type!=="directory"?-1:V.type!=="directory"&&U.type==="directory"?1:V.name.localeCompare(U.name)});p(q)}catch{p([])}finally{f(!1)}}},[e,t,k]);o.useEffect(()=>{v()},[v]),o.useEffect(()=>{const w=setInterval(v,5e3);return()=>clearInterval(w)},[v]);const I=o.useCallback(()=>{const w=n.substring(0,n.lastIndexOf("/")+1);return k.startsWith(w)?k.substring(w.length):k},[n,k]),T=o.useCallback(async()=>{const w=u.trim();if(!w)return;const q=w.endsWith(".md")?w:`${w}.md`;b(!0);try{const V=await Rs(e,t,`${I()}/${q}`);V.ok&&(h(""),await v(),i(V.path))}catch{}finally{b(!1)}},[u,e,t,I,v,i]),L=o.useCallback(async()=>{const w=u.trim().replace(/\/+$/,"");if(w){b(!0);try{await Ns(e,t,`${I()}/${w}`),h(""),await v()}catch{}finally{b(!1)}}},[u,e,t,I,v]),$=o.useCallback(async w=>{const q=`${k}/${w.name}`,V=w.type==="directory"?`folder "${w.name}" and all its contents`:`"${w.name}"`;if(window.confirm(`Delete ${V}?`))try{await Ls(e,t,q),l==null||l(q),await v()}catch{}},[e,t,k,v,l]),O=o.useCallback(w=>{C(q=>`${q}/${w}`)},[]),W=o.useCallback(()=>{k!==n&&C(w=>w.substring(0,w.lastIndexOf("/")))},[k,n]),B=n.split("/").pop()||"AiTasks",F=(()=>{const w=n.split("/");return w.length>=2?w[w.length-2]+"/":""})(),N=k===n?F+B+"/":F+B+"/"+k.substring(n.length+1)+"/",S=r?r.split("/").pop():null;return a.jsxs("div",{className:"plan-file-browser",children:[a.jsxs("div",{className:"plan-file-browser__header",children:[a.jsx("span",{className:"plan-file-browser__title",title:N,children:N}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:v,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),a.jsxs("div",{className:"plan-file-browser__create",children:[a.jsx("input",{ref:j,className:"plan-file-browser__input",value:u,onChange:w=>h(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),T())},placeholder:"name",disabled:g}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:T,disabled:g||!u.trim(),title:"Create new .md file",style:u.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:L,disabled:g||!u.trim(),title:"Create new folder",style:u.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),a.jsxs("div",{className:"plan-file-browser__list",children:[c&&d.length===0&&a.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&d.length===0&&a.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),k!==n&&a.jsxs("div",{className:"plan-file-browser__item",onClick:W,title:"Go up to parent directory",style:{cursor:"pointer"},children:[a.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),a.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(w=>{const q=`${k}/${w.name}`,V=w.type==="file"&&w.name===S,U=w.type==="directory";return a.jsxs("div",{className:`plan-file-browser__item${V?" plan-file-browser__item--active":""}`,onClick:()=>U?O(w.name):s(q),title:U?`Open folder ${w.name}`:w.name,style:{cursor:"pointer"},children:[a.jsx("span",{className:"plan-file-browser__icon",children:U?"📁":w.name===".index.json"?"🔒":"□"}),a.jsxs("span",{className:"plan-file-browser__name",children:[w.name,U?"/":""]}),!U&&a.jsx("span",{className:"plan-file-browser__size",children:Mn(w.size)}),!w.name.startsWith(".")&&a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:J=>{J.stopPropagation(),$(w)},title:`Delete ${w.name}`,children:"×"})]},w.name)})]})]})}const vt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},$s=200;function _s(){const[t,e]=o.useState(vt),n=o.useRef("lines"),r=o.useRef([]),s=o.useRef(""),i=o.useRef(""),l=o.useRef([]),d=o.useRef(0),p=o.useRef(0),c=o.useRef(null),f=o.useRef(null),u=o.useCallback(()=>{const C=n.current;e(v=>({...v,receivedBytes:d.current,...C==="lines"?{lines:[...r.current]}:{},...C==="content"?{content:i.current}:{}}))},[]),h=o.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,u()},$s))},[u]),g=o.useCallback(C=>{n.current=C,r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...vt,mode:C,status:"streaming"})},[]),b=o.useCallback(C=>{d.current+=C.length;const v=n.current;if(v==="lines"){const T=f.current.decode(C,{stream:!0}).split(`
|
|
30
30
|
`);T[0]=s.current+T[0],s.current=T.pop(),T.length>0&&r.current.push(...T)}else if(v==="content"){const I=f.current.decode(C,{stream:!0});i.current+=I}else l.current.push(new Uint8Array(C));h()},[h]),j=o.useCallback(C=>{switch(C.type){case"file-stream-start":p.current=C.size,e(v=>({...v,totalSize:C.size,mtime:C.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const v=n.current;let I=r.current,T=i.current,L=null;if(v==="lines"){const $=f.current.decode(),O=s.current+$;O&&(I=[...I,O],r.current=I),s.current=""}else if(v==="content"){const $=f.current.decode();T=i.current+$,i.current=T}else{const $=l.current.reduce((W,B)=>W+B.length,0);L=new Uint8Array($);let O=0;for(const W of l.current)L.set(W,O),O+=W.length;l.current=[]}e({status:"complete",mode:v,lines:v==="lines"?[...I]:[],content:v==="content"?T:"",buffer:v==="binary"?L:null,totalSize:p.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(v=>({...v,status:"error",error:C.error}));break}},[]),k=o.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=null,e(vt)},[]);return{state:t,startStream:g,handleChunk:b,handleControl:j,reset:k}}function cn({label:t,percent:e}){return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:t}),e!=null&&a.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[a.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:a.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),a.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function Os({sessionId:t,token:e,connected:n,onRequestFileStream:r,onSendToTerminal:s}){const i=_s(),[l,d]=o.useState(!1),[p,c]=o.useState(null),[f,u]=o.useState(null),[h,g]=o.useState(""),[b,j]=o.useState(!1),[k,C]=o.useState(!1),v=o.useRef(null),I="plan-selected-file",T=o.useRef(void 0);o.useEffect(()=>{if(f)return clearTimeout(T.current),T.current=setTimeout(()=>{try{localStorage.setItem(I,f)}catch{}},50),()=>clearTimeout(T.current)},[f]);const L=o.useRef(null);o.useEffect(()=>{L.current=null;let D=!1;return j(!0),C(!1),(async()=>{let z="";try{const Q=await Re(e,t);if(D)return;if(z=Q.home||"",Q.files.find(G=>G.name==="AiTasks"&&G.type==="directory")){const G=Q.cwd+"/AiTasks";c(G);const be=localStorage.getItem(I);be&&be.startsWith(G+"/")&&u(be)}else c(null),u(null),C(!0)}catch{c(null)}finally{D||j(!1)}try{if(D)return;if(z){const Q=`${z}/.claude/plugins/installed_plugins.json`,P=await sn(e,t,Q,0);if(!D&&P)try{const G=JSON.parse(P.content);"ai-cli-task@moonview"in(G.plugins||G)||d(!0)}catch{d(!0)}}}catch{}})(),()=>{D=!0}},[t,e]),o.useEffect(()=>{if(!k||!n)return;const D=setInterval(async()=>{try{const z=await Re(e,t);if(z.files.find(P=>P.name==="AiTasks"&&P.type==="directory")){const P=z.cwd+"/AiTasks";c(P),C(!1);const G=localStorage.getItem(I);G&&G.startsWith(P+"/")&&u(G)}}catch{}},3e3);return()=>clearInterval(D)},[k,n,e,t,I]),o.useEffect(()=>(Wr(t,i.handleChunk,i.handleControl),()=>Ur(t)),[t,i.handleChunk,i.handleControl]),o.useEffect(()=>{!f||!n||L.current===f&&h||(L.current=f,i.reset(),i.startStream("content"),r==null||r(f))},[f,n]);const $=o.useRef(0);o.useEffect(()=>{i.state.status==="complete"&&f&&(g(i.state.content),$.current=Date.now())},[i.state.status,i.state.content,f]),o.useEffect(()=>{if(!f||!n||!h)return;const D=setInterval(async()=>{if($.current)try{const z=await sn(e,t,f,$.current);z&&(g(z.content),$.current=z.mtime)}catch{}},3e3);return()=>clearInterval(D)},[f,n,h,e,t]);const O=o.useRef(new Map),W=o.useCallback(()=>{var z,Q;if(!f)return;const D=((Q=(z=v.current)==null?void 0:z.getScrollTop)==null?void 0:Q.call(z))??0;D>0&&O.current.set(f,D)},[f]);o.useEffect(()=>{if(!f||!h)return;const D=O.current.get(f);D!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var z,Q;(Q=(z=v.current)==null?void 0:z.setScrollTop)==null||Q.call(z,D)})})},[f,h]);const B=o.useCallback(D=>{D!==f&&(W(),u(D),g(""),L.current=null)},[f,W]),F=o.useCallback(D=>{f&&(f===D||f.startsWith(D+"/"))&&(u(null),g(""),L.current=null)},[f]),N=o.useCallback(D=>{u(D),g(""),L.current=null},[]),S=o.useCallback(D=>{D&&(s==null||s(D))},[s]),w=o.useCallback((D,z)=>{g(D),$.current=z},[]),q=o.useCallback(()=>{W(),u(null),g(""),L.current=null},[W]),V=o.useCallback(()=>{!f||!n||(L.current=null,g(""),i.reset(),i.startStream("content"),r==null||r(f),L.current=f)},[f,n,i,r]),[U,J]=o.useState(()=>{const D=localStorage.getItem(`plan-fb-width-${t}`);if(D){const z=Number(D);if(Number.isFinite(z)&&z>=60&&z<=300)return z}return 130}),_=o.useRef(U);if(U!==_.current){_.current=U;try{localStorage.setItem(`plan-fb-width-${t}`,String(Math.round(U)))}catch{}}const H=o.useCallback(D=>{D.preventDefault();const z=D.clientX,Q=U;document.body.classList.add("resizing-panes");const P=be=>{const je=be.clientX-z;J(Math.min(300,Math.max(60,Q+je)))},G=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",G)};document.addEventListener("mousemove",P),document.addEventListener("mouseup",G)},[U]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[l&&a.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:[a.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),a.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{s&&s("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),d(!1)},children:"Install"}),a.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>d(!1),children:"×"})]}),a.jsxs("div",{className:"plan-overlay-body",children:[p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{width:U,flexShrink:0,overflow:"hidden"},children:a.jsx(zs,{sessionId:t,token:e,planDir:p,selectedFile:f,onSelectFile:B,onCreateFile:N,onDeleteFile:F})}),a.jsx("div",{onMouseDown:H,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:D=>{D.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:D=>{D.currentTarget.style.backgroundColor="var(--border)"}})]}),a.jsx("div",{className:"plan-overlay-center",children:b?a.jsx(cn,{label:"Loading AiTasks/..."}):k?a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),a.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",a.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/ai-cli-task:init <name>"})," in the terminal to create a task"]})]}):f&&!h&&(i.state.status==="streaming"||i.state.status==="idle")?a.jsx(cn,{label:`Loading ${f.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):f?a.jsx(js,{ref:v,markdown:h,filePath:f,sessionId:t,token:e,onExecute:S,onSend:s,onRefresh:V,onClose:q,onContentSaved:w,readOnly:f.endsWith("/.index.json")}):a.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]})]})}async function Fs(t,e){try{return(await pe.get(t,e,"draft")).content??""}catch{return""}}async function dn(t,e,n){try{await pe.put(t,e,"draft",{content:n})}catch{}}const It="chat-history",un=50;function zn(){try{const t=localStorage.getItem(It);return t?JSON.parse(t):[]}catch{return[]}}function Bs(t){const n=zn().filter(r=>r.text!==t);n.unshift({text:t,ts:Date.now()}),n.length>un&&(n.length=un),localStorage.setItem(It,JSON.stringify(n))}const fn=[{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:"/ai-cli-task:ai-cli-task",desc:"Task lifecycle management (8 skills)"},{cmd:"/ai-cli-task:init",desc:"Initialize task module + branch"},{cmd:"/ai-cli-task:plan",desc:"Generate plan or process annotations"},{cmd:"/ai-cli-task:check",desc:"Check feasibility (post-plan/mid/post-exec)"},{cmd:"/ai-cli-task:exec",desc:"Execute implementation plan"},{cmd:"/ai-cli-task:merge",desc:"Merge task branch to main"},{cmd:"/ai-cli-task:report",desc:"Generate completion report"},{cmd:"/ai-cli-task:auto",desc:"Autonomous full lifecycle loop"},{cmd:"/ai-cli-task:cancel",desc:"Cancel task + optional cleanup"}],Ps=o.forwardRef(function({onSend:e,onContentChange:n,sessionId:r,token:s},i){const l=A(y=>y.fontSize),[d,p]=o.useState(""),c=o.useRef(null),f=o.useRef(void 0),u=o.useRef(!1),h=o.useRef(!1),{pushUndo:g,popUndo:b}=Tt(),j=o.useRef(d);j.current=d;const k=o.useCallback(()=>g(j.current),[g]),[C,v]=o.useState(!1),[I,T]=o.useState(""),[L,$]=o.useState(0),[O,W]=o.useState(!1),[B,F]=o.useState([]),[N,S]=o.useState(0),[w,q]=o.useState(""),V=o.useRef(null),U=o.useMemo(()=>{if(!w)return B;const y=w.toLowerCase();return B.filter(E=>E.text.toLowerCase().includes(y))},[B,w]),[J,_]=o.useState(!1),[H,D]=o.useState(""),[z,Q]=o.useState(""),[P,G]=o.useState(0),[be,je]=o.useState([]),[Ue,ae]=o.useState(!1),Te=o.useRef(""),xe=o.useRef(null),ce=o.useMemo(()=>{if(!I)return fn;const y=I.toLowerCase();return fn.filter(E=>E.cmd.toLowerCase().includes(y)||E.desc.toLowerCase().includes(y))},[I]),he=o.useMemo(()=>{let y=be;if(H){const E=H.toLowerCase();y=y.filter(K=>K.name.toLowerCase().includes(E))}return[...y].sort((E,K)=>E.type==="directory"&&K.type!=="directory"?-1:E.type!=="directory"&&K.type==="directory"?1:E.name.localeCompare(K.name))},[be,H]),X=A(y=>y.latency),ye=`chat-draft-${r}`,Ce=o.useRef(!1),Ee=o.useRef(void 0);o.useEffect(()=>{try{const E=localStorage.getItem(ye);E&&!h.current&&p(E)}catch{}let y=!1;return Fs(s,r).then(E=>{if(y||h.current){u.current=!0;return}if(E){p(E);try{localStorage.setItem(ye,E)}catch{}}u.current=!0}).catch(()=>{u.current=!0}),()=>{y=!0}},[s,r,ye]),o.useEffect(()=>{if(!u.current)return;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{try{localStorage.setItem(ye,d)}catch{}},50),Ee.current&&clearTimeout(Ee.current);const y=Math.max(200,(X??30)*3);return Ee.current=setTimeout(()=>{Ce.current||(Ce.current=!0,dn(s,r,d).catch(()=>{}).finally(()=>{Ce.current=!1}))},y),()=>{f.current&&clearTimeout(f.current),Ee.current&&clearTimeout(Ee.current)}},[d,s,r,X,ye]),o.useEffect(()=>{var y;(y=c.current)==null||y.focus()},[]),o.useEffect(()=>{if(!J)return;let y=!1;return ae(!0),(async()=>{try{if(z){if(!Te.current){const Z=await Re(s,r);if(y)return;Te.current=Z.cwd}const E=`${Te.current}/${z.replace(/\/$/,"")}`,K=await Re(s,r,E);if(y)return;je(K.files)}else{const E=await Re(s,r);if(y)return;Te.current=E.cwd,je(E.files)}ae(!1)}catch{if(y)return;je([]),ae(!1)}})(),()=>{y=!0}},[J,z,s,r]),o.useEffect(()=>{if(!J||!xe.current)return;const y=xe.current.querySelector(".file-item--active");y==null||y.scrollIntoView({block:"nearest"})},[P,J]);const Me=o.useCallback(()=>{const y=j.current.trim();if(y){Bs(y),e(y),p("");try{localStorage.removeItem(ye)}catch{}dn(s,r,"").catch(()=>{})}},[e,s,r,ye]),re=o.useCallback(y=>{k(),p(y),h.current=!0},[k]),ve=o.useCallback(y=>{const E=c.current;k();const K=j.current;if(E){const Z=E.selectionStart,te=E.selectionEnd,we=K.slice(0,Z)+y+K.slice(te);p(we);const se=Z+y.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=se,E.focus()})}else p(K+y)},[k]);o.useImperativeHandle(i,()=>({send:Me,fillContent:re,insertAtCursor:ve}),[Me,re,ve]),o.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const ie=o.useCallback(()=>{const y=c.current;if(!y)return;const{selectionStart:E,selectionEnd:K}=y;if(E!==K){const Z=y.value.substring(E,K);Z&&navigator.clipboard.writeText(Z).catch(()=>{})}},[]),He=o.useCallback(()=>{const y=zn();v(!1),T("");const E=c.current;if(E){const K=E.selectionStart,Z=d.slice(0,K),te=d.slice(K),we=Z.match(/(?:^|\s)(\/history)\s*$/);if(we){const se=Z.length-we[1].length;p(d.slice(0,se)+te)}}y.length!==0&&(F(y),S(0),q(""),W(!0))},[d]),$e=o.useCallback(y=>{k(),p(y.text),W(!1),requestAnimationFrame(()=>{const E=c.current;E&&(E.selectionStart=E.selectionEnd=y.text.length,E.focus())})},[k]),_e=o.useCallback(y=>{const E=U[y];if(!E)return;const K=B.filter(te=>te.ts!==E.ts||te.text!==E.text);F(K),localStorage.setItem(It,JSON.stringify(K));const Z=w?K.filter(te=>te.text.toLowerCase().includes(w.toLowerCase())):K;N>=Z.length&&S(Math.max(0,Z.length-1))},[U,B,N,w]);o.useEffect(()=>{if(!O||!V.current)return;const y=V.current.querySelector(".history-item--active");y==null||y.scrollIntoView({block:"nearest"})},[N,O]);const Ne=o.useCallback(y=>{if(y==="/history"){He();return}const E=c.current;if(!E)return;k();const K=E.selectionStart,Z=d.slice(0,K),te=d.slice(K),se=Z.lastIndexOf(`
|
|
31
31
|
`)+1,de=Z.slice(se).match(/\/[a-zA-Z:-]*$/);if(de){const oe=se+(de.index??0),ge=y+" ",Ke=d.slice(0,oe)+ge+te;p(Ke);const Oe=oe+ge.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=Oe,E.focus()})}else{const oe=Z+y+te;p(oe);const ge=K+y.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ge,E.focus()})}v(!1),T(""),$(0)},[d,k,He]),Le=o.useCallback(y=>{const E=c.current;if(!E)return;k();const K=E.selectionStart,Z=d.slice(0,K),te=d.slice(K),we=Z.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!we)return;const se=Z.length-we[0].length;if(y.type==="directory"){const fe="@"+z+y.name+"/",de=d.slice(0,se)+fe+te;p(de);const oe=se+fe.length;Q(z+y.name+"/"),D(""),G(0),requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=oe,E.focus()})}else{const fe=y.name+" ",de=d.slice(0,se)+fe+te;p(de);const oe=se+fe.length;_(!1),D(""),Q(""),G(0),je([]),Te.current="",requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=oe,E.focus()})}},[d,z,k]),Ye=o.useCallback(y=>{const E=y.target.value;if(p(E),O){const fe=E.trim();fe?(q(fe),S(0)):q("");return}const K=y.target.selectionStart,Z=E.slice(0,K),te=Z.lastIndexOf(`
|
|
32
32
|
`),se=Z.slice(te+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(se)v(!0),T(se[1]),$(0),_(!1);else{v(!1);const fe=Z.match(/@([a-zA-Z0-9_.\-/]*)$/);if(fe){const de=fe[1],oe=de.lastIndexOf("/"),ge=oe>=0?de.slice(0,oe+1):"",Ke=oe>=0?de.slice(oe+1):de;D(Ke),G(0),Q(ge),_(!0)}else _(!1)}},[O]),ft=o.useCallback(y=>{if(C&&ce.length>0){if(y.key==="ArrowDown"){y.preventDefault(),$(E=>(E+1)%ce.length);return}if(y.key==="ArrowUp"){y.preventDefault(),$(E=>(E-1+ce.length)%ce.length);return}if(y.key==="Enter"||y.key==="Tab"){y.preventDefault(),Ne(ce[L].cmd);return}if(y.key==="Escape"){y.preventDefault(),v(!1);return}}if(J&&he.length>0){if(y.key==="ArrowDown"){y.preventDefault(),G(E=>(E+1)%he.length);return}if(y.key==="ArrowUp"){y.preventDefault(),G(E=>(E-1+he.length)%he.length);return}if(y.key==="Tab"||y.key==="Enter"){y.preventDefault(),Le(he[P]);return}if(y.key==="Escape"){y.preventDefault(),_(!1);return}}if(O&&U.length>0){if(y.key==="ArrowDown"){y.preventDefault(),S(E=>(E+1)%U.length);return}if(y.key==="ArrowUp"){y.preventDefault(),S(E=>(E-1+U.length)%U.length);return}if(y.key==="Enter"){y.preventDefault(),$e(U[N]);return}if(y.key==="Delete"||y.key==="Backspace"&&(y.ctrlKey||y.metaKey)){y.preventDefault(),_e(N);return}if(y.key==="Escape"){y.preventDefault(),W(!1);return}}if(y.key==="Tab"){Ct(y,p,g);return}y.key==="Enter"&&(y.ctrlKey||y.metaKey)&&(y.preventDefault(),Me())},[Me,C,ce,L,Ne,J,he,P,Le,g,b,O,U,N,$e,_e]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[C&&ce.length>0&&a.jsx("div",{className:"slash-dropdown",children:ce.map((y,E)=>a.jsxs("div",{className:`slash-item${E===L?" slash-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ne(y.cmd)},onMouseEnter:()=>$(E),children:[a.jsx("span",{className:"slash-cmd",children:y.cmd}),a.jsx("span",{className:"slash-desc",children:y.desc})]},y.cmd))}),J&&(Ue||he.length>0)&&a.jsx("div",{className:"file-dropdown",ref:xe,children:Ue?a.jsx("div",{className:"file-item file-loading",children:"Loading..."}):he.map((y,E)=>a.jsxs("div",{className:`file-item${E===P?" file-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Le(y)},onMouseEnter:()=>G(E),children:[a.jsx("span",{className:"file-icon",children:y.type==="directory"?"📁":"📄"}),a.jsx("span",{className:"file-name",children:y.name})]},y.name))}),O&&a.jsx("div",{className:"history-dropdown",ref:V,children:U.length===0?a.jsx("div",{className:"history-item history-empty",children:"No history yet"}):U.map((y,E)=>a.jsxs("div",{className:`history-item${E===N?" history-item--active":""}`,onMouseDown:K=>{K.preventDefault(),$e(y)},onMouseEnter:()=>S(E),children:[a.jsx("span",{className:"history-text",children:y.text.length>120?y.text.slice(0,120)+"...":y.text}),a.jsx("span",{className:"history-time",children:new Date(y.ts).toLocaleString()}),a.jsx("button",{className:"history-delete",onMouseDown:K=>{K.preventDefault(),K.stopPropagation(),_e(E)},title:"Delete (Del key)",children:"×"})]},`${y.ts}-${E}`))}),a.jsx("textarea",{ref:c,className:"md-editor-textarea",value:d,onChange:Ye,onKeyDown:ft,onMouseUp:ie,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${l}px`}})]})});function Ws({token:t,sessionId:e,onClose:n}){const[r,s]=o.useState([]),[i,l]=o.useState(""),[d,p]=o.useState([]),[c,f]=o.useState(!0),[u,h]=o.useState(!1),g=o.useRef(null);o.useEffect(()=>{let v=!1;return(async()=>{try{const I=await Re(t,e);v||(l(I.cwd),s(I.files))}catch{v||n()}finally{v||f(!1)}})(),()=>{v=!0}},[t,e,n]),o.useEffect(()=>{const v=L=>{L.key==="Escape"&&n()},I=L=>{g.current&&!g.current.contains(L.target)&&n()};document.addEventListener("keydown",v);const T=setTimeout(()=>document.addEventListener("mousedown",I),50);return()=>{document.removeEventListener("keydown",v),document.removeEventListener("mousedown",I),clearTimeout(T)}},[n]);const b=o.useCallback(async v=>{f(!0);try{const I=await Re(t,e,v);p(T=>[...T,i]),l(v),s(I.files)}catch{}finally{f(!1)}},[t,e,i]),j=o.useCallback(async()=>{if(d.length===0)return;const v=d[d.length-1];f(!0);try{const I=await Re(t,e,v);p(T=>T.slice(0,-1)),l(v),s(I.files)}catch{}finally{f(!1)}},[t,e,d]),k=o.useCallback(async v=>{try{await Ms(t,e,v)}catch(I){alert(`Download failed: ${I instanceof Error?I.message:"Unknown error"}`)}},[t,e]),C=o.useCallback(async()=>{h(!0),n();try{await Ds(t,e)}catch(v){alert(`Download failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{h(!1)}},[t,e,n]);return a.jsxs("div",{ref:g,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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[d.length>0&&a.jsx("button",{className:"pane-btn",onClick:j,disabled:c,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),a.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}),a.jsx("button",{className:"pane-btn",onClick:n,style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),a.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:c?a.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?a.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(v=>a.jsxs("div",{onClick:()=>{const I=i+"/"+v.name;v.type==="directory"?b(I):k(I)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[a.jsx("span",{style:{flexShrink:0,fontSize:13},children:v.type==="directory"?"📁":As(v.name,v.type)}),a.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.type==="directory"?a.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):v.size!=null?a.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:Mn(v.size)}):null]},v.name))}),a.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:a.jsx("button",{className:"pane-btn",onClick:C,disabled:u,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:u?"Downloading...":"Download All (tar.gz)"})})]})}function pn(t,e,{containerRef:n,axis:r,offset:s=0,min:i,max:l,invert:d=!1,bodyClass:p}){const[c,f]=o.useState(()=>{const g=localStorage.getItem(t);if(g){const b=Number(g);if(Number.isFinite(b)&&b>=i&&b<=l)return b}return e}),u=o.useRef(c);if(c!==u.current){u.current=c;try{localStorage.setItem(t,String(Math.round(c)))}catch{}}const h=o.useCallback(g=>{g.preventDefault();const b=n.current;if(!b)return;const j=b.getBoundingClientRect(),k=r==="x"?j.width:j.height-s,C=r==="x"?j.left:j.top+s;document.body.classList.add(p);const v=T=>{let $=((r==="x"?T.clientX:T.clientY)-C)/k*100;d&&($=100-$),f(Math.min(l,Math.max(i,$)))},I=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",I)},[n,r,s,i,l,d,p]);return[c,h]}const Us=600,Pe=typeof window<"u"?window.matchMedia(`(max-width: ${Us-1}px)`):null;function Hs(){const[t,e]=o.useState(()=>(Pe==null?void 0:Pe.matches)??!1);return o.useEffect(()=>{if(!Pe)return;const n=r=>e(r.matches);return Pe.addEventListener("change",n),()=>Pe.removeEventListener("change",n)},[]),t}const Ks=o.memo(function({terminal:e}){const n=Hs(),r=A(_=>_.splitTerminal),s=A(_=>_.token),i=A(_=>_.toggleChat),l=A(_=>_.togglePlan),{chatOpen:d,planOpen:p}=e.panels,c=o.useRef(null),f=o.useRef(null),u=o.useRef(null),h=o.useRef(null),g=o.useRef(null),[b,j]=pn(`plan-width-${e.id}`,50,{containerRef:f,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[k,C]=pn(`doc-height-${e.id}`,35,{containerRef:c,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[v,I]=o.useState("");o.useEffect(()=>{if(!s||!e.connected)return;let _=!1;const H=async()=>{try{const z=await ln(s,e.id);_||I(z)}catch{}};H();const D=setInterval(H,5e3);return()=>{_=!0,clearInterval(D)}},[s,e.id,e.connected]);const T=o.useCallback(async _=>{let H;if(s)try{H=await ln(s,e.id)}catch{}r(e.id,_,H)},[s,e.id,r]),[L,$]=o.useState(!1),[O,W]=o.useState(0),[B,F]=o.useState(!1),[N,S]=o.useState(!1),w=async _=>{const H=_.target.files;if(!(!H||H.length===0||!s)){$(!0),W(0);try{await Is(s,e.id,H,D=>{W(D)})}catch(D){alert(`Upload failed: ${D instanceof Error?D.message:"Unknown error"}`)}finally{$(!1),W(0),u.current&&(u.current.value="")}}},q=o.useRef(void 0),V=o.useCallback(_=>{if(h.current){const H=_.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(H),q.current=window.setTimeout(()=>{var D;return(D=h.current)==null?void 0:D.sendInput("\r")},50)}},[]);o.useEffect(()=>()=>{q.current&&clearTimeout(q.current)},[]);const U=o.useCallback(_=>{if(h.current){const H=_.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(H),setTimeout(()=>{var D;return(D=h.current)==null?void 0:D.sendInput("\r")},50)}},[]),J=o.useCallback(()=>S(!1),[]);return a.jsxs("div",{ref:c,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[a.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),a.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]}),v&&a.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:v,children:v})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[a.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:w}),a.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=u.current)==null?void 0:_.click()},disabled:L,style:L?{color:"var(--accent-yellow)"}:void 0,title:L?`Uploading ${O}%`:"Upload files","aria-label":"Upload files",children:L?`${O}%`:"↑"}),a.jsxs("div",{style:{position:"relative"},children:[a.jsx("button",{className:"pane-btn",onClick:()=>S(!0),title:"Download files","aria-label":"Download files",children:"↓"}),N&&s&&a.jsx(Ws,{token:s,sessionId:e.id,onClose:J})]}),a.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),a.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),a.jsx("button",{className:"pane-btn",onClick:()=>T(n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),a.jsx("button",{className:"pane-btn",onClick:()=>T("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),a.jsxs("div",{ref:f,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{width:`${b}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:a.jsx(Os,{sessionId:e.id,token:s||"",connected:e.connected,onRequestFileStream:_=>{var H;return(H=h.current)==null?void 0:H.requestFileStream(_)},onSendToTerminal:U})}),a.jsx("div",{className:"md-editor-divider-h",onMouseDown:j,style:{width:"3px",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)"}})]}),a.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[a.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[a.jsx(as,{ref:h,sessionId:e.id}),!e.connected&&a.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"md-editor-divider",onMouseDown:C}),a.jsxs("div",{style:{height:`${k}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[a.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:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),a.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=g.current)==null?void 0:_.send()},disabled:!B,title:"Send to terminal (Ctrl+Enter)",style:B?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),a.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),a.jsx("div",{style:{flex:1,overflow:"hidden"},children:a.jsx(Ps,{ref:g,onSend:V,onContentChange:F,sessionId:e.id,token:s||""})})]})]})]})]}),e.error&&a.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 $n extends o.Component{constructor(){super(...arguments);zt(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){}render(){var n,r;return this.state.hasError?this.props.inline?a.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:[a.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),a.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textAlign:"center"},children:((n=this.state.error)==null?void 0:n.message)||"An unexpected error occurred"}),a.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"})]}):a.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:[a.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),a.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"}),a.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 Js=4,mn=10;function Vs(){const t=A(s=>s.layout),e=A(s=>s.terminalIds.length),n=A(s=>s.addTerminal);if(!t)return a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:a.jsx("button",{onClick:()=>n(),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 a.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:a.jsx(_n,{node:t,canClose:r})})}const _n=o.memo(function({node:e,canClose:n}){return e.type==="leaf"?a.jsx(Gs,{terminalId:e.terminalId,canClose:n}):a.jsx(qs,{node:e,canClose:n})}),Gs=o.memo(function({terminalId:e,canClose:n}){const r=A(i=>i.terminalsMap[e]),s=A(i=>i.reconnectTerminal);return r?a.jsx($n,{inline:!0,children:a.jsx(Ks,{terminal:r,canClose:n})}):a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:a.jsxs("button",{onClick:()=>s(e),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",e]})})}),qs=o.memo(function({node:e,canClose:n}){const r=A(c=>c.setSplitSizes),s=o.useRef(null),i=e.direction==="horizontal",l=o.useRef(e.sizes);l.current=e.sizes;const d=o.useCallback((c,f)=>{f.preventDefault();const u=i?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const h=i?f.clientX:f.clientY,g=[...l.current],b=s.current,j=i?(b==null?void 0:b.clientWidth)||1:(b==null?void 0:b.clientHeight)||1;let k=null;const C=I=>{k||(k=requestAnimationFrame(()=>{k=null;const $=((i?I.clientX:I.clientY)-h)/j*100,O=g[c]+$,W=g[c+1]-$;if(O>=mn&&W>=mn){const B=[...g];B[c]=O,B[c+1]=W,r(e.id,B)}}))},v=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(u),document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",C),document.addEventListener("mouseup",v)},[i,e.id,r]),p=[];return e.children.forEach((c,f)=>{const u=c.type==="leaf"?c.terminalId:c.id;p.push(a.jsx("div",{style:{flex:`${e.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:a.jsx(_n,{node:c,canClose:n})},u)),f<e.children.length-1&&p.push(a.jsx("div",{onMouseDown:h=>d(f,h),style:{flex:`0 0 ${Js}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}-${f}`))}),a.jsx("div",{ref:s,style:{display:"flex",flexDirection:i?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function Ys({tabId:t}){const e=A(S=>S.tabs.find(w=>w.id===t)),n=A(S=>S.activeTabId),r=A(S=>S.switchTab),s=A(S=>S.closeTab),i=A(S=>S.reopenTab),l=A(S=>S.deleteTab),d=A(S=>S.renameTab),p=A(S=>e?e.terminalIds.map(w=>{const q=S.terminalsMap[w];return q?{id:w,connected:q.connected,active:!0}:{id:w,connected:!1,active:!1}}):[]),c=A(S=>S.disconnectTerminal),f=A(S=>S.reconnectTerminal),u=A(S=>S.killServerSession),[h,g]=o.useState(!1),[b,j]=o.useState(""),[k,C]=o.useState(!1),v=o.useRef(null);if(!e)return null;const I=n===t,T=e.status==="open",L=()=>{T&&r(t)},$=S=>{T&&(S.stopPropagation(),j(e.name),g(!0),setTimeout(()=>{var w;return(w=v.current)==null?void 0:w.focus()},0))},O=()=>{const S=b.trim();S&&d(t,S),g(!1)},W=S=>{S.stopPropagation(),i(t)},B=S=>{S.stopPropagation(),s(t)},F=async S=>{S.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await l(t)},N=S=>{S.stopPropagation(),C(!k)};return a.jsxs("div",{children:[a.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:T?"pointer":"default",borderLeft:I?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:I?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:T?1:.5},onMouseEnter:S=>{T&&!I&&(S.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:S=>{I||(S.currentTarget.style.backgroundColor="transparent")},children:[T&&e.terminalIds.length>0&&a.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?"▼":"▶"}),a.jsxs("div",{style:{flex:1,minWidth:0},children:[h?a.jsx("input",{ref:v,value:b,onChange:S=>j(S.target.value),onBlur:O,onKeyDown:S=>{S.key==="Enter"&&O(),S.key==="Escape"&&g(!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"}}):a.jsx("div",{onDoubleClick:$,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:T?"Double-click to rename":e.name,children:e.name}),a.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",An(Math.floor(e.createdAt/1e3))]})]}),T?a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:B,style:{flexShrink:0},title:"Close tab",children:"×"}):a.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[a.jsx("button",{className:"pane-btn",onClick:W,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:F,title:"Delete tab",children:"×"})]})]}),T&&k&&p.length>0&&a.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(S=>a.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${S.connected}`,children:[a.jsx("span",{style:{fontFamily:"monospace"},children:S.id}),a.jsx("span",{style:{marginLeft:"8px",color:S.active?S.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:S.active?S.connected?"●":"◐":"○"}),S.active?a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:w=>{w.stopPropagation(),c(S.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):a.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[a.jsx("button",{className:"pane-btn",onClick:w=>{w.stopPropagation(),f(S.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:w=>{w.stopPropagation(),window.confirm(`Kill terminal "${S.id}"? This will destroy the tmux session.`)&&u(S.id)},title:"Kill session",children:"×"})]})]},S.id))})]})}function Xs({sessionId:t,active:e,createdAt:n}){const r=A(d=>d.addTerminal),s=A(d=>d.killServerSession),i=()=>{r("horizontal",t)},l=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${t}"? This will kill the tmux session.`)&&s(t)};return a.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:d=>{d.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent"},children:[a.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),a.jsxs("div",{style:{flex:1,minWidth:0},children:[a.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),a.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:An(n)})]}),a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:l,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function Zs(){const t=A(c=>c.sidebarOpen),e=A(c=>c.toggleSidebar),n=A(c=>c.fetchSessions),r=A(c=>t?c.serverSessions:[]),s=A(c=>t?c.tabs:[]),i=A(c=>c.terminalIds.length),l=A(c=>c.tabsLoading),d=new Set(s.flatMap(c=>c.terminalIds)),p=r.filter(c=>!d.has(c.sessionId));return o.useEffect(()=>{if(!t)return;n();let c=setInterval(n,5e3);const f=()=>{document.hidden?c&&(clearInterval(c),c=null):(n(),c||(c=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",f),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",f)}},[t,n]),o.useEffect(()=>{if(!t)return;const c=setTimeout(n,800);return()=>clearTimeout(c)},[i,t,n]),a.jsxs("div",{className:"session-sidebar",style:{width:t?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:t?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[a.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),a.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:"×"})]}),a.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),s.length===0?a.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):s.map(c=>a.jsx(Ys,{tabId:c.id},c.id))]}),!l&&p.length>0&&a.jsxs("div",{style:{marginTop:"16px"},children:[a.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=>a.jsx(Xs,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const On=jt.memo(()=>{const t=A(T=>T.tabs),e=A(T=>T.activeTabId),n=A(T=>T.addTab),r=A(T=>T.switchTab),s=A(T=>T.closeTab),i=A(T=>T.renameTab),[l,d]=o.useState(null),[p,c]=o.useState(""),f=o.useRef(null),u=t.filter(T=>T.status==="open");o.useEffect(()=>{l&&f.current&&(f.current.focus(),f.current.select())},[l]);const h=T=>{d(T.id),c(T.name)},g=()=>{l&&p.trim()&&i(l,p.trim()),d(null),c("")},b=()=>{d(null),c("")},j=T=>{T.key==="Enter"?g():T.key==="Escape"&&b()},k=T=>{l||r(T)},C=(T,L)=>{T.stopPropagation(),s(L)},v=(T,L)=>{T.button===1&&(T.preventDefault(),s(L))},I=u.length>1;return a.jsxs("div",{className:"tab-bar",children:[u.map(T=>{const L=T.id===e,$=l===T.id,O=T.terminalIds.length;return a.jsx("div",{className:`tab-item ${L?"tab-item--active":""}`,onClick:()=>k(T.id),onDoubleClick:()=>h(T),onMouseDown:W=>v(W,T.id),children:$?a.jsx("input",{ref:f,type:"text",value:p,onChange:W=>c(W.target.value),onBlur:g,onKeyDown:j,className:"tab-item__rename-input"}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"tab-item__name",children:[T.name," ",O>0&&`(${O})`]}),I&&a.jsx("button",{className:"tab-item__close",onClick:W=>C(W,T.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},T.id)}),a.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});On.displayName="TabBar";function Qs(){return localStorage.getItem("ai-cli-online-token")}function eo(){const t=A(f=>f.token),e=A(f=>f.setToken),n=A(f=>f.tabs),r=A(f=>f.addTab),s=A(f=>f.toggleSidebar),i=A(f=>f.fontSize),l=A(f=>f.setFontSize),d=A(f=>f.tabsLoading),p=A(f=>f.theme),c=A(f=>f.toggleTheme);return o.useEffect(()=>{const f=Qs();f&&!t&&e(f)},[]),o.useEffect(()=>{t&&!d&&n.filter(f=>f.status==="open").length===0&&r("Default")},[t,d]),t?a.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),a.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.3"]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[a.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−"}),a.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:i}),a.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+"})]}),a.jsx(no,{}),a.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"☀":"🌙"}),a.jsx("button",{className:"header-btn",onClick:s,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),a.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),a.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[a.jsx("main",{style:{flex:1,overflow:"hidden"},children:a.jsx(Vs,{})}),a.jsx(Zs,{})]}),a.jsx(On,{})]}):a.jsx(Pr,{})}const to=[1,2,3,4];function no(){const t=A(r=>r.latency);if(t===null)return a.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let e,n;return t<50?(e="var(--accent-green)",n=4):t<150?(e="var(--accent-yellow)",n=3):t<300?(e="var(--accent-orange)",n=2):(e="var(--accent-red)",n=1),a.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: ${t}ms`,children:[to.map(r=>a.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),a.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[t,"ms"]})]})}St.createRoot(document.getElementById("root")).render(a.jsx(jt.StrictMode,{children:a.jsx($n,{children:a.jsx(eo,{})})}));
|
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-D4ZKzY3K.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">
|