ai-cli-online 2.9.9 โ†’ 3.0.1

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.
@@ -0,0 +1,32 @@
1
+ var Tn=Object.defineProperty;var Cn=(e,t,n)=>t in e?Tn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wt=(e,t,n)=>Cn(e,typeof t!="symbol"?t+"":t,n);import{r as a,a as En,g as In,R as bt}from"./react-vendor-BCIvbQoU.js";import{D as Qt,o as en,L as jn,x as tn}from"./terminal-DnNpv9tw.js";import{p as ut,g as nn}from"./markdown-CU76q5qk.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const i of c.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(o){if(o.ep)return;o.ep=!0;const c=n(o);fetch(o.href,c)}})();var rn={exports:{}},et={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var Rn=a,Nn=Symbol.for("react.element"),Ln=Symbol.for("react.fragment"),Dn=Object.prototype.hasOwnProperty,Mn=Rn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,An={key:!0,ref:!0,__self:!0,__source:!0};function on(e,t,n){var r,o={},c=null,i=null;n!==void 0&&(c=""+n),t.key!==void 0&&(c=""+t.key),t.ref!==void 0&&(i=t.ref);for(r in t)Dn.call(t,r)&&!An.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:Nn,type:e,key:c,ref:i,props:o,_owner:Mn.current}}et.Fragment=Ln;et.jsx=on;et.jsxs=on;rn.exports=et;var s=rn.exports,ft={},St=En;ft.createRoot=St.createRoot,ft.hydrateRoot=St.hydrateRoot;const zn={},kt=e=>{let t;const n=new Set,r=(u,f)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const g=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(x=>x(t,g))}},o=()=>t,p={setState:r,getState:o,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{n.clear()}},l=t=e(r,o,p);return p},_n=e=>e?kt(e):kt;var sn={exports:{}},an={},cn={exports:{}},ln={};/**
10
+ * @license React
11
+ * use-sync-external-store-shim.production.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var je=a;function $n(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var On=typeof Object.is=="function"?Object.is:$n,Pn=je.useState,Fn=je.useEffect,Bn=je.useLayoutEffect,Un=je.useDebugValue;function Wn(e,t){var n=t(),r=Pn({inst:{value:n,getSnapshot:t}}),o=r[0].inst,c=r[1];return Bn(function(){o.value=n,o.getSnapshot=t,ct(o)&&c({inst:o})},[e,n,t]),Fn(function(){return ct(o)&&c({inst:o}),e(function(){ct(o)&&c({inst:o})})},[e]),Un(n),n}function ct(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!On(e,n)}catch{return!0}}function Hn(e,t){return t()}var Kn=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hn:Wn;ln.useSyncExternalStore=je.useSyncExternalStore!==void 0?je.useSyncExternalStore:Kn;cn.exports=ln;var Jn=cn.exports;/**
18
+ * @license React
19
+ * use-sync-external-store-shim/with-selector.production.js
20
+ *
21
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
22
+ *
23
+ * This source code is licensed under the MIT license found in the
24
+ * LICENSE file in the root directory of this source tree.
25
+ */var tt=a,Gn=Jn;function Vn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var qn=typeof Object.is=="function"?Object.is:Vn,Yn=Gn.useSyncExternalStore,Xn=tt.useRef,Zn=tt.useEffect,Qn=tt.useMemo,er=tt.useDebugValue;an.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var c=Xn(null);if(c.current===null){var i={hasValue:!1,value:null};c.current=i}else i=c.current;c=Qn(function(){function p(g){if(!l){if(l=!0,u=g,g=r(g),o!==void 0&&i.hasValue){var x=i.value;if(o(x,g))return f=x}return f=g}if(x=f,qn(u,g))return x;var R=r(g);return o!==void 0&&o(x,R)?(u=g,x):(u=g,f=R)}var l=!1,u,f,h=n===void 0?null:n;return[function(){return p(t())},h===null?void 0:function(){return p(h())}]},[t,n,r,o]);var d=Yn(e,c[0],c[1]);return Zn(function(){i.hasValue=!0,i.value=d},[d]),er(d),d};sn.exports=an;var tr=sn.exports;const nr=In(tr),dn={},{useDebugValue:rr}=bt,{useSyncExternalStoreWithSelector:or}=nr;let Tt=!1;const sr=e=>e;function ar(e,t=sr,n){(dn?"production":void 0)!=="production"&&n&&!Tt&&(Tt=!0);const r=or(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return rr(r),r}const Ct=e=>{const t=typeof e=="function"?_n(e):e,n=(r,o)=>ar(t,r,o);return Object.assign(n,t),n},cr=e=>e?Ct(e):Ct,xe="";function oe(e){return{Authorization:`Bearer ${e}`}}class Ae extends Error{constructor(t,n){super(n),this.status=t,this.name="ApiError"}}function Ce(e,t){return`${xe}/api/sessions/${encodeURIComponent(e)}/${t}`}function Et(e){return`${xe}/api/settings/${e}`}async function Ve(e){if(!e.ok){const t=await e.text().catch(()=>e.statusText);throw new Ae(e.status,t)}return e.json()}const ne={async get(e,t,n,r){const o=new URL(Ce(t,n),window.location.origin);if(r)for(const[i,d]of Object.entries(r))o.searchParams.set(i,d);const c=await fetch(o.toString(),{headers:oe(e)});return Ve(c)},async getOptional(e,t,n,r){const o=new URL(Ce(t,n),window.location.origin);if(r)for(const[i,d]of Object.entries(r))o.searchParams.set(i,d);const c=await fetch(o.toString(),{headers:oe(e)});return c.status===304?null:Ve(c)},async post(e,t,n,r){const o=await fetch(Ce(t,n),{method:"POST",headers:{...oe(e),"Content-Type":"application/json"},body:JSON.stringify(r)});return Ve(o)},async put(e,t,n,r){const o=await fetch(Ce(t,n),{method:"PUT",headers:{...oe(e),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const c=await o.text().catch(()=>o.statusText);throw new Ae(o.status,c)}},async del(e,t,n,r){const o=await fetch(Ce(t,n),{method:"DELETE",headers:{...oe(e),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!o.ok){const c=await o.text().catch(()=>o.statusText);throw new Ae(o.status,c)}},async getBlob(e,t,n,r){const o=new URL(Ce(t,n),window.location.origin);if(r)for(const[i,d]of Object.entries(r))o.searchParams.set(i,d);const c=await fetch(o.toString(),{headers:oe(e)});if(!c.ok)throw new Ae(c.status,"Download failed");return c}},nt={async get(e,t){const n=await fetch(Et(t),{headers:oe(e)});return Ve(n)},async put(e,t,n){const r=await fetch(Et(t),{method:"PUT",headers:{...oe(e),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.text().catch(()=>r.statusText);throw new Ae(r.status,o)}}};async function ir(e){try{return(await nt.get(e,"font-size")).fontSize}catch{return 14}}async function lr(e,t){try{await nt.put(e,"font-size",{fontSize:t})}catch{}}let We=null;const dr=(e,t)=>({fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),We&&clearTimeout(We),We=setTimeout(()=>{We=null;const o=t().token;o&&lr(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),theme:(()=>{try{const n=localStorage.getItem("ai-cli-online-theme");if(n==="light"||n==="dark")return n}catch{}return"dark"})(),setTheme:n=>{e({theme:n});try{localStorage.setItem("ai-cli-online-theme",n)}catch{}document.documentElement.setAttribute("data-theme",n)},toggleTheme:()=>{const n=t().theme==="dark"?"light":"dark";t().setTheme(n)},sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${xe}/api/sessions`,{headers:oe(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}}});function qe(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let i=0;i<e.children.length;i++){const d=qe(e.children[i],t);d!==null&&(n.push(d),r.push(e.sizes[i]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((i,d)=>i+d,0),c=r.map(i=>i/o*100);return{...e,children:n,sizes:c}}function un(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(c=>un(c,t,n,r,o))}}function fn(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>fn(r,t,n))}}function it(e){return e.tabs.find(t=>t.id===e.activeTabId)}function pe(e,t,n){return e.map(r=>r.id===t?n(r):r)}function It(e,t){const n=e.tabs.find(l=>l.terminalIds.includes(t));if(!n){const{[t]:l,...u}=e.terminalsMap;return{terminalsMap:u}}const r=n.terminalIds.filter(l=>l!==t),o=n.layout?qe(n.layout,t):null,c=pe(e.tabs,n.id,l=>({...l,terminalIds:r,layout:o})),{[t]:i,...d}=e.terminalsMap,p={terminalsMap:d,tabs:c};return n.id===e.activeTabId&&(p.terminalIds=r,p.layout=o),p}async function ur(e){try{return(await nt.get(e,"tabs-layout")).layout}catch{return null}}async function fr(e,t){try{await nt.put(e,"tabs-layout",{layout:t})}catch{}}function jt(e,t){try{const n=`${xe}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const pt="ai-cli-online-tabs",Rt="ai-cli-online-layout",Nt="ai-cli-online-session-names";let ie=null;function pr(e){ie=e,yr()}let He=null,we=null,ze=null;function mr(e){ze=e,we&&clearTimeout(we),we=setTimeout(()=>{we=null,ze=null;const t=ie==null?void 0:ie.getState().token;t&&fr(t,e)},2e3)}function te(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(pt,JSON.stringify(t))}catch{}mr(t)}function hr(e){He&&clearTimeout(He),He=setTimeout(()=>{He=null,te(e)},500)}function ee(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function gr(){try{const e=localStorage.getItem(pt);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(Rt);if(e){const t=JSON.parse(e);let n="Default";try{const c=localStorage.getItem(Nt);if(c){const i=JSON.parse(c),d=Object.values(i)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(pt,JSON.stringify(o))}catch{}return localStorage.removeItem(Rt),localStorage.removeItem(Nt),o}}catch{}return null}function br(e,t){const n=new Set(t.map(i=>i.sessionId)),r=[];for(const i of e.tabs){if(i.status!=="open"){const l=i.terminalIds.filter(u=>n.has(u));if(l.length>0){let u=i.layout;for(const f of i.terminalIds)!n.has(f)&&u&&(u=qe(u,f));r.push({...i,terminalIds:l,layout:u})}continue}const d=i.terminalIds.filter(l=>n.has(l));if(d.length===0)continue;let p=i.layout;for(const l of i.terminalIds)!n.has(l)&&p&&(p=qe(p,l));r.push({...i,terminalIds:d,layout:p})}if(r.filter(i=>i.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(i=>i.id===o&&i.status==="open")){const i=r.find(d=>d.status==="open");o=(i==null?void 0:i.id)||""}return{...e,activeTabId:o,tabs:r}}async function xr(e,t){var o,c;if(!ie)return;const{setState:n,getState:r}=ie;try{const[i,d]=await Promise.all([ur(e),fetch(`${xe}/api/sessions`,{headers:oe(e)}).then(x=>x.ok?x.json():[]).catch(()=>[])]);if(r().token!==e)return;const p=i&&((o=i.tabs)==null?void 0:o.length)>0?i:t;if(!p||p.tabs.length===0){n({tabsLoading:!1});return}const l=br(p,d);if(!l){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:p.nextId,nextSplitId:p.nextSplitId,nextTabId:p.nextTabId,terminalIds:[],layout:null});return}const u=r().terminalsMap,f={};for(const x of l.tabs)if(x.status==="open")for(const R of x.terminalIds)f[R]=u[R]||{id:R,connected:!1,sessionResumed:!1,error:null,panels:((c=x.panelStates)==null?void 0:c[R])||{chatOpen:!1,planOpen:!1}};const h=l.tabs.find(x=>x.id===l.activeTabId&&x.status==="open")||l.tabs.find(x=>x.status==="open"),g=(h==null?void 0:h.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:l.tabs,activeTabId:g,nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:(h==null?void 0:h.terminalIds)||[],layout:(h==null?void 0:h.layout)||null}),te(ee(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function yr(){typeof window>"u"||!ie||window.addEventListener("beforeunload",()=>{const e=ie==null?void 0:ie.getState().token;if(e)if(ze)we&&(clearTimeout(we),we=null),jt(e,ze),ze=null;else{const t=ie.getState();t.tabs.length>0&&jt(e,ee(t))}})}const _=cr((...e)=>{const[t,n]=e;return{...dr(...e),token:null,tabsLoading:!1,setToken:r=>{var o;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}ir(r).then(i=>{n().token===r&&t({fontSize:i})});const c=gr();if(c&&c.tabs.length>0){const i={};for(const l of c.tabs)if(l.status==="open")for(const u of l.terminalIds)i[u]={id:u,connected:!1,sessionResumed:!1,error:null,panels:((o=l.panelStates)==null?void 0:o[u])||{chatOpen:!1,planOpen:!1}};const d=c.tabs.find(l=>l.id===c.activeTabId&&l.status==="open")||c.tabs.find(l=>l.status==="open"),p=(d==null?void 0:d.id)||"";t({token:r,tabsLoading:!0,terminalsMap:i,tabs:c.tabs,activeTabId:p,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(d==null?void 0:d.terminalIds)||[],layout:(d==null?void 0:d.layout)||null})}else t({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});xr(r,c);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),t({token:r,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:r=>{const o=n(),c=`tab${o.nextTabId}`,i=`t${o.nextId}`,d={id:i,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},p={type:"leaf",terminalId:i},l={id:c,name:r||`Tab ${o.nextTabId}`,status:"open",terminalIds:[i],layout:p,createdAt:Date.now()};return t({tabs:[...o.tabs,l],activeTabId:c,nextTabId:o.nextTabId+1,nextId:o.nextId+1,terminalsMap:{...o.terminalsMap,[i]:d},terminalIds:l.terminalIds,layout:l.layout}),te(ee(n())),c},switchTab:r=>{const c=n().tabs.find(i=>i.id===r);!c||c.status!=="open"||(t({activeTabId:r,terminalIds:c.terminalIds,layout:c.layout}),te(ee(n())))},closeTab:r=>{const o=n(),c=o.tabs.find(h=>h.id===r);if(!c||c.status!=="open"||o.tabs.filter(h=>h.status==="open").length<=1)return;const d={...o.terminalsMap};for(const h of c.terminalIds)delete d[h];const p=pe(o.tabs,r,h=>({...h,status:"closed"}));let l=o.activeTabId,u=o.terminalIds,f=o.layout;if(o.activeTabId===r){const h=o.tabs.findIndex(R=>R.id===r),g=p.filter(R=>R.status==="open"),x=g.find(R=>p.findIndex(j=>j.id===R.id)>h)||g[g.length-1];x&&(l=x.id,u=x.terminalIds,f=x.layout)}t({tabs:p,activeTabId:l,terminalsMap:d,terminalIds:u,layout:f}),te(ee(n()))},reopenTab:r=>{var p;const o=n(),c=o.tabs.find(l=>l.id===r);if(!c||c.status!=="closed")return;const i={...o.terminalsMap};for(const l of c.terminalIds)i[l]={id:l,connected:!1,sessionResumed:!1,error:null,panels:((p=c.panelStates)==null?void 0:p[l])||{chatOpen:!1,planOpen:!1}};const d=pe(o.tabs,r,l=>({...l,status:"open"}));t({tabs:d,activeTabId:r,terminalsMap:i,terminalIds:c.terminalIds,layout:c.layout}),te(ee(n()))},deleteTab:async r=>{const o=n(),c=o.tabs.find(x=>x.id===r);if(!c)return;const i=o.token;i&&await Promise.all(c.terminalIds.map(x=>fetch(`${xe}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:oe(i)}).catch(()=>{})));const d=n(),p=d.tabs.find(x=>x.id===r);if(!p)return;const l={...d.terminalsMap};for(const x of p.terminalIds)delete l[x];const u=d.tabs.filter(x=>x.id!==r);let f=d.activeTabId,h=d.terminalIds,g=d.layout;if(d.activeTabId===r){const x=u.find(R=>R.status==="open");x?(f=x.id,h=x.terminalIds,g=x.layout):(f="",h=[],g=null)}t({tabs:u,activeTabId:f,terminalsMap:l,terminalIds:h,layout:g}),te(ee(n())),setTimeout(()=>n().fetchSessions(),500)},renameTab:(r,o)=>{const c=pe(n().tabs,r,i=>({...i,name:o}));t({tabs:c}),te(ee(n()))},addTerminal:(r,o)=>{const c=n();if(o&&c.terminalsMap[o])return o;const i=it(c);if(!i){const P=`tab${c.nextTabId}`,B=o||`t${c.nextId}`;let $=c.nextId;const F=B.match(/^t(\d+)$/);F&&($=Math.max($,parseInt(F[1],10)+1));const O=o?$:$+1,D={id:B,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},T={type:"leaf",terminalId:B},y={id:P,name:`Tab ${c.nextTabId}`,status:"open",terminalIds:[B],layout:T,createdAt:Date.now()};return t({tabs:[...c.tabs,y],activeTabId:P,nextTabId:c.nextTabId+1,nextId:O,terminalsMap:{...c.terminalsMap,[B]:D},terminalIds:[B],layout:T}),te(ee(n())),B}const{nextId:d,nextSplitId:p,terminalsMap:l}=c,{terminalIds:u,layout:f}=i,h=o||`t${d}`;let g=d;const x=h.match(/^t(\d+)$/);x&&(g=Math.max(g,parseInt(x[1],10)+1));const R={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},C={type:"leaf",terminalId:h};let j,S=p;if(!f)j=C;else if(f.type==="leaf"){const P=r||"horizontal";j={id:`s${S}`,type:"split",direction:P,children:[f,C],sizes:[50,50]},S++}else if(f.direction===(r||"horizontal")){const B=100/(f.children.length+1),$=(100-B)/100,F=[...f.sizes.map(O=>O*$),B];j={...f,children:[...f.children,C],sizes:F}}else{const P=r||"horizontal";j={id:`s${S}`,type:"split",direction:P,children:[f,C],sizes:[50,50]},S++}const w=[...u,h],k=o?g:g+1,A=pe(c.tabs,i.id,P=>({...P,terminalIds:w,layout:j}));return t({terminalsMap:{...l,[h]:R},terminalIds:w,layout:j,tabs:A,nextId:k,nextSplitId:S}),te(ee(n())),h},splitTerminal:(r,o,c)=>{const i=n(),d=it(i);if(!d||!d.layout)return"";const{nextId:p,nextSplitId:l,terminalsMap:u}=i,f=`t${p}`,h={id:f,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1},...c?{startCwd:c}:{}},g={type:"leaf",terminalId:f},x=`s${l}`,R=un(d.layout,r,o,g,x),C=[...d.terminalIds,f],j=p+1,S=l+1,w=pe(i.tabs,d.id,k=>({...k,terminalIds:C,layout:R}));return t({terminalsMap:{...u,[f]:h},terminalIds:C,layout:R,tabs:w,nextId:j,nextSplitId:S}),te(ee(n())),f},removeTerminal:r=>{const o=It(n(),r);o&&(t(o),te(ee(n())))},disconnectTerminal:r=>{const o=n();if(!o.terminalsMap[r])return;const{[r]:i,...d}=o.terminalsMap;t({terminalsMap:d})},reconnectTerminal:r=>{var p;const o=n();if(o.terminalsMap[r])return;const c=o.tabs.find(l=>l.terminalIds.includes(r)),i=((p=c==null?void 0:c.panelStates)==null?void 0:p[r])||{chatOpen:!1,planOpen:!1},d={id:r,connected:!1,sessionResumed:!1,error:null,panels:i};t({terminalsMap:{...o.terminalsMap,[r]:d}})},setTerminalConnected:(r,o)=>{t(c=>{const i=c.terminalsMap[r];return!i||i.connected===o?c:{terminalsMap:{...c.terminalsMap,[r]:{...i,connected:o}}}})},setTerminalResumed:(r,o)=>{t(c=>{const i=c.terminalsMap[r];return!i||i.sessionResumed===o?c:{terminalsMap:{...c.terminalsMap,[r]:{...i,sessionResumed:o}}}})},setTerminalError:(r,o)=>{t(c=>{const i=c.terminalsMap[r];return!i||i.error===o?c:{terminalsMap:{...c.terminalsMap,[r]:{...i,error:o}}}})},toggleChat:r=>{const o=n(),c=o.terminalsMap[r];if(!c)return;const i={...c.panels,chatOpen:!c.panels.chatOpen},d={...o.terminalsMap,[r]:{...c,panels:i}},p=o.tabs.find(u=>u.terminalIds.includes(r));let l=o.tabs;if(p){const u={...p.panelStates,[r]:i};l=pe(o.tabs,p.id,f=>({...f,panelStates:u}))}t({terminalsMap:d,tabs:l}),te(ee(n()))},togglePlan:r=>{const o=n(),c=o.terminalsMap[r];if(!c)return;const i={...c.panels,planOpen:!c.panels.planOpen},d={...o.terminalsMap,[r]:{...c,panels:i}},p=o.tabs.find(u=>u.terminalIds.includes(r));let l=o.tabs;if(p){const u={...p.panelStates,[r]:i};l=pe(o.tabs,p.id,f=>({...f,panelStates:u}))}t({terminalsMap:d,tabs:l}),te(ee(n()))},setSplitSizes:(r,o)=>{const c=n(),i=it(c);if(!i||!i.layout)return;const d=fn(i.layout,r,o),p=pe(c.tabs,i.id,l=>({...l,layout:d}));t({layout:d,tabs:p}),hr(ee(n()))},killServerSession:async r=>{const o=n().token;if(!o)return;try{await fetch(`${xe}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:oe(o)})}catch{}const c=It(n(),r);c&&(t(c),te(ee(n()))),setTimeout(()=>n().fetchSessions(),500)}}});pr(_);typeof document<"u"&&document.documentElement.setAttribute("data-theme",_.getState().theme);function vr(){const[e,t]=a.useState(""),n=_(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, var(--bg-primary) 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"var(--bg-tertiary)",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid var(--border)"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"var(--bg-primary)",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"var(--accent-blue)",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"var(--bg-primary)",color:"var(--text-bright)",border:"1px solid var(--border)",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:e.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const rt=new Map;function wr(e,t,n){rt.set(e,{onChunk:t,onControl:n})}function Sr(e){rt.delete(e)}function kr(e,t){var n;(n=rt.get(e))==null||n.onChunk(t)}function Tr(e,t){var n;(n=rt.get(e))==null||n.onControl(t)}const Cr=1,Lt=2,Er=3,Ir=4,jr=5,Rr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,Ke=500,Nr=8e3,Lr=1e4,Dt=4e3,Dr=5e3,Mr=10,Ar=64*1024,zr=new TextDecoder,_r=new TextEncoder;function Mt(e,t){const n=_r.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function $r(e,t,n){const r=a.useRef(null),o=a.useRef(Ke),c=a.useRef(null),i=a.useRef(null),d=a.useRef(null),p=a.useRef(null),l=a.useRef(!1),u=a.useRef(n),f=a.useRef(!1),h=a.useRef(0),g=a.useRef(!0),x=a.useRef(!navigator.onLine),R=a.useRef(""),C=a.useRef(null),j=a.useRef("");u.current=n;const S=a.useCallback(()=>{i.current&&(clearInterval(i.current),i.current=null),d.current&&(clearTimeout(d.current),d.current=null),c.current&&(clearTimeout(c.current),c.current=null),p.current&&(clearTimeout(p.current),p.current=null),C.current&&(clearTimeout(C.current),C.current=null)},[]),w=a.useCallback(()=>{var W;const{token:F,setTerminalError:O}=_.getState();if(!F||l.current)return;if(r.current){const U=r.current.readyState;if(U===WebSocket.OPEN||U===WebSocket.CONNECTING)return}f.current=!1;const D=(W=_.getState().terminalsMap[t])==null?void 0:W.startCwd;let T=`${Rr}?sessionId=${encodeURIComponent(t)}`;D&&(T+=`&cwd=${encodeURIComponent(D)}`);const y=new WebSocket(T);y.binaryType="arraybuffer",p.current=window.setTimeout(()=>{y.readyState===WebSocket.CONNECTING&&y.close()},Dr);const G=()=>{y.readyState===WebSocket.OPEN&&(h.current=performance.now(),y.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,y.close())},Dt))};y.onopen=()=>{p.current&&(clearTimeout(p.current),p.current=null),y.send(JSON.stringify({type:"auth",token:F})),O(t,null),o.current=Ke,g.current=!0},y.onclose=U=>{const{setTerminalConnected:V,setTerminalError:z,setToken:L}=_.getState();if(V(t,!1),S(),f.current)return;if(U.code===4001){l.current=!0,z(t,"Authentication failed"),L(null),localStorage.removeItem("ai-cli-online-token");return}if(U.code===4002)return;if(U.code===4005){z(t,"Connection limit reached");return}if(!navigator.onLine){x.current=!0;return}if(g.current){g.current=!1,c.current=window.setTimeout(()=>w(),50);return}const M=o.current;o.current=Math.min(M*2,Nr);const H=Math.round(M*(.5+Math.random()));c.current=window.setTimeout(()=>{w()},H)},y.onerror=()=>{},y.onmessage=U=>{var V;try{const z=e.current;if(U.data instanceof ArrayBuffer){const M=new Uint8Array(U.data);if(M.length<1)return;const H=M[0],X=M.subarray(1);switch(H){case Cr:z==null||z.write(X);break;case Er:z==null||z.write(X);break;case Ir:{(V=u.current)==null||V.call(u,zr.decode(X));break}case jr:{kr(t,X);break}}return}const L=JSON.parse(U.data);switch(L.type){case"connected":{const M=_.getState();M.setTerminalConnected(t,!0),M.setTerminalResumed(t,L.resumed);const H=e.current;H&&y.readyState===WebSocket.OPEN&&y.send(JSON.stringify({type:"resize",cols:H.cols,rows:H.rows})),j.current&&(y.send(Mt(Lt,j.current)),j.current=""),G(),i.current=window.setInterval(G,Lr);break}case"error":_.getState().setTerminalError(t,L.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),h.current>0){const M=Math.round(performance.now()-h.current),H=_.getState();(H.terminalIds.length===0||H.terminalIds[0]===t)&&H.setLatency(M),h.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Tr(t,L);break}}catch{}},r.current=y},[t,e,S]),k=a.useCallback(F=>{const O=r.current;if(!O||O.readyState!==WebSocket.OPEN){j.current.length<Ar&&(j.current+=F);return}R.current+=F,C.current||(C.current=window.setTimeout(()=>{const D=R.current;R.current="",C.current=null,D&&O.readyState===WebSocket.OPEN&&O.send(Mt(Lt,D))},Mr))},[]),A=a.useCallback((F,O)=>{var D;((D=r.current)==null?void 0:D.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:F,rows:O}))},[]),P=a.useCallback(()=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),B=a.useCallback(F=>{var O;((O=r.current)==null?void 0:O.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:F}))},[]),$=a.useCallback(()=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return a.useEffect(()=>{_.getState().token&&(l.current=!1,w());const O=()=>{x.current=!1,o.current=Ke,g.current=!0;const y=r.current;(!y||y.readyState===WebSocket.CLOSED||y.readyState===WebSocket.CLOSING)&&w()},D=()=>{x.current=!0},T=()=>{if(document.visibilityState!=="visible")return;const y=r.current;if(!y||y.readyState!==WebSocket.OPEN){!x.current&&!f.current&&(o.current=Ke,g.current=!0,w());return}h.current=performance.now(),y.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,y.close())},Dt)};return window.addEventListener("online",O),window.addEventListener("offline",D),document.addEventListener("visibilitychange",T),()=>{f.current=!0,S(),window.removeEventListener("online",O),window.removeEventListener("offline",D),document.removeEventListener("visibilitychange",T),r.current&&(r.current.close(),r.current=null)}},[w,S,t]),{sendInput:k,sendResize:A,requestScrollback:P,requestFileStream:B,cancelFileStream:$}}function Or(e){const t=a.useRef(null),n=a.useRef(null),r=a.useRef(e);r.current=e;const o=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null),t.current&&(t.current.remove(),t.current=null)},[]),c=a.useCallback((i,d)=>{o();const p=document.createElement("div");p.style.cssText=`position:fixed;left:${i}px;top:${d}px;z-index:1000;display:flex;align-items:center;gap:4px;padding:4px 6px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.4);font-family:inherit;`;const l=document.createElement("textarea");l.style.cssText="width:90px;height:22px;resize:none;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-size:11px;font-family:inherit;padding:2px 4px;outline:none;",l.placeholder="Ctrl+V",l.addEventListener("paste",u=>{var h;u.preventDefault();const f=(h=u.clipboardData)==null?void 0:h.getData("text/plain");f&&r.current(f),o()}),l.addEventListener("keydown",u=>{u.key==="Escape"&&o()}),p.appendChild(l),document.body.appendChild(p),t.current=p,requestAnimationFrame(()=>{const u=p.getBoundingClientRect();u.right>window.innerWidth&&(p.style.left=`${window.innerWidth-u.width-8}px`),u.bottom>window.innerHeight&&(p.style.top=`${window.innerHeight-u.height-8}px`),l.focus()}),n.current=setTimeout(o,8e3)},[o]);return a.useEffect(()=>{const i=()=>{t.current&&o()};return document.addEventListener("click",i),()=>{document.removeEventListener("click",i),o()}},[o]),{showPasteFloat:c,removePasteFloat:o}}const Ye={background:"#000000",foreground:"#cccccc",cursor:"#aeafad",selectionBackground:"rgba(38, 79, 120, 0.5)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5"},Xe={background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"rgba(9, 105, 218, 0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#2da44e",brightYellow:"#bf8803",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"},pn="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",Pr=a.forwardRef(function({sessionId:t},n){const r=a.useRef(null),o=a.useRef(null),c=a.useRef(null),[i,d]=a.useState(!1),[p,l]=a.useState(""),u=_(A=>A.fontSize),f=_(A=>A.theme),h=a.useCallback(A=>{l(A),d(!0)},[]),{sendInput:g,sendResize:x,requestScrollback:R,requestFileStream:C,cancelFileStream:j}=$r(o,t,h);a.useImperativeHandle(n,()=>({sendInput:g,requestFileStream:C,cancelFileStream:j}),[g,C,j]);const S=a.useRef(g),w=a.useRef(x);S.current=g,w.current=x;const{removePasteFloat:k}=Or(A=>S.current(A));return a.useEffect(()=>{if(!r.current)return;let A=!1,P=null,B=null,$=null,F=null;if(A||!r.current)return;const O=new Qt({cursorBlink:!0,scrollback:1e4,fontSize:_.getState().fontSize,fontFamily:pn,theme:_.getState().theme==="dark"?Ye:Xe,allowProposedApi:!0}),D=new en;O.loadAddon(D),O.loadAddon(new jn((L,M)=>{window.open(M,"_blank","noopener,noreferrer")})),O.open(r.current);try{const L=new tn;L.onContextLoss(()=>{L.dispose()}),O.loadAddon(L)}catch{}o.current=O,c.current=D,O.onSelectionChange(()=>{const L=O.getSelection();L&&navigator.clipboard.writeText(L).catch(()=>{})});const T=O.element,y=L=>{var M;L.preventDefault(),k(),(M=navigator.clipboard)!=null&&M.readText&&navigator.clipboard.readText().then(H=>{H&&S.current(H)}).catch(()=>{})};T&&T.addEventListener("contextmenu",y);const G=()=>{try{const L=r.current;if(L&&L.clientWidth>0&&L.clientHeight>0)return D.fit(),w.current(O.cols,O.rows),!0}catch{}return!1};requestAnimationFrame(()=>G());let W=0;P=setInterval(()=>{W++,(G()||W>=10)&&(clearInterval(P),P=null)},100),document.fonts.ready.then(()=>{if(!A)try{D.fit(),w.current(O.cols,O.rows)}catch{}});let U=null;const V=()=>{A||(U&&clearTimeout(U),U=setTimeout(()=>{if(!A)try{D.fit(),w.current(O.cols,O.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",V),O.onData(L=>{S.current(L)});let z=!1;return F=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!z){z=!0;const M=()=>{document.removeEventListener("mouseup",M),z=!1,requestAnimationFrame(()=>{try{D.fit(),w.current(O.cols,O.rows)}catch{}})};document.addEventListener("mouseup",M)}return}B||(B=requestAnimationFrame(()=>{B=null;try{D.fit(),$&&clearTimeout($),$=setTimeout(()=>{$=null,w.current(O.cols,O.rows)},50)}catch{}}))}),F.observe(r.current),()=>{A=!0,P&&clearInterval(P),B&&cancelAnimationFrame(B),$&&clearTimeout($),U&&clearTimeout(U),document.fonts.removeEventListener("loadingdone",V),F&&F.disconnect(),k(),T&&T.removeEventListener("contextmenu",y),o.current&&(o.current.dispose(),o.current=null),c.current=null}},[t]),a.useEffect(()=>{const A=o.current,P=c.current;if(!(!A||!P)&&A.options.fontSize!==u){A.options.fontSize=u;try{P.fit()}catch{}w.current(A.cols,A.rows)}},[u]),a.useEffect(()=>{o.current&&(o.current.options.theme=f==="dark"?Ye:Xe)},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:A=>{A.currentTarget.blur(),i?(d(!1),l("")):R()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:i?"var(--accent-blue)":"var(--bg-hover)",color:"var(--text-bright)",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:A=>{A.currentTarget.style.opacity="1"},onMouseLeave:A=>{A.currentTarget.style.opacity="0.8"},children:i?"โœ•":s.jsx("span",{style:{fontSize:14},children:"๐Ÿ‘"})}),i&&s.jsx(Fr,{data:p,onClose:()=>{d(!1),l("")}})]})});function Fr({data:e,onClose:t}){const n=a.useRef(null),r=a.useRef(t);r.current=t;const o=_(l=>l.fontSize),c=_(l=>l.theme),i=a.useRef(null),d=a.useRef(null);a.useEffect(()=>{if(!n.current)return;const l=new Qt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:pn,theme:c==="dark"?Ye:Xe});i.current=l;const u=new en;d.current=u,l.loadAddon(u),l.open(n.current);let f=null;try{f=new tn,f.onContextLoss(()=>{f==null||f.dispose(),f=null}),l.loadAddon(f)}catch{f=null}l.onSelectionChange(()=>{const j=l.getSelection();j&&navigator.clipboard.writeText(j).catch(()=>{})}),l.attachCustomKeyEventHandler(j=>(j.key==="Escape"&&r.current(),!1)),l.write(e);let h=null;const g=()=>{const j=n.current;if(!j||j.clientWidth<=0||j.clientHeight<=0)return!1;try{return u.fit(),l.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!g()){let j=0;h=setInterval(()=>{j++,(g()||j>=30)&&(clearInterval(h),h=null)},50)}});let x=null;const R=new ResizeObserver(()=>{x||(x=requestAnimationFrame(()=>{x=null,g()}))});R.observe(n.current);const C=j=>{j.key==="Escape"&&r.current()};return document.addEventListener("keydown",C),()=>{if(h&&clearInterval(h),x&&cancelAnimationFrame(x),document.removeEventListener("keydown",C),R.disconnect(),f){try{f.dispose()}catch{}f=null}l.dispose(),i.current=null,d.current=null}},[e]),a.useEffect(()=>{var l;if(i.current){i.current.options.fontSize=o;try{(l=d.current)==null||l.fit()}catch{}}},[o]),a.useEffect(()=>{i.current&&(i.current.options.theme=c==="dark"?Ye:Xe)},[c]);const p=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[s.jsx("div",{style:{height:p,boxSizing:"border-box",padding:"0 12px",background:"var(--bg-tertiary)",color:"var(--accent-blue)",fontSize:12,borderBottom:"1px solid var(--scrollbar-thumb-hover)",display:"flex",alignItems:"center"},children:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{position:"absolute",top:p,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const Br=50;function mt(){const e=a.useRef([]),t=a.useCallback(o=>{e.current.push(o),e.current.length>Br&&e.current.shift()},[]),n=a.useCallback(()=>e.current.pop(),[]),r=a.useCallback(()=>{e.current=[]},[]);return a.useMemo(()=>({pushUndo:t,popUndo:n,clearUndo:r}),[t,n,r])}function ht(e,t,n){e.preventDefault();const r=e.currentTarget,o=r.selectionStart,c=r.selectionEnd,i=r.value;n==null||n(i);const d=i.slice(0,o)+" "+i.slice(c);t(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function Ze(e,t=20){var n;return Math.min(t,Math.max(1,(((n=e.match(/\n/g))==null?void 0:n.length)??0)+1))}let Ee=null,mn="dark";const Ur=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],Wr={primaryColor:"#7aa2f7",primaryTextColor:"#c0caf5",primaryBorderColor:"#414868",lineColor:"#565f89",secondaryColor:"#bb9af7",tertiaryColor:"#24283b",background:"#1a1b26",mainBkg:"#24283b",nodeBorder:"#414868",clusterBkg:"#1e2030",titleColor:"#c0caf5",edgeLabelBackground:"#1e2030",gridColor:"#292e42",doneTaskBkgColor:"#9ece6a",doneTaskBorderColor:"#73a942",activeTaskBkgColor:"#7aa2f7",activeTaskBorderColor:"#5d87d6",critBkgColor:"#f7768e",critBorderColor:"#d35d72",taskBkgColor:"#414868",taskBorderColor:"#565f89",taskTextColor:"#c0caf5",taskTextDarkColor:"#1a1b26",sectionBkgColor:"#1e2030",sectionBkgColor2:"#24283b",altSectionBkgColor:"#1e2030",todayLineColor:"#e0af68"},Hr={primaryColor:"#2e59a8",primaryTextColor:"#343b58",primaryBorderColor:"#9aa5ce",lineColor:"#8c8fa1",secondaryColor:"#7847bd",tertiaryColor:"#d5d6db",background:"#f5f5f5",mainBkg:"#e8e8ed",nodeBorder:"#9aa5ce",clusterBkg:"#ebebf0",titleColor:"#343b58",edgeLabelBackground:"#ebebf0",gridColor:"#d5d6db",doneTaskBkgColor:"#4e8a2f",doneTaskBorderColor:"#3d6e25",activeTaskBkgColor:"#2e59a8",activeTaskBorderColor:"#24478a",critBkgColor:"#c4384b",critBorderColor:"#a02e3e",taskBkgColor:"#c0c1c9",taskBorderColor:"#9aa5ce",taskTextColor:"#343b58",taskTextDarkColor:"#f5f5f5",sectionBkgColor:"#e8e8ed",sectionBkgColor2:"#d5d6db",altSectionBkgColor:"#e8e8ed",todayLineColor:"#b68d28"},Kr={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function At(e,t){return mn=t,e.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:t==="dark"?Wr:Hr,gantt:Kr}),e}function Jr(e="dark"){return Ee?mn!==e?Ee.then(t=>At(t,e)):Ee:(Ee=(async()=>{for(const t of Ur)try{const n=await import(t);return At(n.default,e)}catch{}throw Ee=null,new Error("All mermaid CDN sources failed")})(),Ee)}let zt=0;function Gr(e,t,n="dark"){const r=a.useRef(n);a.useEffect(()=>{const o=e.current;if(!o)return;const c=r.current!==n;r.current=n;const i=o.querySelectorAll("code.language-mermaid, code.language-gantt"),d=c?o.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(i.length===0&&d.length===0)return;let p=!1;return(async()=>{let l;try{l=await Jr(n)}catch{if(p)return;for(const f of i){const h=f.parentElement;if(!h||h.tagName!=="PRE")continue;h.classList.add("mermaid-error");const g=document.createElement("div");g.className="mermaid-error__msg",g.textContent="Failed to load Mermaid library",h.appendChild(g)}return}if(!p){for(const u of d){if(p)break;const f=u.getAttribute("data-mermaid-source");if(!f)continue;const h=`mermaid-${++zt}`;try{const{svg:g}=await l.render(h,f);if(p)break;u.innerHTML=ut.sanitize(g,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const u of i){if(p)break;const f=u.parentElement;if(!f||f.tagName!=="PRE")continue;const h=u.textContent||"";if(!h.trim())continue;const g=`mermaid-${++zt}`;try{const{svg:x}=await l.render(g,h);if(p)break;const R=document.createElement("div");R.className="mermaid-diagram",R.setAttribute("data-mermaid-source",h),R.innerHTML=ut.sanitize(x,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),f.replaceWith(R)}catch{if(p)break;f.classList.add("mermaid-error");const x=document.createElement("div");x.className="mermaid-error__msg",x.textContent="Mermaid syntax error",f.appendChild(x)}}}})(),()=>{p=!0}},[t,n])}async function Vr(e,t,n){const r=await ne.get(e,t,"annotations",{path:n});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function hn(e,t,n,r,o){await ne.put(e,t,"annotations",{path:n,content:r,updatedAt:o})}async function _t(e,t,n,r){return ne.post(e,t,"task-annotations",{modulePath:n,content:r})}const gt={additions:[],deletions:[],replacements:[],comments:[]};let qr=0;function ce(){return`ann_${++qr}_${Date.now()}`}function _e(e,t){return`plan-annotations-${e}-${t}`}function $t(e,t){return`plan-scroll-${e}-${t}`}function Yr(e){const t=String(nn.parser([e],{async:!1}));return ut.sanitize(t,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function Je(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++){const o=e[r].raw??"";for(const c of o)c===`
26
+ `&&n++}return n}function Ge(e,t,n,r){const o=e.join(`
27
+ `);let c=0;for(let g=0;g<t-1&&g<e.length;g++)c+=e[g].length+1;let i=0;for(let g=0;g<n&&g<e.length;g++)i+=e[g].length+1;let d=c,p=Math.min(o.length,i);if(r){const g=Math.max(0,c-10),x=Math.min(o.length,i+10),C=o.slice(g,x).indexOf(r);C>=0&&(d=g+C,p=d+r.length)}const l=Math.max(0,d-20),u=o.slice(l,d).replace(/\n/g,"โ†ต"),f=Math.min(o.length,p+20),h=o.slice(p,f).replace(/\n/g,"โ†ต");return{before:u,after:h}}function Ot(e,t){const n=[],r=[],o=[],c=[];for(const i of e.additions){const{before:d,after:p}=Ge(t,i.sourceLine,i.sourceLine);n.push([`Line${i.sourceLine}:...${d}`,i.content,`${p}...`])}for(const i of e.deletions){const{before:d,after:p}=Ge(t,i.startLine,i.endLine,i.selectedText);r.push([`Line${i.startLine}:...${d}`,i.selectedText,`${p}...`])}for(const i of e.replacements){const{before:d,after:p}=Ge(t,i.startLine,i.endLine,i.selectedText);o.push([`Line${i.startLine}:...${d}`,i.selectedText,i.content,`${p}...`])}for(const i of e.comments){const{before:d,after:p}=Ge(t,i.startLine,i.endLine,i.selectedText);c.push([`Line${i.startLine}:...${d}`,i.selectedText,i.content,`${p}...`])}return{"Insert Annotations":n,"Delete Annotations":r,"Replace Annotations":o,"Comment Annotations":c}}function Pt(e){return e.additions.length>0||e.deletions.length>0||e.replacements.length>0||e.comments.length>0}function Ft(e){return/^[a-zA-Z0-9_./:@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function Bt(e,t){return`/ai-cli-task plan ${Ft(e)} ${Ft(t)} --silent`}function Ut(e){const t=e.split("/"),n=t.indexOf("AiTasks");return n>=0&&n+1<t.length?t.slice(0,n+2).join("/"):e.substring(0,e.lastIndexOf("/"))}function Qe(e){const t=new Set;return e.additions.forEach(n=>t.add(n.id)),e.deletions.forEach(n=>t.add(n.id)),e.replacements.forEach(n=>t.add(n.id)),e.comments.forEach(n=>t.add(n.id)),t}function Wt(e){return e.replacements||(e.replacements=[]),e.comments||(e.comments=[]),e}function Xr({sessionId:e,filePath:t,token:n,annotations:r,annLoadedRef:o,setAnnotations:c,baselineIdsRef:i}){const d=_(f=>f.latency),p=a.useRef(void 0),l=a.useRef(void 0),u=a.useRef(!1);a.useEffect(()=>{if(!o.current)return;const f=_e(e,t),h=JSON.stringify(r);p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(f,h)}catch{}},50),l.current&&clearTimeout(l.current);const g=Math.max(200,(d??30)*3);return l.current=setTimeout(()=>{u.current||(u.current=!0,hn(n,e,t,h,Date.now()).catch(()=>{}).finally(()=>{u.current=!1}))},g),()=>{p.current&&clearTimeout(p.current),l.current&&clearTimeout(l.current)}},[r,e,t,n,d,o]),a.useEffect(()=>{o.current=!1;let f=gt,h=0;try{const x=localStorage.getItem(_e(e,t));x&&(f=Wt(JSON.parse(x)),h=Date.now())}catch{}c(f),i.current=Qe(f);let g=!1;return Vr(n,e,t).then(x=>{if(!g&&x&&x.updatedAt>h)try{const R=Wt(JSON.parse(x.content));c(R);try{localStorage.setItem(_e(e,t),x.content)}catch{}i.current=Qe(R)}catch{}}).catch(()=>{}).finally(()=>{o.current=!0}),o.current=!0,()=>{g=!0}},[e,t,n,o,c,i])}function gn(e,t){let n=e.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");n||(n="heading");const r=t.get(n)||0;return r>0&&(n=`${n}-${r}`),t.set(n,r+1),n}function bn(e){return e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function Zr(e){if(!e)return[];const t=[],n=new Map,r=e.split(`
28
+ `);let o=!1;for(const c of r){if(/^```/.test(c.trim())){o=!o;continue}if(o)continue;const i=c.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(i){const d=i[1].length,p=bn(i[2]),l=gn(p,n);t.push({id:l,text:p,level:d})}}return t}const Qr=160,eo=22;function to({headings:e,scrollRef:t}){const[n,r]=a.useState(null),[o,c]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),i=a.useRef(null),d=a.useRef(!1),p=a.useMemo(()=>Math.min(...e.map(f=>f.level)),[e]),l=a.useCallback(()=>{c(f=>{const h=!f;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);a.useEffect(()=>{const f=t.current;if(!f||e.length===0)return;const h=()=>{d.current=!1;const x=f.scrollTop,R=50;let C=null;for(const j of e){const S=f.querySelector(`[id="${CSS.escape(j.id)}"]`);S&&S.offsetTop<=x+R&&(C=j.id)}r(C)},g=()=>{d.current||(d.current=!0,requestAnimationFrame(h))};return h(),f.addEventListener("scroll",g,{passive:!0}),()=>f.removeEventListener("scroll",g)},[e,t]);const u=a.useCallback(f=>{const h=t.current;if(!h)return;const g=h.querySelector(`[id="${CSS.escape(f)}"]`);g&&(g.scrollIntoView({behavior:"smooth",block:"start"}),r(f))},[t]);return a.useEffect(()=>{if(!n||o)return;const f=i.current;if(!f)return;const h=f.querySelector(`[data-toc-id="${CSS.escape(n)}"]`);if(h){const g=h.offsetTop-f.offsetTop,x=g+h.offsetHeight;(g<f.scrollTop||x>f.scrollTop+f.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[n,o]),e.length<2?null:o?s.jsx("div",{style:{width:eo,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{onClick:l,title:"Show table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:13,cursor:"pointer",padding:"2px",lineHeight:1},onMouseEnter:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"โ˜ฐ"})}):s.jsxs("div",{ref:i,style:{width:Qr,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),s.jsx("button",{onClick:l,title:"Hide table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:"0 2px",lineHeight:1},onMouseEnter:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"ยป"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:e.map((f,h)=>s.jsx("div",{"data-toc-id":f.id,onClick:()=>u(f.id),style:{padding:`2px 6px 2px ${(f.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:n===f.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:n===f.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:f.level<=2?500:400,transition:"color 0.1s"},title:f.text,onMouseEnter:g=>{n!==f.id&&(g.currentTarget.style.color="var(--text-primary)"),g.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:g=>{n!==f.id&&(g.currentTarget.style.color="var(--text-secondary)"),g.currentTarget.style.backgroundColor="transparent"},children:f.text},`${f.id}-${h}`))})]})}const no={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 ro({annotations:e,annCounts:t,isSent:n,onSendAll:r,onSendSingle:o,onDelete:c}){const[i,d]=a.useState(!1),p=a.useRef(null);a.useEffect(()=>{if(!i)return;const f=h=>{p.current&&!p.current.contains(h.target)&&d(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i]);const l=a.useCallback((f,h,g)=>{const x=no[h],R=n(f);return s.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[s.jsx("span",{className:"plan-anno-dropdown__type",style:{color:x.color},children:x.symbol}),s.jsxs("span",{className:"plan-anno-dropdown__text",children:[g.slice(0,60),g.length>60?"...":""]}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!R&&o(f,h),disabled:R,title:R?"Already sent":"Send to terminal",style:R?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>c(f,h),title:"Delete",children:"ร—"})]},f)},[n,o,c]),u=(()=>{const f=e.additions[0],h=e.deletions[0],g=e.replacements[0],x=e.comments[0],R=f?f.content:h?h.selectedText:g?g.content:x?x.content:"";return R?R.slice(0,40)+(R.length>40?"...":""):""})();return s.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[s.jsxs("div",{className:`plan-anno-dropdown-trigger${i?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>d(f=>!f),title:t.total>0?`${t.total} annotations (${t.unsent} unsent)`:"No annotations",children:[s.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:u}),s.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"โ–ผ"})]}),i&&s.jsxs("div",{className:"plan-anno-dropdown",children:[t.unsent>0&&s.jsx("div",{className:"plan-anno-dropdown__header",children:s.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",t.unsent,")"]})}),s.jsxs("div",{className:"plan-anno-dropdown__list",children:[e.additions.map(f=>l(f.id,"add",f.content)),e.deletions.map(f=>l(f.id,"del",f.selectedText)),e.replacements.map(f=>l(f.id,"rep",f.content)),e.comments.map(f=>l(f.id,"com",f.content)),t.total===0&&s.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const oo={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 lt({type:e,annotation:t,fontSize:n,onEdit:r,onRemove:o,onSend:c,isSent:i}){const d=oo[e],[p,l]=a.useState(!1),[u,f]=a.useState(""),h=a.useRef(null),g=e==="del"?t.selectedText:t.content,x=a.useCallback(()=>{l(!0),f(g)},[g]),R=a.useCallback(()=>{const C=u.trim();C?r(t.id,C):o(t.id),l(!1)},[u,t.id,r,o]);return a.useEffect(()=>{p&&requestAnimationFrame(()=>{const C=h.current;C&&(C.focus(),C.selectionStart=C.selectionEnd=C.value.length)})},[p]),p?s.jsx("div",{className:d.className,children:s.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:u,onChange:C=>f(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.ctrlKey||C.metaKey)&&(C.preventDefault(),R()),C.key==="Escape"&&(C.preventDefault(),l(!1))},onBlur:R,rows:Ze(u),style:{fontSize:`${n}px`,flex:1}})}):s.jsxs("div",{className:d.className,children:[d.icon&&s.jsx("span",{style:{color:d.color,flexShrink:0},children:d.icon}),e==="del"?s.jsx("span",{style:{flex:1,fontSize:`${n}px`,color:d.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:t.selectedText}):e==="rep"?s.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:t.selectedText}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:" โ†’ "}),s.jsx("span",{style:{color:"var(--accent-blue)"},children:t.content})]}):s.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',t.selectedText,'"']}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),s.jsx("span",{style:{color:"var(--accent-green)"},children:t.content})]}),c&&s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!i&&c(t.id),disabled:i,title:i?"Already sent":"Send to terminal",style:i?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:x,style:{color:"var(--accent-blue)"},title:`Edit ${e==="del"?"deletion":e==="rep"?"replacement":"comment"}`,children:"โœŽ"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>o(t.id),title:`Remove ${e==="del"?"deletion":e==="rep"?"replacement":"comment"}`,children:"ร—"})]})}function so({x:e,y:t,onDelete:n,onReplace:r,onComment:o}){return s.jsxs("div",{className:"plan-selection-float",style:{top:t,left:e},children:[s.jsx("button",{className:"plan-selection-float__delete",onMouseDown:c=>{c.preventDefault(),n()},title:"Delete selection",children:"โˆ’"}),s.jsx("button",{className:"plan-selection-float__replace",onMouseDown:c=>{c.preventDefault(),r()},title:"Replace selection",children:"โ‡„"}),s.jsx("button",{className:"plan-selection-float__comment",onMouseDown:c=>{c.preventDefault(),o()},title:"Comment on selection",children:"?"})]})}const ao=a.forwardRef(function({markdown:t,filePath:n,sessionId:r,token:o,onExecute:c,onSend:i,onRefresh:d,onClose:p,expanded:l,readOnly:u},f){const h=_(m=>m.fontSize),g=a.useMemo(()=>t?nn.lexer(t):[],[t]),x=a.useMemo(()=>t.split(`
29
+ `),[t]),R=a.useMemo(()=>Zr(t),[t]),C=a.useMemo(()=>{const m=new Map,b=new Map;return g.forEach((N,E)=>{if(N.type==="heading"){const J=bn(N.text||""),K=gn(J,b);m.set(E,K)}}),m},[g]),j=a.useRef(new Set),S=a.useRef(!1),[w,k]=a.useState(()=>{try{const m=localStorage.getItem(_e(r,n)),b=m?JSON.parse(m):gt;return j.current=Qe(b),b.replacements||(b.replacements=[]),b.comments||(b.comments=[]),b}catch{return gt}});Xr({sessionId:r,filePath:n,token:o,annotations:w,annLoadedRef:S,setAnnotations:k,baselineIdsRef:j});const[A,P]=a.useState(0),B=a.useMemo(()=>{const m=j.current,b=w.additions.length+w.deletions.length+w.replacements.length+w.comments.length;let N=0;return w.additions.forEach(E=>{m.has(E.id)&&N++}),w.deletions.forEach(E=>{m.has(E.id)&&N++}),w.replacements.forEach(E=>{m.has(E.id)&&N++}),w.comments.forEach(E=>{m.has(E.id)&&N++}),{total:b,sent:N,unsent:b-N}},[w,A]),[$,F]=a.useState(null),[O,D]=a.useState(""),T=a.useRef(null),[y,G]=a.useState(null),[W,U]=a.useState(""),V=a.useRef(null),[z,L]=a.useState(null),M=a.useRef(null),H=a.useRef(0),X=a.useRef(null);a.useEffect(()=>{const m=M.current;if(!m)return;let b;const N=()=>{clearTimeout(b),b=setTimeout(()=>{const E=$t(r,n);if(m.scrollTop>0)try{localStorage.setItem(E,String(m.scrollTop))}catch{}else localStorage.removeItem(E)},50)};return m.addEventListener("scroll",N,{passive:!0}),()=>{clearTimeout(b),m.removeEventListener("scroll",N)}},[r,n]),a.useEffect(()=>{if(!g.length)return;const m=localStorage.getItem($t(r,n));if(!m)return;const b=Number(m),N=M.current;if(!N||(N.scrollTop=b,N.scrollTop>=b-10))return;let E;const J=()=>{N.scrollTop=b,K.disconnect()},K=new MutationObserver(()=>{clearTimeout(E),E=setTimeout(J,80)});K.observe(N,{childList:!0,subtree:!0});const q=setTimeout(J,500);return()=>{clearTimeout(E),clearTimeout(q),K.disconnect()}},[r,n,g.length]),a.useEffect(()=>{$!=null&&requestAnimationFrame(()=>{var m;return(m=T.current)==null?void 0:m.focus()})},[$]),a.useEffect(()=>{y&&requestAnimationFrame(()=>{var m;return(m=V.current)==null?void 0:m.focus()})},[y]);const Y=a.useRef({annotations:w,activeInsert:$,insertText:O,pendingAction:y,pendingText:W,tokens:g,filePath:n,sessionId:r,token:o});Y.current={annotations:w,activeInsert:$,insertText:O,pendingAction:y,pendingText:W,tokens:g,filePath:n,sessionId:r,token:o},a.useEffect(()=>()=>{const m=Y.current;let b=m.annotations,N=!1;if(m.activeInsert!=null&&m.insertText.trim()){const E=Je(m.tokens,m.activeInsert+1);b={...b,additions:[...b.additions,{id:ce(),afterTokenIndex:m.activeInsert,sourceLine:E,content:m.insertText.trim()}]},N=!0}if(m.pendingAction&&m.pendingText.trim()){const E=m.pendingAction,J=m.pendingText.trim();E.type==="replace"?b={...b,replacements:[...b.replacements,{id:ce(),tokenIndices:E.tokenIndices,startLine:E.startLine,endLine:E.endLine,selectedText:E.text,content:J}]}:b={...b,comments:[...b.comments,{id:ce(),tokenIndices:E.tokenIndices,startLine:E.startLine,endLine:E.endLine,selectedText:E.text,content:J}]},N=!0}if(N){const E=JSON.stringify(b);try{localStorage.setItem(_e(m.sessionId,m.filePath),E)}catch{}hn(m.token,m.sessionId,m.filePath,E,Date.now()).catch(()=>{})}},[]);const Z=a.useCallback(m=>{if(!O.trim()){F(null),D("");return}const b=Je(g,m+1);k(N=>({...N,additions:[...N.additions,{id:ce(),afterTokenIndex:m,sourceLine:b,content:O.trim()}]})),F(null),D("")},[O,g]),ue=a.useCallback(m=>{k(b=>({...b,additions:b.additions.filter(N=>N.id!==m)}))},[]),ye=a.useCallback((m,b)=>{k(N=>({...N,additions:N.additions.map(E=>E.id===m?{...E,id:ce(),content:b}:E)}))},[]),$e=a.useCallback(()=>{var m;z&&(k(b=>({...b,deletions:[...b.deletions,{id:ce(),tokenIndices:z.tokenIndices,startLine:z.startLine,endLine:z.endLine,selectedText:z.text.slice(0,80)}]})),L(null),(m=window.getSelection())==null||m.removeAllRanges())},[z]),Se=a.useCallback(m=>{var b;z&&(G({type:m,tokenIndices:z.tokenIndices,startLine:z.startLine,endLine:z.endLine,text:z.text.slice(0,80)}),U(""),L(null),(b=window.getSelection())==null||b.removeAllRanges())},[z]),se=a.useCallback(()=>{if(!y)return;const m=W.trim();if(!m){G(null),U("");return}y.type==="replace"?k(b=>({...b,replacements:[...b.replacements,{id:ce(),tokenIndices:y.tokenIndices,startLine:y.startLine,endLine:y.endLine,selectedText:y.text,content:m}]})):k(b=>({...b,comments:[...b.comments,{id:ce(),tokenIndices:y.tokenIndices,startLine:y.startLine,endLine:y.endLine,selectedText:y.text,content:m}]})),G(null),U("")},[y,W]),ve=a.useCallback(m=>{k(b=>({...b,replacements:b.replacements.filter(N=>N.id!==m)}))},[]),le=a.useCallback((m,b)=>{k(N=>({...N,replacements:N.replacements.map(E=>E.id===m?{...E,id:ce(),content:b}:E)}))},[]),re=a.useCallback(m=>{k(b=>({...b,comments:b.comments.filter(N=>N.id!==m)}))},[]),Oe=a.useCallback((m,b)=>{k(N=>({...N,comments:N.comments.map(E=>E.id===m?{...E,id:ce(),content:b}:E)}))},[]),ae=a.useCallback(m=>{k(b=>({...b,deletions:b.deletions.filter(N=>N.id!==m)}))},[]),Re=a.useCallback((m,b)=>{k(N=>({...N,deletions:N.deletions.map(E=>E.id===m?{...E,id:ce(),selectedText:b}:E)}))},[]),fe=a.useCallback(m=>{let b=m instanceof Element?m:m.parentElement;for(;b&&b!==M.current;){if(b.hasAttribute("data-token-index"))return b;b=b.parentElement}return null},[]),me=a.useCallback(()=>{const m=window.getSelection();if(!m||m.isCollapsed||!M.current){L(null);return}const b=m.toString().trim();if(!b){L(null);return}const N=m.getRangeAt(0);if(!M.current.contains(N.commonAncestorContainer)){L(null);return}const E=fe(N.startContainer),J=fe(N.endContainer);if(!E||!J){L(null);return}const K=parseInt(E.getAttribute("data-token-index")||"0",10),q=parseInt(J.getAttribute("data-token-index")||"0",10),Q=[];for(let at=Math.min(K,q);at<=Math.max(K,q);at++)Q.push(at);const ge=Je(g,Math.min(K,q)),Me=Je(g,Math.max(K,q)+1),Be=N.getBoundingClientRect(),st=M.current,yt=st.getBoundingClientRect();navigator.clipboard.writeText(b).catch(()=>{});const Ue=X.current,vt=Ue&&Date.now()-Ue.time<500;H.current=Date.now(),L({x:(vt?Ue.x:Be.right)-yt.left+st.scrollLeft+6,y:(vt?Ue.y:Be.top)-yt.top+st.scrollTop-44,tokenIndices:Q,startLine:ge,endLine:Me,text:b})},[g,fe]),he=a.useRef(void 0);a.useEffect(()=>{const m=()=>{he.current&&clearTimeout(he.current),he.current=setTimeout(()=>{const b=window.getSelection();if(!b||b.isCollapsed||!M.current){if(Date.now()-H.current<300)return;L(null);return}const N=b.anchorNode;N&&M.current.contains(N)&&me()},120)};return document.addEventListener("selectionchange",m),()=>{document.removeEventListener("selectionchange",m),he.current&&clearTimeout(he.current)}},[me]);const Pe=_(m=>m.theme);Gr(M,g,Pe);const ke=a.useCallback(()=>{const m=j.current;return{additions:w.additions.filter(b=>!m.has(b.id)),deletions:w.deletions.filter(b=>!m.has(b.id)),replacements:w.replacements.filter(b=>!m.has(b.id)),comments:w.comments.filter(b=>!m.has(b.id))}},[w]),Te=a.useCallback(async()=>{const m=ke();if(!Pt(m))return;const b=Ot(m,x),N=Ut(n);try{const{path:E}=await _t(o,r,N,b),J=Bt(n,E);c(J),j.current=Qe(w),P(K=>K+1)}catch{}},[ke,w,x,c,n,o,r]),de=a.useCallback(async(m,b)=>{if(!i)return;const N={additions:[],deletions:[],replacements:[],comments:[]};if(b==="add"){const K=w.additions.find(q=>q.id===m);if(!K)return;N.additions.push(K)}else if(b==="del"){const K=w.deletions.find(q=>q.id===m);if(!K)return;N.deletions.push(K)}else if(b==="rep"){const K=w.replacements.find(q=>q.id===m);if(!K)return;N.replacements.push(K)}else{const K=w.comments.find(q=>q.id===m);if(!K)return;N.comments.push(K)}const E=Ot(N,x),J=Ut(n);try{const{path:K}=await _t(o,r,J,E);i(Bt(n,K)),j.current.add(m),P(q=>q+1)}catch{}},[i,n,w,x,o,r]),Ne=a.useCallback((m,b)=>{b==="add"?ue(m):b==="del"?ae(m):b==="rep"?ve(m):re(m)},[ue,ae,ve,re]);a.useImperativeHandle(f,()=>({getSummary:()=>{const m=ke();return Pt(m)?"[pending annotations]":""},handleEscape:()=>y?(se(),!0):$!=null?(Z($),!0):!1,getScrollTop:()=>{var m;return((m=M.current)==null?void 0:m.scrollTop)??0},setScrollTop:m=>{requestAnimationFrame(()=>{M.current&&(M.current.scrollTop=m)})}}),[ke,$,Z,y,se]);const Le=a.useMemo(()=>{const m=new Set;return w.deletions.forEach(b=>b.tokenIndices.forEach(N=>m.add(N))),m},[w.deletions]),De=a.useMemo(()=>{const m=new Set;return w.replacements.forEach(b=>b.tokenIndices.forEach(N=>m.add(N))),m},[w.replacements]),ot=a.useMemo(()=>{const m=new Set;return w.comments.forEach(b=>b.tokenIndices.forEach(N=>m.add(N))),m},[w.comments]),Fe=a.useMemo(()=>{const m=new Map;return w.additions.forEach(b=>{const N=m.get(b.afterTokenIndex)||[];N.push(b),m.set(b.afterTokenIndex,N)}),m},[w.additions]),v=B.unsent>0,I=a.useCallback(m=>j.current.has(m),[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:n,children:n.split("/").pop()||n}),d&&s.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"โ†ป"}),s.jsx("button",{className:"pane-btn",onClick:Te,disabled:!v,title:"Send all annotations",style:v?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),s.jsx(ro,{annotations:w,annCounts:B,isSent:I,onSendAll:Te,onSendSingle:de,onDelete:Ne}),p&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await Te(),p()},title:"Send annotations & close file",children:"ร—"})]}),s.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[s.jsxs("div",{ref:M,className:`plan-anno-content md-preview${$!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${h}px`,minWidth:0},onMouseUp:m=>{X.current={x:m.clientX,y:m.clientY,time:Date.now()},me()},children:[!u&&s.jsx(Ht,{index:-1,active:$===-1,additions:Fe.get(-1),onOpen:()=>{F(-1),D("")},onSubmit:()=>Z(-1),onRemoveAddition:ue,onEditAddition:ye,onSendSingle:i?m=>de(m,"add"):void 0,isSent:I,insertText:O,setInsertText:D,textareaRef:$===-1?T:void 0,expanded:l,alwaysShow:g.length===0,fontSize:h}),g.map((m,b)=>{const N=Yr(m);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":b,id:C.get(b),className:Le.has(b)?"plan-block--deleted":De.has(b)?"plan-block--replaced":ot.has(b)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:N}}),w.deletions.filter(E=>E.tokenIndices[0]===b).map(E=>s.jsx(lt,{type:"del",annotation:E,fontSize:h,onEdit:Re,onRemove:ae,onSend:i?J=>de(J,"del"):void 0,isSent:j.current.has(E.id)},E.id)),w.replacements.filter(E=>E.tokenIndices[0]===b).map(E=>s.jsx(lt,{type:"rep",annotation:E,fontSize:h,onEdit:le,onRemove:ve,onSend:i?J=>de(J,"rep"):void 0,isSent:j.current.has(E.id)},E.id)),w.comments.filter(E=>E.tokenIndices[0]===b).map(E=>s.jsx(lt,{type:"com",annotation:E,fontSize:h,onEdit:Oe,onRemove:re,onSend:i?J=>de(J,"com"):void 0,isSent:j.current.has(E.id)},E.id)),y&&y.tokenIndices[0]===b&&s.jsxs("div",{className:y.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[s.jsx("span",{style:{color:y.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:y.type==="replace"?"โ‡„":"?"}),s.jsx("textarea",{ref:V,className:"plan-annotation-textarea",value:W,onChange:E=>U(E.target.value),onKeyDown:E=>{if(E.key==="Enter"&&(E.ctrlKey||E.metaKey)){E.preventDefault(),se();return}if(E.key==="Escape"){E.preventDefault(),se();return}},onBlur:se,placeholder:y.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:Ze(W),style:{fontSize:`${h}px`,flex:1}})]}),!u&&s.jsx(Ht,{index:b,active:$===b,additions:Fe.get(b),onOpen:()=>{F(b),D("")},onSubmit:()=>Z(b),onRemoveAddition:ue,onEditAddition:ye,onSendSingle:i?E=>de(E,"add"):void 0,isSent:I,insertText:O,setInsertText:D,textareaRef:$===b?T:void 0,expanded:l,fontSize:h})]},b)}),!u&&z&&s.jsx(so,{x:z.x,y:z.y,onDelete:$e,onReplace:()=>Se("replace"),onComment:()=>Se("comment")})]}),s.jsx(to,{headings:R,scrollRef:M})]})]})});function Ht({index:e,active:t,additions:n,onOpen:r,onSubmit:o,onRemoveAddition:c,onEditAddition:i,onSendSingle:d,isSent:p,insertText:l,setInsertText:u,textareaRef:f,expanded:h,alwaysShow:g,fontSize:x=14}){const[R,C]=a.useState(null),[j,S]=a.useState(""),w=a.useRef(null),k=mt(),A=mt();a.useEffect(()=>{R&&(k.clearUndo(),requestAnimationFrame(()=>{const D=w.current;D&&(D.focus(),D.selectionStart=D.selectionEnd=D.value.length)}))},[R]),a.useEffect(()=>{t&&A.clearUndo()},[t]);const P=a.useCallback(D=>{S(T=>(k.pushUndo(T),D))},[k]),B=a.useCallback(D=>{A.pushUndo(l),u(D)},[l,u,A]),$=a.useCallback(D=>{C(D.id),S(D.content)},[]),F=a.useCallback(()=>{if(!R)return;const D=j.trim();D?i(R,D):c(R),C(null),S("")},[R,j,i,c]),O=a.useCallback(()=>{C(null),S("")},[]);return s.jsxs("div",{className:`plan-insert-zone${g?" plan-insert-zone--empty":""}`,"data-zone-index":e,children:[n==null?void 0:n.map(D=>s.jsx("div",{className:"plan-annotation-card",children:R===D.id?s.jsx("textarea",{ref:w,className:"plan-annotation-textarea",value:j,onChange:T=>P(T.target.value),onKeyDown:T=>{if(T.key==="Enter"&&(T.ctrlKey||T.metaKey)){T.preventDefault(),F();return}if(T.key==="Escape"){T.preventDefault(),O();return}if(T.key==="Tab"){ht(T,P);return}},onBlur:F,rows:Ze(j),style:{fontSize:`${x}px`,flex:1,...h?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${x}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>$(D),title:"Double-click to edit",children:D.content}),d&&(()=>{const T=(p==null?void 0:p(D.id))??!1;return s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!T&&d(D.id),disabled:T,title:T?"Already sent":"Send to terminal",style:T?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>$(D),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"โœŽ"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>c(D.id),children:"ร—"})]})},D.id)),t?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:f,className:"plan-annotation-textarea",value:l,onChange:D=>B(D.target.value),onKeyDown:D=>{if(D.key==="Enter"&&(D.ctrlKey||D.metaKey)){D.preventDefault(),o();return}if(D.key==="Escape"){D.preventDefault(),o();return}if(D.key==="Tab"){ht(D,B);return}},onBlur:o,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:Ze(l),style:{fontSize:`${x}px`,...h?{minWidth:300}:void 0}})}):g&&!(n!=null&&n.length)?s.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:r,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function be(e,t,n){const r=n?{path:n}:void 0;return ne.get(e,t,"files",r)}function co(e,t,n,r){return new Promise((o,c)=>{const i=new FormData;for(const p of n)i.append("files",p);const d=new XMLHttpRequest;d.open("POST",`${xe}/api/sessions/${encodeURIComponent(t)}/upload`),d.setRequestHeader("Authorization",`Bearer ${e}`),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?o():c(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>c(new Error("Upload network error"))),d.addEventListener("abort",()=>c(new Error("Upload aborted"))),d.send(i)})}async function Kt(e,t){return(await ne.get(e,t,"cwd")).cwd}async function io(e,t,n){return ne.post(e,t,"touch",{name:n})}async function lo(e,t,n){return ne.post(e,t,"mkdir",{path:n})}async function uo(e,t,n){return ne.del(e,t,"rm",{path:n})}async function fo(e,t){const n=await ne.getBlob(e,t,"download-cwd"),r=await n.blob(),o=URL.createObjectURL(r),c=document.createElement("a");c.href=o;const i=n.headers.get("Content-Disposition"),d=i==null?void 0:i.match(/filename="(.+)"/);c.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(o)}async function po(e,t,n){const o=await(await ne.getBlob(e,t,"download",{path:n})).blob(),c=URL.createObjectURL(o),i=document.createElement("a");i.href=c,i.download=n.split("/").pop()||"download",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(c)}function xn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function mo(e,t){if(t==="directory")return"๐Ÿ“";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"๐Ÿ“•":n===".html"||n===".htm"?"๐ŸŒ":n===".md"?"๐Ÿ“":"๐Ÿ“„"}function yn(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function ho({sessionId:e,token:t,planDir:n,selectedFile:r,onSelectFile:o,onCreateFile:c,onDeleteFile:i}){const[d,p]=a.useState([]),[l,u]=a.useState(!0),[f,h]=a.useState(""),[g,x]=a.useState(!1),R=a.useRef(null),[C,j]=a.useState(n),S=a.useCallback(async()=>{if(!(!t||!C)){u(!0);try{const G=(await be(t,e,C)).files.filter(W=>W.type==="file"&&W.name.toLowerCase().endsWith(".md")||W.type==="directory").sort((W,U)=>{const V=W.type==="file"&&W.name===".index.md",z=U.type==="file"&&U.name===".index.md";return V&&!z?-1:!V&&z?1:W.type==="directory"&&U.type!=="directory"?-1:W.type!=="directory"&&U.type==="directory"?1:W.name.localeCompare(U.name)});p(G)}catch{p([])}finally{u(!1)}}},[t,e,C]);a.useEffect(()=>{S()},[S]),a.useEffect(()=>{const y=setInterval(S,5e3);return()=>clearInterval(y)},[S]);const w=a.useCallback(()=>{const y=n.substring(0,n.lastIndexOf("/")+1);return C.startsWith(y)?C.substring(y.length):C},[n,C]),k=a.useCallback(async()=>{const y=f.trim();if(!y)return;const G=y.endsWith(".md")?y:`${y}.md`;x(!0);try{const W=await io(t,e,`${w()}/${G}`);W.ok&&(h(""),await S(),c(W.path))}catch{}finally{x(!1)}},[f,t,e,w,S,c]),A=a.useCallback(async()=>{const y=f.trim().replace(/\/+$/,"");if(y){x(!0);try{await lo(t,e,`${w()}/${y}`),h(""),await S()}catch{}finally{x(!1)}}},[f,t,e,w,S]),P=a.useCallback(async y=>{const G=`${C}/${y.name}`,W=y.type==="directory"?`folder "${y.name}" and all its contents`:`"${y.name}"`;if(window.confirm(`Delete ${W}?`))try{await uo(t,e,G),i==null||i(G),await S()}catch{}},[t,e,C,S,i]),B=a.useCallback(y=>{j(G=>`${G}/${y}`)},[]),$=a.useCallback(()=>{C!==n&&j(y=>y.substring(0,y.lastIndexOf("/")))},[C,n]),F=n.split("/").pop()||"AiTasks",O=(()=>{const y=n.split("/");return y.length>=2?y[y.length-2]+"/":""})(),D=C===n?O+F+"/":O+F+"/"+C.substring(n.length+1)+"/",T=r?r.split("/").pop():null;return s.jsxs("div",{className:"plan-file-browser",children:[s.jsxs("div",{className:"plan-file-browser__header",children:[s.jsx("span",{className:"plan-file-browser__title",title:D,children:D}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:S,title:"Refresh file list",style:{fontSize:12},children:"โ†ป"})]}),s.jsxs("div",{className:"plan-file-browser__create",children:[s.jsx("input",{ref:R,className:"plan-file-browser__input",value:f,onChange:y=>h(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),k())},placeholder:"name",disabled:g}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:k,disabled:g||!f.trim(),title:"Create new .md file",style:f.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:A,disabled:g||!f.trim(),title:"Create new folder",style:f.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"๐Ÿ“"})]}),s.jsxs("div",{className:"plan-file-browser__list",children:[l&&d.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!l&&d.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),C!==n&&s.jsxs("div",{className:"plan-file-browser__item",onClick:$,title:"Go up to parent directory",style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"โ†"}),s.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(y=>{const G=`${C}/${y.name}`,W=y.type==="file"&&y.name===T,U=y.type==="directory";return s.jsxs("div",{className:`plan-file-browser__item${W?" plan-file-browser__item--active":""}`,onClick:()=>U?B(y.name):o(G),title:U?`Open folder ${y.name}`:y.name,style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",children:U?"๐Ÿ“":y.name===".index.md"?"๐Ÿ”’":"โ–ก"}),s.jsxs("span",{className:"plan-file-browser__name",children:[y.name,U?"/":""]}),!U&&s.jsx("span",{className:"plan-file-browser__size",children:xn(y.size)}),y.name!==".index.md"&&s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:V=>{V.stopPropagation(),P(y)},title:`Delete ${y.name}`,children:"ร—"})]},y.name)})]})]})}const dt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},go=200;function bo(){const[e,t]=a.useState(dt),n=a.useRef("lines"),r=a.useRef([]),o=a.useRef(""),c=a.useRef(""),i=a.useRef([]),d=a.useRef(0),p=a.useRef(0),l=a.useRef(null),u=a.useRef(null),f=a.useCallback(()=>{const j=n.current;t(S=>({...S,receivedBytes:d.current,...j==="lines"?{lines:[...r.current]}:{},...j==="content"?{content:c.current}:{}}))},[]),h=a.useCallback(()=>{l.current===null&&(l.current=window.setTimeout(()=>{l.current=null,f()},go))},[f]),g=a.useCallback(j=>{n.current=j,r.current=[],o.current="",c.current="",i.current=[],d.current=0,p.current=0,u.current=new TextDecoder,l.current!==null&&(clearTimeout(l.current),l.current=null),t({...dt,mode:j,status:"streaming"})},[]),x=a.useCallback(j=>{d.current+=j.length;const S=n.current;if(S==="lines"){const k=u.current.decode(j,{stream:!0}).split(`
30
+ `);k[0]=o.current+k[0],o.current=k.pop(),k.length>0&&r.current.push(...k)}else if(S==="content"){const w=u.current.decode(j,{stream:!0});c.current+=w}else i.current.push(new Uint8Array(j));h()},[h]),R=a.useCallback(j=>{switch(j.type){case"file-stream-start":p.current=j.size,t(S=>({...S,totalSize:j.size,mtime:j.mtime}));break;case"file-stream-end":{l.current!==null&&(clearTimeout(l.current),l.current=null);const S=n.current;let w=r.current,k=c.current,A=null;if(S==="lines"){const P=u.current.decode(),B=o.current+P;B&&(w=[...w,B],r.current=w),o.current=""}else if(S==="content"){const P=u.current.decode();k=c.current+P,c.current=k}else{const P=i.current.reduce(($,F)=>$+F.length,0);A=new Uint8Array(P);let B=0;for(const $ of i.current)A.set($,B),B+=$.length;i.current=[]}t({status:"complete",mode:S,lines:S==="lines"?[...w]:[],content:S==="content"?k:"",buffer:S==="binary"?A:null,totalSize:p.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":l.current!==null&&(clearTimeout(l.current),l.current=null),t(S=>({...S,status:"error",error:j.error}));break}},[]),C=a.useCallback(()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),r.current=[],o.current="",c.current="",i.current=[],d.current=0,p.current=0,u.current=null,t(dt)},[]);return{state:e,startStream:g,handleChunk:x,handleControl:R,reset:C}}async function Jt(e,t,n,r){const o={path:n};return r&&(o.since=String(r)),ne.getOptional(e,t,"file-content",o)}function Gt({label:e,percent:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:e}),t!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${t}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[t,"%"]})]})]})}function xo({sessionId:e,token:t,connected:n,onRequestFileStream:r,onSendToTerminal:o}){const c=bo(),[i,d]=a.useState(!1),[p,l]=a.useState(null),[u,f]=a.useState(null),[h,g]=a.useState(""),[x,R]=a.useState(!1),[C,j]=a.useState(!1),S=a.useRef(null),w=`plan-selected-file-${e}`,k=a.useRef(void 0);a.useEffect(()=>{if(u)return clearTimeout(k.current),k.current=setTimeout(()=>{try{localStorage.setItem(w,u)}catch{}},50),()=>clearTimeout(k.current)},[u,w]);const A=a.useRef(null);a.useEffect(()=>{A.current=null;let L=!1;return R(!0),j(!1),(async()=>{let M="";try{const H=await be(t,e);if(L)return;if(M=H.home||"",H.files.find(Y=>Y.name==="AiTasks"&&Y.type==="directory")){const Y=H.cwd+"/AiTasks";l(Y);const Z=localStorage.getItem(w);Z&&Z.startsWith(Y+"/")&&f(Z)}else l(null),f(null),j(!0)}catch{l(null)}finally{L||R(!1)}try{if(L)return;if(M){const H=`${M}/.claude/plugins/installed_plugins.json`,X=await Jt(t,e,H,0);if(!L&&X)try{const Y=JSON.parse(X.content);"ai-cli-task@moonview"in(Y.plugins||Y)||d(!0)}catch{d(!0)}}}catch{}})(),()=>{L=!0}},[e,t]),a.useEffect(()=>(wr(e,c.handleChunk,c.handleControl),()=>Sr(e)),[e,c.handleChunk,c.handleControl]),a.useEffect(()=>{!u||!n||A.current===u&&h||(A.current=u,c.reset(),c.startStream("content"),r==null||r(u))},[u,n]);const P=a.useRef(0);a.useEffect(()=>{c.state.status==="complete"&&u&&(g(c.state.content),P.current=Date.now())},[c.state.status,c.state.content,u]),a.useEffect(()=>{if(!u||!n||!h)return;const L=setInterval(async()=>{if(P.current)try{const M=await Jt(t,e,u,P.current);M&&(g(M.content),P.current=M.mtime)}catch{}},3e3);return()=>clearInterval(L)},[u,n,h,t,e]);const B=a.useRef(new Map),$=a.useCallback(()=>{var M,H;if(!u)return;const L=((H=(M=S.current)==null?void 0:M.getScrollTop)==null?void 0:H.call(M))??0;L>0&&B.current.set(u,L)},[u]);a.useEffect(()=>{if(!u||!h)return;const L=B.current.get(u);L!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var M,H;(H=(M=S.current)==null?void 0:M.setScrollTop)==null||H.call(M,L)})})},[u,h]);const F=a.useCallback(L=>{L!==u&&($(),f(L),g(""),A.current=null)},[u,$]),O=a.useCallback(L=>{u&&(u===L||u.startsWith(L+"/"))&&(f(null),g(""),A.current=null)},[u]),D=a.useCallback(L=>{f(L),g(""),A.current=null},[]),T=a.useCallback(L=>{L&&(o==null||o(L))},[o]),y=a.useCallback(()=>{$(),f(null),g(""),A.current=null},[$]),G=a.useCallback(()=>{!u||!n||(A.current=null,g(""),c.reset(),c.startStream("content"),r==null||r(u),A.current=u)},[u,n,c,r]),[W,U]=a.useState(()=>{const L=localStorage.getItem(`plan-fb-width-${e}`);if(L){const M=Number(L);if(Number.isFinite(M)&&M>=60&&M<=300)return M}return 130}),V=a.useRef(W);if(W!==V.current){V.current=W;try{localStorage.setItem(`plan-fb-width-${e}`,String(Math.round(W)))}catch{}}const z=a.useCallback(L=>{L.preventDefault();const M=L.clientX,H=W;document.body.classList.add("resizing-panes");const X=Z=>{const ue=Z.clientX-M;U(Math.min(300,Math.max(60,H+ue)))},Y=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",Y)};document.addEventListener("mousemove",X),document.addEventListener("mouseup",Y)},[W]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[i&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",fontSize:12,flexShrink:0},children:[s.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),s.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{o&&o("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),d(!1)},children:"Install"}),s.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>d(!1),children:"ร—"})]}),s.jsxs("div",{className:"plan-overlay-body",children:[p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:W,flexShrink:0,overflow:"hidden"},children:s.jsx(ho,{sessionId:e,token:t,planDir:p,selectedFile:u,onSelectFile:F,onCreateFile:D,onDeleteFile:O})}),s.jsx("div",{onMouseDown:z,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:L=>{L.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:L=>{L.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsx("div",{className:"plan-overlay-center",children:x?s.jsx(Gt,{label:"Loading AiTasks/..."}):C?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),s.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",s.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/ai-cli-task init <name>"})," in the terminal to create a task"]})]}):u&&!h&&(c.state.status==="streaming"||c.state.status==="idle")?s.jsx(Gt,{label:`Loading ${u.split("/").pop()}...`,percent:c.state.totalSize>0?Math.round(c.state.receivedBytes/c.state.totalSize*100):void 0}):u?s.jsx(ao,{ref:S,markdown:h,filePath:u,sessionId:e,token:t,onExecute:T,onSend:o,onRefresh:G,onClose:y,readOnly:u.endsWith("/.index.md")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]})]})}async function yo(e,t){try{return(await ne.get(e,t,"draft")).content??""}catch{return""}}async function Vt(e,t,n){try{await ne.put(e,t,"draft",{content:n})}catch{}}const xt="chat-history",qt=50;function vn(){try{const e=localStorage.getItem(xt);return e?JSON.parse(e):[]}catch{return[]}}function vo(e){const n=vn().filter(r=>r.text!==e);n.unshift({text:e,ts:Date.now()}),n.length>qt&&(n.length=qt),localStorage.setItem(xt,JSON.stringify(n))}const Yt=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],wo=a.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},c){const i=_(v=>v.fontSize),[d,p]=a.useState(""),l=a.useRef(null),u=a.useRef(void 0),f=a.useRef(!1),h=a.useRef(!1),{pushUndo:g,popUndo:x}=mt(),R=a.useRef(d);R.current=d;const C=a.useCallback(()=>g(R.current),[g]),[j,S]=a.useState(!1),[w,k]=a.useState(""),[A,P]=a.useState(0),[B,$]=a.useState(!1),[F,O]=a.useState([]),[D,T]=a.useState(0),[y,G]=a.useState(""),W=a.useRef(null),U=a.useMemo(()=>{if(!y)return F;const v=y.toLowerCase();return F.filter(I=>I.text.toLowerCase().includes(v))},[F,y]),[V,z]=a.useState(!1),[L,M]=a.useState(""),[H,X]=a.useState(""),[Y,Z]=a.useState(0),[ue,ye]=a.useState([]),[$e,Se]=a.useState(!1),se=a.useRef(""),ve=a.useRef(null),le=a.useMemo(()=>{if(!w)return Yt;const v=w.toLowerCase();return Yt.filter(I=>I.cmd.toLowerCase().includes(v)||I.desc.toLowerCase().includes(v))},[w]),re=a.useMemo(()=>{let v=ue;if(L){const I=L.toLowerCase();v=v.filter(m=>m.name.toLowerCase().includes(I))}return[...v].sort((I,m)=>I.type==="directory"&&m.type!=="directory"?-1:I.type!=="directory"&&m.type==="directory"?1:I.name.localeCompare(m.name))},[ue,L]),Oe=_(v=>v.latency),ae=`chat-draft-${r}`,Re=a.useRef(!1),fe=a.useRef(void 0);a.useEffect(()=>{try{const I=localStorage.getItem(ae);I&&!h.current&&p(I)}catch{}let v=!1;return yo(o,r).then(I=>{if(v||h.current){f.current=!0;return}if(I){p(I);try{localStorage.setItem(ae,I)}catch{}}f.current=!0}).catch(()=>{f.current=!0}),()=>{v=!0}},[o,r,ae]),a.useEffect(()=>{if(!f.current)return;u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{try{localStorage.setItem(ae,d)}catch{}},50),fe.current&&clearTimeout(fe.current);const v=Math.max(200,(Oe??30)*3);return fe.current=setTimeout(()=>{Re.current||(Re.current=!0,Vt(o,r,d).catch(()=>{}).finally(()=>{Re.current=!1}))},v),()=>{u.current&&clearTimeout(u.current),fe.current&&clearTimeout(fe.current)}},[d,o,r,Oe,ae]),a.useEffect(()=>{var v;(v=l.current)==null||v.focus()},[]),a.useEffect(()=>{if(!V)return;let v=!1;return Se(!0),(async()=>{try{if(H){if(!se.current){const b=await be(o,r);if(v)return;se.current=b.cwd}const I=`${se.current}/${H.replace(/\/$/,"")}`,m=await be(o,r,I);if(v)return;ye(m.files)}else{const I=await be(o,r);if(v)return;se.current=I.cwd,ye(I.files)}Se(!1)}catch{if(v)return;ye([]),Se(!1)}})(),()=>{v=!0}},[V,H,o,r]),a.useEffect(()=>{if(!V||!ve.current)return;const v=ve.current.querySelector(".file-item--active");v==null||v.scrollIntoView({block:"nearest"})},[Y,V]);const me=a.useCallback(()=>{const v=R.current.trim();if(v){vo(v),t(v),p("");try{localStorage.removeItem(ae)}catch{}Vt(o,r,"").catch(()=>{})}},[t,o,r,ae]),he=a.useCallback(v=>{C(),p(v),h.current=!0},[C]),Pe=a.useCallback(v=>{const I=l.current;C();const m=R.current;if(I){const b=I.selectionStart,N=I.selectionEnd,E=m.slice(0,b)+v+m.slice(N);p(E);const J=b+v.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=J,I.focus()})}else p(m+v)},[C]);a.useImperativeHandle(c,()=>({send:me,fillContent:he,insertAtCursor:Pe}),[me,he,Pe]),a.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const ke=a.useCallback(()=>{const v=l.current;if(!v)return;const{selectionStart:I,selectionEnd:m}=v;if(I!==m){const b=v.value.substring(I,m);b&&navigator.clipboard.writeText(b).catch(()=>{})}},[]),Te=a.useCallback(()=>{const v=vn();S(!1),k("");const I=l.current;if(I){const m=I.selectionStart,b=d.slice(0,m),N=d.slice(m),E=b.match(/(?:^|\s)(\/history)\s*$/);if(E){const J=b.length-E[1].length;p(d.slice(0,J)+N)}}v.length!==0&&(O(v),T(0),G(""),$(!0))},[d]),de=a.useCallback(v=>{C(),p(v.text),$(!1),requestAnimationFrame(()=>{const I=l.current;I&&(I.selectionStart=I.selectionEnd=v.text.length,I.focus())})},[C]),Ne=a.useCallback(v=>{const I=U[v];if(!I)return;const m=F.filter(N=>N.ts!==I.ts||N.text!==I.text);O(m),localStorage.setItem(xt,JSON.stringify(m));const b=y?m.filter(N=>N.text.toLowerCase().includes(y.toLowerCase())):m;D>=b.length&&T(Math.max(0,b.length-1))},[U,F,D,y]);a.useEffect(()=>{if(!B||!W.current)return;const v=W.current.querySelector(".history-item--active");v==null||v.scrollIntoView({block:"nearest"})},[D,B]);const Le=a.useCallback(v=>{if(v==="/history"){Te();return}const I=l.current;if(!I)return;C();const m=I.selectionStart,b=d.slice(0,m),N=d.slice(m),J=b.lastIndexOf(`
31
+ `)+1,q=b.slice(J).match(/\/[a-zA-Z:-]*$/);if(q){const Q=J+(q.index??0),ge=v+" ",Me=d.slice(0,Q)+ge+N;p(Me);const Be=Q+ge.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Be,I.focus()})}else{const Q=b+v+N;p(Q);const ge=m+v.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=ge,I.focus()})}S(!1),k(""),P(0)},[d,C,Te]),De=a.useCallback(v=>{const I=l.current;if(!I)return;C();const m=I.selectionStart,b=d.slice(0,m),N=d.slice(m),E=b.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!E)return;const J=b.length-E[0].length;if(v.type==="directory"){const K="@"+H+v.name+"/",q=d.slice(0,J)+K+N;p(q);const Q=J+K.length;X(H+v.name+"/"),M(""),Z(0),requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Q,I.focus()})}else{const K=v.name+" ",q=d.slice(0,J)+K+N;p(q);const Q=J+K.length;z(!1),M(""),X(""),Z(0),ye([]),se.current="",requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Q,I.focus()})}},[d,H,C]),ot=a.useCallback(v=>{const I=v.target.value;if(p(I),B){const K=I.trim();K?(G(K),T(0)):G("");return}const m=v.target.selectionStart,b=I.slice(0,m),N=b.lastIndexOf(`
32
+ `),J=b.slice(N+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(J)S(!0),k(J[1]),P(0),z(!1);else{S(!1);const K=b.match(/@([a-zA-Z0-9_.\-/]*)$/);if(K){const q=K[1],Q=q.lastIndexOf("/"),ge=Q>=0?q.slice(0,Q+1):"",Me=Q>=0?q.slice(Q+1):q;M(Me),Z(0),X(ge),z(!0)}else z(!1)}},[B]),Fe=a.useCallback(v=>{if(j&&le.length>0){if(v.key==="ArrowDown"){v.preventDefault(),P(I=>(I+1)%le.length);return}if(v.key==="ArrowUp"){v.preventDefault(),P(I=>(I-1+le.length)%le.length);return}if(v.key==="Enter"||v.key==="Tab"){v.preventDefault(),Le(le[A].cmd);return}if(v.key==="Escape"){v.preventDefault(),S(!1);return}}if(V&&re.length>0){if(v.key==="ArrowDown"){v.preventDefault(),Z(I=>(I+1)%re.length);return}if(v.key==="ArrowUp"){v.preventDefault(),Z(I=>(I-1+re.length)%re.length);return}if(v.key==="Tab"||v.key==="Enter"){v.preventDefault(),De(re[Y]);return}if(v.key==="Escape"){v.preventDefault(),z(!1);return}}if(B&&U.length>0){if(v.key==="ArrowDown"){v.preventDefault(),T(I=>(I+1)%U.length);return}if(v.key==="ArrowUp"){v.preventDefault(),T(I=>(I-1+U.length)%U.length);return}if(v.key==="Enter"){v.preventDefault(),de(U[D]);return}if(v.key==="Delete"||v.key==="Backspace"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),Ne(D);return}if(v.key==="Escape"){v.preventDefault(),$(!1);return}}if(v.key==="Tab"){ht(v,p,g);return}v.key==="Enter"&&(v.ctrlKey||v.metaKey)&&(v.preventDefault(),me())},[me,j,le,A,Le,V,re,Y,De,g,x,B,U,D,de,Ne]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[j&&le.length>0&&s.jsx("div",{className:"slash-dropdown",children:le.map((v,I)=>s.jsxs("div",{className:`slash-item${I===A?" slash-item--active":""}`,onMouseDown:m=>{m.preventDefault(),Le(v.cmd)},onMouseEnter:()=>P(I),children:[s.jsx("span",{className:"slash-cmd",children:v.cmd}),s.jsx("span",{className:"slash-desc",children:v.desc})]},v.cmd))}),V&&($e||re.length>0)&&s.jsx("div",{className:"file-dropdown",ref:ve,children:$e?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):re.map((v,I)=>s.jsxs("div",{className:`file-item${I===Y?" file-item--active":""}`,onMouseDown:m=>{m.preventDefault(),De(v)},onMouseEnter:()=>Z(I),children:[s.jsx("span",{className:"file-icon",children:v.type==="directory"?"๐Ÿ“":"๐Ÿ“„"}),s.jsx("span",{className:"file-name",children:v.name})]},v.name))}),B&&s.jsx("div",{className:"history-dropdown",ref:W,children:U.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):U.map((v,I)=>s.jsxs("div",{className:`history-item${I===D?" history-item--active":""}`,onMouseDown:m=>{m.preventDefault(),de(v)},onMouseEnter:()=>T(I),children:[s.jsx("span",{className:"history-text",children:v.text.length>120?v.text.slice(0,120)+"...":v.text}),s.jsx("span",{className:"history-time",children:new Date(v.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:m=>{m.preventDefault(),m.stopPropagation(),Ne(I)},title:"Delete (Del key)",children:"ร—"})]},`${v.ts}-${I}`))}),s.jsx("textarea",{ref:l,className:"md-editor-textarea",value:d,onChange:ot,onKeyDown:Fe,onMouseUp:ke,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${i}px`}})]})});function So({token:e,sessionId:t,onClose:n}){const[r,o]=a.useState([]),[c,i]=a.useState(""),[d,p]=a.useState([]),[l,u]=a.useState(!0),[f,h]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{let S=!1;return(async()=>{try{const w=await be(e,t);S||(i(w.cwd),o(w.files))}catch{S||n()}finally{S||u(!1)}})(),()=>{S=!0}},[e,t,n]),a.useEffect(()=>{const S=A=>{A.key==="Escape"&&n()},w=A=>{g.current&&!g.current.contains(A.target)&&n()};document.addEventListener("keydown",S);const k=setTimeout(()=>document.addEventListener("mousedown",w),50);return()=>{document.removeEventListener("keydown",S),document.removeEventListener("mousedown",w),clearTimeout(k)}},[n]);const x=a.useCallback(async S=>{u(!0);try{const w=await be(e,t,S);p(k=>[...k,c]),i(S),o(w.files)}catch{}finally{u(!1)}},[e,t,c]),R=a.useCallback(async()=>{if(d.length===0)return;const S=d[d.length-1];u(!0);try{const w=await be(e,t,S);p(k=>k.slice(0,-1)),i(S),o(w.files)}catch{}finally{u(!1)}},[e,t,d]),C=a.useCallback(async S=>{try{await po(e,t,S)}catch(w){alert(`Download failed: ${w instanceof Error?w.message:"Unknown error"}`)}},[e,t]),j=a.useCallback(async()=>{h(!0),n();try{await fo(e,t)}catch(S){alert(`Download failed: ${S instanceof Error?S.message:"Unknown error"}`)}finally{h(!1)}},[e,t,n]);return s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[d.length>0&&s.jsx("button",{className:"pane-btn",onClick:R,disabled:l,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),s.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:c.split("/").slice(-2).join("/")||c}),s.jsx("button",{className:"pane-btn",onClick:n,style:{fontSize:11,flexShrink:0},title:"Close",children:"ร—"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:l?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(S=>s.jsxs("div",{onClick:()=>{const w=c+"/"+S.name;S.type==="directory"?x(w):C(w)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{flexShrink:0,fontSize:13},children:S.type==="directory"?"๐Ÿ“":mo(S.name,S.type)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name}),S.type==="directory"?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"โ€บ"}):S.size!=null?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:xn(S.size)}):null]},S.name))}),s.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{className:"pane-btn",onClick:j,disabled:f,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:f?"Downloading...":"Download All (tar.gz)"})})]})}function Xt(e,t,{containerRef:n,axis:r,offset:o=0,min:c,max:i,invert:d=!1,bodyClass:p}){const[l,u]=a.useState(()=>{const g=localStorage.getItem(e);if(g){const x=Number(g);if(Number.isFinite(x)&&x>=c&&x<=i)return x}return t}),f=a.useRef(l);if(l!==f.current){f.current=l;try{localStorage.setItem(e,String(Math.round(l)))}catch{}}const h=a.useCallback(g=>{g.preventDefault();const x=n.current;if(!x)return;const R=x.getBoundingClientRect(),C=r==="x"?R.width:R.height-o,j=r==="x"?R.left:R.top+o;document.body.classList.add(p);const S=k=>{let P=((r==="x"?k.clientX:k.clientY)-j)/C*100;d&&(P=100-P),u(Math.min(i,Math.max(c,P)))},w=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",w)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",w)},[n,r,o,c,i,d,p]);return[l,h]}const ko=600,Ie=typeof window<"u"?window.matchMedia(`(max-width: ${ko-1}px)`):null;function To(){const[e,t]=a.useState(()=>(Ie==null?void 0:Ie.matches)??!1);return a.useEffect(()=>{if(!Ie)return;const n=r=>t(r.matches);return Ie.addEventListener("change",n),()=>Ie.removeEventListener("change",n)},[]),e}const Co=a.memo(function({terminal:t}){const n=To(),r=_(z=>z.splitTerminal),o=_(z=>z.token),c=_(z=>z.toggleChat),i=_(z=>z.togglePlan),{chatOpen:d,planOpen:p}=t.panels,l=a.useRef(null),u=a.useRef(null),f=a.useRef(null),h=a.useRef(null),g=a.useRef(null),[x,R]=Xt(`plan-width-${t.id}`,50,{containerRef:u,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[C,j]=Xt(`doc-height-${t.id}`,35,{containerRef:l,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[S,w]=a.useState("");a.useEffect(()=>{if(!o||!t.connected)return;let z=!1;const L=async()=>{try{const H=await Kt(o,t.id);z||w(H)}catch{}};L();const M=setInterval(L,5e3);return()=>{z=!0,clearInterval(M)}},[o,t.id,t.connected]);const k=a.useCallback(async z=>{let L;if(o)try{L=await Kt(o,t.id)}catch{}r(t.id,z,L)},[o,t.id,r]),[A,P]=a.useState(!1),[B,$]=a.useState(0),[F,O]=a.useState(!1),[D,T]=a.useState(!1),y=async z=>{const L=z.target.files;if(!(!L||L.length===0||!o)){P(!0),$(0);try{await co(o,t.id,L,M=>{$(M)})}catch(M){alert(`Upload failed: ${M instanceof Error?M.message:"Unknown error"}`)}finally{P(!1),$(0),f.current&&(f.current.value="")}}},G=a.useRef(void 0),W=a.useCallback(z=>{if(h.current){const L=z.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(L),G.current=window.setTimeout(()=>{var M;return(M=h.current)==null?void 0:M.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{G.current&&clearTimeout(G.current)},[]);const U=a.useCallback(z=>{if(h.current){const L=z.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(L),setTimeout(()=>{var M;return(M=h.current)==null?void 0:M.sendInput("\r")},50)}},[]),V=a.useCallback(()=>T(!1),[]);return s.jsxs("div",{ref:l,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:t.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),s.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]}),S&&s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:S,children:S})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:f,type:"file",multiple:!0,style:{display:"none"},onChange:y}),s.jsx("button",{className:"pane-btn",onClick:()=>{var z;return(z=f.current)==null?void 0:z.click()},disabled:A,style:A?{color:"var(--accent-yellow)"}:void 0,title:A?`Uploading ${B}%`:"Upload files","aria-label":"Upload files",children:A?`${B}%`:"โ†‘"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>T(!0),title:"Download files","aria-label":"Download files",children:"โ†“"}),D&&o&&s.jsx(So,{token:o,sessionId:t.id,onClose:V})]}),s.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>c(t.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>i(t.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),s.jsx("button",{className:"pane-btn",onClick:()=>k(n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>k("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"โ”€"})]})]}),s.jsxs("div",{ref:u,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:`${x}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:s.jsx(xo,{sessionId:t.id,token:o||"",connected:t.connected,onRequestFileStream:z=>{var L;return(L=h.current)==null?void 0:L.requestFileStream(z)},onSendToTerminal:U})}),s.jsx("div",{className:"md-editor-divider-h",onMouseDown:R,style:{width:"2px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:z=>{z.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[s.jsx(Pr,{ref:h,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:j}),s.jsxs("div",{style:{height:`${C}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",height:"22px",flexShrink:0,backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),s.jsx("button",{className:"pane-btn",onClick:()=>{var z;return(z=g.current)==null?void 0:z.send()},disabled:!F,title:"Send to terminal (Ctrl+Enter)",style:F?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(wo,{ref:g,onSend:W,onContentChange:O,sessionId:t.id,token:o||""})})]})]})]})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--accent-red)",color:"var(--accent-red)",fontSize:"11px",flexShrink:0},children:t.error})]})});class wn extends a.Component{constructor(){super(...arguments);wt(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?s.jsxs("div",{style:{height:"100%",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"var(--text-bright)",fontFamily:"monospace",padding:"16px"},children:[s.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),s.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textAlign:"center"},children:((n=this.state.error)==null?void 0:n.message)||"An unexpected error occurred"}),s.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-bright)",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):s.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"var(--text-bright)",fontFamily:"monospace"},children:[s.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),s.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",border:"none",color:"var(--bg-primary)",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const Eo=4,Zt=10;function Io(){const e=_(o=>o.layout),t=_(o=>o.terminalIds.length),n=_(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:s.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=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(Sn,{node:e,canClose:r})})}const Sn=a.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(jo,{terminalId:t.terminalId,canClose:n}):s.jsx(Ro,{node:t,canClose:n})}),jo=a.memo(function({terminalId:t,canClose:n}){const r=_(c=>c.terminalsMap[t]),o=_(c=>c.reconnectTerminal);return r?s.jsx(wn,{inline:!0,children:s.jsx(Co,{terminal:r,canClose:n})}):s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:s.jsxs("button",{onClick:()=>o(t),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["โ†ป Reconnect ",t]})})}),Ro=a.memo(function({node:t,canClose:n}){const r=_(l=>l.setSplitSizes),o=a.useRef(null),c=t.direction==="horizontal",i=a.useRef(t.sizes);i.current=t.sizes;const d=a.useCallback((l,u)=>{u.preventDefault();const f=c?"resizing-panes":"resizing-panes-v";document.body.classList.add(f);const h=c?u.clientX:u.clientY,g=[...i.current],x=o.current,R=c?(x==null?void 0:x.clientWidth)||1:(x==null?void 0:x.clientHeight)||1;let C=null;const j=w=>{C||(C=requestAnimationFrame(()=>{C=null;const P=((c?w.clientX:w.clientY)-h)/R*100,B=g[l]+P,$=g[l+1]-P;if(B>=Zt&&$>=Zt){const F=[...g];F[l]=B,F[l+1]=$,r(t.id,F)}}))},S=()=>{C&&cancelAnimationFrame(C),document.body.classList.remove(f),document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",S)};document.addEventListener("mousemove",j),document.addEventListener("mouseup",S)},[c,t.id,r]),p=[];return t.children.forEach((l,u)=>{const f=l.type==="leaf"?l.terminalId:l.id;p.push(s.jsx("div",{style:{flex:`${t.sizes[u]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(Sn,{node:l,canClose:n})},f)),u<t.children.length-1&&p.push(s.jsx("div",{onMouseDown:h=>d(u,h),style:{flex:`0 0 ${Eo}px`,cursor:c?"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-${t.id}-${u}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:c?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function No({tabId:e}){const t=_(T=>T.tabs.find(y=>y.id===e)),n=_(T=>T.activeTabId),r=_(T=>T.switchTab),o=_(T=>T.closeTab),c=_(T=>T.reopenTab),i=_(T=>T.deleteTab),d=_(T=>T.renameTab),p=_(T=>t?t.terminalIds.map(y=>{const G=T.terminalsMap[y];return G?{id:y,connected:G.connected,active:!0}:{id:y,connected:!1,active:!1}}):[]),l=_(T=>T.disconnectTerminal),u=_(T=>T.reconnectTerminal),f=_(T=>T.killServerSession),[h,g]=a.useState(!1),[x,R]=a.useState(""),[C,j]=a.useState(!1),S=a.useRef(null);if(!t)return null;const w=n===e,k=t.status==="open",A=()=>{k&&r(e)},P=T=>{k&&(T.stopPropagation(),R(t.name),g(!0),setTimeout(()=>{var y;return(y=S.current)==null?void 0:y.focus()},0))},B=()=>{const T=x.trim();T&&d(e,T),g(!1)},$=T=>{T.stopPropagation(),c(e)},F=T=>{T.stopPropagation(),o(e)},O=async T=>{T.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await i(e)},D=T=>{T.stopPropagation(),j(!C)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:A,style:{padding:"8px 12px",cursor:k?"pointer":"default",borderLeft:w?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:w?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:k?1:.5},onMouseEnter:T=>{k&&!w&&(T.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:T=>{w||(T.currentTarget.style.backgroundColor="transparent")},children:[k&&t.terminalIds.length>0&&s.jsx("button",{onClick:D,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:C?"โ–ผ":"โ–ถ"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[h?s.jsx("input",{ref:S,value:x,onChange:T=>R(T.target.value),onBlur:B,onKeyDown:T=>{T.key==="Enter"&&B(),T.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"}}):s.jsx("div",{onDoubleClick:P,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:k?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," ยท ",yn(Math.floor(t.createdAt/1e3))]})]}),k?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:F,style:{flexShrink:0},title:"Close tab",children:"ร—"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:$,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"โ†ป"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:O,title:"Delete tab",children:"ร—"})]})]}),k&&C&&p.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(T=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${T.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:T.id}),s.jsx("span",{style:{marginLeft:"8px",color:T.active?T.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:T.active?T.connected?"โ—":"โ—":"โ—‹"}),T.active?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:y=>{y.stopPropagation(),l(T.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"ร—"}):s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:y=>{y.stopPropagation(),u(T.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"โ†ป"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:y=>{y.stopPropagation(),window.confirm(`Kill terminal "${T.id}"? This will destroy the tmux session.`)&&f(T.id)},title:"Kill session",children:"ร—"})]})]},T.id))})]})}function Lo({sessionId:e,active:t,createdAt:n}){const r=_(d=>d.addTerminal),o=_(d=>d.killServerSession),c=()=>{r("horizontal",e)},i=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};return s.jsxs("div",{onClick:c,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:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:yn(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:i,style:{flexShrink:0},title:"Delete session",children:"ร—"})]})}function Do(){const e=_(l=>l.sidebarOpen),t=_(l=>l.toggleSidebar),n=_(l=>l.fetchSessions),r=_(l=>e?l.serverSessions:[]),o=_(l=>e?l.tabs:[]),c=_(l=>l.terminalIds.length),i=_(l=>l.tabsLoading),d=new Set(o.flatMap(l=>l.terminalIds)),p=r.filter(l=>!d.has(l.sessionId));return a.useEffect(()=>{if(!e)return;n();let l=setInterval(n,5e3);const u=()=>{document.hidden?l&&(clearInterval(l),l=null):(n(),l||(l=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",u),()=>{l&&clearInterval(l),document.removeEventListener("visibilitychange",u)}},[e,n]),a.useEffect(()=>{if(!e)return;const l=setTimeout(n,800);return()=>clearTimeout(l)},[c,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:e?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"ร—"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),o.length===0?s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(l=>s.jsx(No,{tabId:l.id},l.id))]}),!i&&p.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-yellow)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid var(--border)"},children:"ORPHANED SESSIONS"}),p.map(l=>s.jsx(Lo,{sessionId:l.sessionId,active:l.active,createdAt:l.createdAt},l.sessionId))]})]})]})}const kn=bt.memo(()=>{const e=_(k=>k.tabs),t=_(k=>k.activeTabId),n=_(k=>k.addTab),r=_(k=>k.switchTab),o=_(k=>k.closeTab),c=_(k=>k.renameTab),[i,d]=a.useState(null),[p,l]=a.useState(""),u=a.useRef(null),f=e.filter(k=>k.status==="open");a.useEffect(()=>{i&&u.current&&(u.current.focus(),u.current.select())},[i]);const h=k=>{d(k.id),l(k.name)},g=()=>{i&&p.trim()&&c(i,p.trim()),d(null),l("")},x=()=>{d(null),l("")},R=k=>{k.key==="Enter"?g():k.key==="Escape"&&x()},C=k=>{i||r(k)},j=(k,A)=>{k.stopPropagation(),o(A)},S=(k,A)=>{k.button===1&&(k.preventDefault(),o(A))},w=f.length>1;return s.jsxs("div",{className:"tab-bar",children:[f.map(k=>{const A=k.id===t,P=i===k.id,B=k.terminalIds.length;return s.jsx("div",{className:`tab-item ${A?"tab-item--active":""}`,onClick:()=>C(k.id),onDoubleClick:()=>h(k),onMouseDown:$=>S($,k.id),children:P?s.jsx("input",{ref:u,type:"text",value:p,onChange:$=>l($.target.value),onBlur:g,onKeyDown:R,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[k.name," ",B>0&&`(${B})`]}),w&&s.jsx("button",{className:"tab-item__close",onClick:$=>j($,k.id),title:"Close tab","aria-label":"Close tab",children:"ร—"})]})},k.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});kn.displayName="TabBar";function Mo(){return localStorage.getItem("ai-cli-online-token")}function Ao(){const e=_(u=>u.token),t=_(u=>u.setToken),n=_(u=>u.tabs),r=_(u=>u.addTab),o=_(u=>u.toggleSidebar),c=_(u=>u.fontSize),i=_(u=>u.setFontSize),d=_(u=>u.tabsLoading),p=_(u=>u.theme),l=_(u=>u.toggleTheme);return a.useEffect(()=>{const u=Mo();u&&!e&&t(u)},[]),a.useEffect(()=>{e&&!d&&n.filter(u=>u.status==="open").length===0&&r("Default")},[e,d]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.1"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>i(c-1),disabled:c<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"Aโˆ’"}),s.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:c}),s.jsx("button",{className:"header-btn",onClick:()=>i(c+1),disabled:c>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(_o,{}),s.jsx("button",{className:"header-btn",onClick:l,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"โ˜€":"๐ŸŒ™"}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"โ˜ฐ"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Io,{})}),s.jsx(Do,{})]}),s.jsx(kn,{})]}):s.jsx(vr,{})}const zo=[1,2,3,4];function _o(){const e=_(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="var(--accent-green)",n=4):e<150?(t="var(--accent-yellow)",n=3):e<300?(t="var(--accent-orange)",n=2):(t="var(--accent-red)",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[zo.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}ft.createRoot(document.getElementById("root")).render(s.jsx(bt.StrictMode,{children:s.jsx(wn,{children:s.jsx(Ao,{})})}));
@@ -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-DjhdaelF.js"></script>
13
+ <script type="module" crossorigin src="/assets/index-D2zgyu4q.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">
package/web/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-web",
3
- "version": "2.9.9",
3
+ "version": "3.0.1",
4
4
  "description": "CLI-Online Web Frontend",
5
5
  "type": "module",
6
6
  "scripts": {