ai-cli-online 3.0.19 → 3.0.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/dist/db.d.ts +29 -0
- package/server/dist/db.js +73 -0
- package/server/dist/index.js +9 -0
- package/server/dist/routes/sessions.js +15 -1
- package/server/dist/routes/taskAuto.d.ts +4 -0
- package/server/dist/routes/taskAuto.js +302 -0
- package/server/package.json +1 -1
- package/shared/package.json +1 -1
- package/web/dist/assets/{index-BI7oV4SU.css → index-D7cmVR0X.css} +1 -1
- package/web/dist/assets/index-DG0BJZ53.js +34 -0
- package/web/dist/index.html +2 -2
- package/web/package.json +1 -1
- package/web/dist/assets/index-Kzdpgxcz.js +0 -33
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
var ir=Object.defineProperty;var lr=(t,e,n)=>e in t?ir(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qt=(t,e,n)=>lr(t,typeof e!="symbol"?e+"":e,n);import{r as o,a as cr,g as dr,R as _t}from"./react-vendor-BCIvbQoU.js";import{D as Ot,o as Ft,L as ur,x as Bt}from"./terminal-DnNpv9tw.js";import{p as Nt,g as Dn}from"./markdown-CU76q5qk.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(a){if(a.ep)return;a.ep=!0;const l=n(a);fetch(a.href,l)}})();var An={exports:{}},gt={};/**
|
|
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 fr=o,pr=Symbol.for("react.element"),mr=Symbol.for("react.fragment"),hr=Object.prototype.hasOwnProperty,gr=fr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,xr={key:!0,ref:!0,__self:!0,__source:!0};function $n(t,e,n){var r,a={},l=null,i=null;n!==void 0&&(l=""+n),e.key!==void 0&&(l=""+e.key),e.ref!==void 0&&(i=e.ref);for(r in e)hr.call(e,r)&&!xr.hasOwnProperty(r)&&(a[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)a[r]===void 0&&(a[r]=e[r]);return{$$typeof:pr,type:t,key:l,ref:i,props:a,_owner:gr.current}}gt.Fragment=mr;gt.jsx=$n;gt.jsxs=$n;An.exports=gt;var s=An.exports,Mt={},Vt=cr;Mt.createRoot=Vt.createRoot,Mt.hydrateRoot=Vt.hydrateRoot;const br={},Yt=t=>{let e;const n=new Set,r=(p,d)=>{const m=typeof p=="function"?p(e):p;if(!Object.is(m,e)){const h=e;e=d??(typeof m!="object"||m===null)?m:Object.assign({},e,m),n.forEach(g=>g(e,h))}},a=()=>e,f={setState:r,getState:a,getInitialState:()=>c,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{n.clear()}},c=e=t(r,a,f);return f},yr=t=>t?Yt(t):Yt;var zn={exports:{}},_n={},On={exports:{}},Fn={};/**
|
|
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=o;function vr(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var wr=typeof Object.is=="function"?Object.is:vr,Sr=Je.useState,kr=Je.useEffect,Cr=Je.useLayoutEffect,Tr=Je.useDebugValue;function jr(t,e){var n=e(),r=Sr({inst:{value:n,getSnapshot:e}}),a=r[0].inst,l=r[1];return Cr(function(){a.value=n,a.getSnapshot=e,Tt(a)&&l({inst:a})},[t,n,e]),kr(function(){return Tt(a)&&l({inst:a}),t(function(){Tt(a)&&l({inst:a})})},[t]),Tr(n),n}function Tt(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!wr(t,n)}catch{return!0}}function Er(t,e){return e()}var Ir=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Er:jr;Fn.useSyncExternalStore=Je.useSyncExternalStore!==void 0?Je.useSyncExternalStore:Ir;On.exports=Fn;var Rr=On.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 xt=o,Lr=Rr;function Nr(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var Mr=typeof Object.is=="function"?Object.is:Nr,Dr=Lr.useSyncExternalStore,Ar=xt.useRef,$r=xt.useEffect,zr=xt.useMemo,_r=xt.useDebugValue;_n.useSyncExternalStoreWithSelector=function(t,e,n,r,a){var l=Ar(null);if(l.current===null){var i={hasValue:!1,value:null};l.current=i}else i=l.current;l=zr(function(){function f(h){if(!c){if(c=!0,p=h,h=r(h),a!==void 0&&i.hasValue){var g=i.value;if(a(g,h))return d=g}return d=h}if(g=d,Mr(p,h))return g;var v=r(h);return a!==void 0&&a(g,v)?(p=h,g):(p=h,d=v)}var c=!1,p,d,m=n===void 0?null:n;return[function(){return f(e())},m===null?void 0:function(){return f(m())}]},[e,n,r,a]);var u=Dr(t,l[0],l[1]);return $r(function(){i.hasValue=!0,i.value=u},[u]),_r(u),u};zn.exports=_n;var Or=zn.exports;const Fr=dr(Or),Bn={},{useDebugValue:Br}=_t,{useSyncExternalStoreWithSelector:Pr}=Fr;let Xt=!1;const Wr=t=>t;function Hr(t,e=Wr,n){(Bn?"production":void 0)!=="production"&&n&&!Xt&&(Xt=!0);const r=Pr(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return Br(r),r}const Zt=t=>{const e=typeof t=="function"?yr(t):t,n=(r,a)=>Hr(e,r,a);return Object.assign(n,e),n},Ur=t=>t?Zt(t):Zt,Se="";function me(t){return{Authorization:`Bearer ${t}`}}class Ze extends Error{constructor(e,n){super(n),this.status=e,this.name="ApiError"}}function Oe(t,e){return`${Se}/api/sessions/${encodeURIComponent(t)}/${e}`}function Qt(t){return`${Se}/api/settings/${t}`}async function Xe(t){if(!t.ok){const e=await t.text().catch(()=>t.statusText);throw new Ze(t.status,e)}return t.json()}const he={async get(t,e,n,r){const a=new URL(Oe(e,n),window.location.origin);if(r)for(const[i,u]of Object.entries(r))a.searchParams.set(i,u);const l=await fetch(a.toString(),{headers:me(t)});return Xe(l)},async getOptional(t,e,n,r){const a=new URL(Oe(e,n),window.location.origin);if(r)for(const[i,u]of Object.entries(r))a.searchParams.set(i,u);const l=await fetch(a.toString(),{headers:me(t)});return l.status===304?null:Xe(l)},async post(t,e,n,r){const a=await fetch(Oe(e,n),{method:"POST",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(r)});return Xe(a)},async put(t,e,n,r){const a=await fetch(Oe(e,n),{method:"PUT",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok){const l=await a.text().catch(()=>a.statusText);throw new Ze(a.status,l)}},async putJson(t,e,n,r){const a=await fetch(Oe(e,n),{method:"PUT",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(r)});return Xe(a)},async del(t,e,n,r){const a=await fetch(Oe(e,n),{method:"DELETE",headers:{...me(t),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!a.ok){const l=await a.text().catch(()=>a.statusText);throw new Ze(a.status,l)}},async getBlob(t,e,n,r){const a=new URL(Oe(e,n),window.location.origin);if(r)for(const[i,u]of Object.entries(r))a.searchParams.set(i,u);const l=await fetch(a.toString(),{headers:me(t)});if(!l.ok)throw new Ze(l.status,"Download failed");return l}},bt={async get(t,e){const n=await fetch(Qt(e),{headers:me(t)});return Xe(n)},async put(t,e,n){const r=await fetch(Qt(e),{method:"PUT",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const a=await r.text().catch(()=>r.statusText);throw new Ze(r.status,a)}}};async function Kr(t){try{return(await bt.get(t,"font-size")).fontSize}catch{return 14}}async function Gr(t,e){try{await bt.put(t,"font-size",{fontSize:e})}catch{}}let rt=null;const Jr=(t,e)=>({fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));t({fontSize:r}),rt&&clearTimeout(rt),rt=setTimeout(()=>{rt=null;const a=e().token;a&&Gr(a,r)},500)},latency:null,setLatency:n=>t({latency:n}),theme:(()=>{try{const n=localStorage.getItem("ai-cli-online-theme");if(n==="light"||n==="dark")return n}catch{}return"dark"})(),setTheme:n=>{t({theme:n});try{localStorage.setItem("ai-cli-online-theme",n)}catch{}document.documentElement.setAttribute("data-theme",n)},toggleTheme:()=>{const n=e().theme==="dark"?"light":"dark";e().setTheme(n)},sidebarOpen:!1,toggleSidebar:()=>t(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=e().token;if(n)try{const r=await fetch(`${Se}/api/sessions`,{headers:me(n)});if(!r.ok)return;const a=await r.json();t({serverSessions:a})}catch{}}});function jt(t,e){return(n,r,a)=>{const l=r(),i=l.terminalsMap[n];if(!i)return;const u=!i.panels[t],f={...i.panels,[t]:u,...u&&e?{[e]:!1}:{}},c={...l.terminalsMap,[n]:{...i,panels:f}},p=l.tabs.find(m=>m.terminalIds.includes(n));let d=l.tabs;if(p){const m={...p.panelStates,[n]:f};d=$e(l.tabs,p.id,h=>({...h,panelStates:m}))}a({terminalsMap:c,tabs:d})}}function ct(t,e){if(t.type==="leaf")return t.terminalId===e?null:t;const n=[],r=[];for(let i=0;i<t.children.length;i++){const u=ct(t.children[i],e);u!==null&&(n.push(u),r.push(t.sizes[i]))}if(n.length===0)return null;if(n.length===1)return n[0];const a=r.reduce((i,u)=>i+u,0),l=r.map(i=>i/a*100);return{...t,children:n,sizes:l}}function Pn(t,e,n,r,a){return t.type==="leaf"?t.terminalId===e?{id:a,type:"split",direction:n,children:[t,r],sizes:[50,50]}:t:{...t,children:t.children.map(l=>Pn(l,e,n,r,a))}}function Wn(t,e,n){return t.type==="leaf"?t:t.id===e?{...t,sizes:n}:{...t,children:t.children.map(r=>Wn(r,e,n))}}function Et(t){return t.tabs.find(e=>e.id===t.activeTabId)}function $e(t,e,n){return t.map(r=>r.id===e?n(r):r)}function en(t,e){const n=t.tabs.find(c=>c.terminalIds.includes(e));if(!n){const{[e]:c,...p}=t.terminalsMap;return{terminalsMap:p}}const r=n.terminalIds.filter(c=>c!==e),a=n.layout?ct(n.layout,e):null,l=$e(t.tabs,n.id,c=>({...c,terminalIds:r,layout:a})),{[e]:i,...u}=t.terminalsMap,f={terminalsMap:u,tabs:l};return n.id===t.activeTabId&&(f.terminalIds=r,f.layout=a),f}async function qr(t){try{return(await bt.get(t,"tabs-layout")).layout}catch{return null}}async function Vr(t,e){try{await bt.put(t,"tabs-layout",{layout:e})}catch{}}function tn(t,e){try{const n=`${Se}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:t});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const Dt="ai-cli-online-tabs",nn="ai-cli-online-layout",rn="ai-cli-online-session-names";let Ie=null;function Yr(t){Ie=t,ns()}let st=null,Fe=null,Qe=null;function Xr(t){Qe=t,Fe&&clearTimeout(Fe),Fe=setTimeout(()=>{Fe=null,Qe=null;const e=Ie==null?void 0:Ie.getState().token;e&&Vr(e,t)},2e3)}function xe(t){const e={version:2,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId,tabs:t.tabs};try{localStorage.setItem(Dt,JSON.stringify(e))}catch{}Xr(e)}function Zr(t){st&&clearTimeout(st),st=setTimeout(()=>{st=null,xe(t)},500)}function pe(t){return{tabs:t.tabs,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId}}function Qr(){try{const t=localStorage.getItem(Dt);if(t){const e=JSON.parse(t);if(e.version===2)return e}}catch{}try{const t=localStorage.getItem(nn);if(t){const e=JSON.parse(t);let n="Default";try{const l=localStorage.getItem(rn);if(l){const i=JSON.parse(l),u=Object.values(i)[0];u&&(n=u)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},a={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Dt,JSON.stringify(a))}catch{}return localStorage.removeItem(nn),localStorage.removeItem(rn),a}}catch{}return null}function es(t,e){const n=new Set(e.map(i=>i.sessionId)),r=[];for(const i of t.tabs){if(i.status!=="open"){const c=i.terminalIds.filter(p=>n.has(p));if(c.length>0){let p=i.layout;for(const d of i.terminalIds)!n.has(d)&&p&&(p=ct(p,d));r.push({...i,terminalIds:c,layout:p})}continue}const u=i.terminalIds.filter(c=>n.has(c));if(u.length===0)continue;let f=i.layout;for(const c of i.terminalIds)!n.has(c)&&f&&(f=ct(f,c));r.push({...i,terminalIds:u,layout:f})}if(r.filter(i=>i.status==="open").length===0)return null;let a=t.activeTabId;if(!r.find(i=>i.id===a&&i.status==="open")){const i=r.find(u=>u.status==="open");a=(i==null?void 0:i.id)||""}return{...t,activeTabId:a,tabs:r}}async function ts(t,e){var a,l;if(!Ie)return;const{setState:n,getState:r}=Ie;try{const[i,u]=await Promise.all([qr(t),fetch(`${Se}/api/sessions`,{headers:me(t)}).then(g=>g.ok?g.json():[]).catch(()=>[])]);if(r().token!==t)return;const f=i&&((a=i.tabs)==null?void 0:a.length)>0?i:e;if(!f||f.tabs.length===0){n({tabsLoading:!1});return}const c=es(f,u);if(!c){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:f.nextId,nextSplitId:f.nextSplitId,nextTabId:f.nextTabId,terminalIds:[],layout:null});return}const p=r().terminalsMap,d={};for(const g of c.tabs)if(g.status==="open")for(const v of g.terminalIds)d[v]=p[v]||{id:v,connected:!1,sessionResumed:!1,error:null,panels:((l=g.panelStates)==null?void 0:l[v])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const m=c.tabs.find(g=>g.id===c.activeTabId&&g.status==="open")||c.tabs.find(g=>g.status==="open"),h=(m==null?void 0:m.id)||"";n({tabsLoading:!1,terminalsMap:d,tabs:c.tabs,activeTabId:h,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(m==null?void 0:m.terminalIds)||[],layout:(m==null?void 0:m.layout)||null}),xe(pe(r()))}catch{r().token===t&&n({tabsLoading:!1})}}function ns(){typeof window>"u"||!Ie||window.addEventListener("beforeunload",()=>{const t=Ie==null?void 0:Ie.getState().token;if(t)if(Qe)Fe&&(clearTimeout(Fe),Fe=null),tn(t,Qe),Qe=null;else{const e=Ie.getState();e.tabs.length>0&&tn(t,pe(e))}})}const A=Ur((...t)=>{const[e,n]=t;return{...Jr(...t),token:null,tabsLoading:!1,setToken:r=>{var a;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}Kr(r).then(i=>{n().token===r&&e({fontSize:i})});const l=Qr();if(l&&l.tabs.length>0){const i={};for(const c of l.tabs)if(c.status==="open")for(const p of c.terminalIds)i[p]={id:p,connected:!1,sessionResumed:!1,error:null,panels:((a=c.panelStates)==null?void 0:a[p])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const u=l.tabs.find(c=>c.id===l.activeTabId&&c.status==="open")||l.tabs.find(c=>c.status==="open"),f=(u==null?void 0:u.id)||"";e({token:r,tabsLoading:!0,terminalsMap:i,tabs:l.tabs,activeTabId:f,nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null})}else e({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});ts(r,l);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),e({token:r,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:r=>{const a=n(),l=`tab${a.nextTabId}`,i=`t${a.nextId}`,u={id:i,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},f={type:"leaf",terminalId:i},c={id:l,name:r||`Tab ${a.nextTabId}`,status:"open",terminalIds:[i],layout:f,createdAt:Date.now()};return e({tabs:[...a.tabs,c],activeTabId:l,nextTabId:a.nextTabId+1,nextId:a.nextId+1,terminalsMap:{...a.terminalsMap,[i]:u},terminalIds:c.terminalIds,layout:c.layout}),xe(pe(n())),l},switchTab:r=>{const l=n().tabs.find(i=>i.id===r);!l||l.status!=="open"||(e({activeTabId:r,terminalIds:l.terminalIds,layout:l.layout}),xe(pe(n())))},closeTab:r=>{const a=n(),l=a.tabs.find(m=>m.id===r);if(!l||l.status!=="open"||a.tabs.filter(m=>m.status==="open").length<=1)return;const u={...a.terminalsMap};for(const m of l.terminalIds)delete u[m];const f=$e(a.tabs,r,m=>({...m,status:"closed"}));let c=a.activeTabId,p=a.terminalIds,d=a.layout;if(a.activeTabId===r){const m=a.tabs.findIndex(v=>v.id===r),h=f.filter(v=>v.status==="open"),g=h.find(v=>f.findIndex(j=>j.id===v.id)>m)||h[h.length-1];g&&(c=g.id,p=g.terminalIds,d=g.layout)}e({tabs:f,activeTabId:c,terminalsMap:u,terminalIds:p,layout:d}),xe(pe(n()))},reopenTab:r=>{var f;const a=n(),l=a.tabs.find(c=>c.id===r);if(!l||l.status!=="closed")return;const i={...a.terminalsMap};for(const c of l.terminalIds)i[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((f=l.panelStates)==null?void 0:f[c])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}};const u=$e(a.tabs,r,c=>({...c,status:"open"}));e({tabs:u,activeTabId:r,terminalsMap:i,terminalIds:l.terminalIds,layout:l.layout}),xe(pe(n()))},deleteTab:async r=>{const a=n(),l=a.tabs.find(g=>g.id===r);if(!l)return;const i=a.token;i&&await Promise.all(l.terminalIds.map(g=>fetch(`${Se}/api/sessions/${encodeURIComponent(g)}`,{method:"DELETE",headers:me(i)}).catch(()=>{})));const u=n(),f=u.tabs.find(g=>g.id===r);if(!f)return;const c={...u.terminalsMap};for(const g of f.terminalIds)delete c[g];const p=u.tabs.filter(g=>g.id!==r);let d=u.activeTabId,m=u.terminalIds,h=u.layout;if(u.activeTabId===r){const g=p.find(v=>v.status==="open");g?(d=g.id,m=g.terminalIds,h=g.layout):(d="",m=[],h=null)}e({tabs:p,activeTabId:d,terminalsMap:c,terminalIds:m,layout:h}),xe(pe(n())),setTimeout(()=>n().fetchSessions(),500)},renameTab:(r,a)=>{const l=$e(n().tabs,r,i=>({...i,name:a}));e({tabs:l}),xe(pe(n()))},addTerminal:(r,a)=>{const l=n();if(a&&l.terminalsMap[a])return a;const i=Et(l);if(!i){const T=`tab${l.nextTabId}`,D=a||`t${l.nextId}`;let F=l.nextId;const z=D.match(/^t(\d+)$/);z&&(F=Math.max(F,parseInt(z[1],10)+1));const q=a?F:F+1,E={id:D,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},w={type:"leaf",terminalId:D},I={id:T,name:`Tab ${l.nextTabId}`,status:"open",terminalIds:[D],layout:w,createdAt:Date.now()};return e({tabs:[...l.tabs,I],activeTabId:T,nextTabId:l.nextTabId+1,nextId:q,terminalsMap:{...l.terminalsMap,[D]:E},terminalIds:[D],layout:w}),xe(pe(n())),D}const{nextId:u,nextSplitId:f,terminalsMap:c}=l,{terminalIds:p,layout:d}=i,m=a||`t${u}`;let h=u;const g=m.match(/^t(\d+)$/);g&&(h=Math.max(h,parseInt(g[1],10)+1));const v={id:m,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1}},C={type:"leaf",terminalId:m};let j,b=f;if(!d)j=C;else if(d.type==="leaf"){const T=r||"horizontal";j={id:`s${b}`,type:"split",direction:T,children:[d,C],sizes:[50,50]},b++}else if(d.direction===(r||"horizontal")){const D=100/(d.children.length+1),F=(100-D)/100,z=[...d.sizes.map(q=>q*F),D];j={...d,children:[...d.children,C],sizes:z}}else{const T=r||"horizontal";j={id:`s${b}`,type:"split",direction:T,children:[d,C],sizes:[50,50]},b++}const R=[...p,m],y=a?h:h+1,W=$e(l.tabs,i.id,T=>({...T,terminalIds:R,layout:j}));return e({terminalsMap:{...c,[m]:v},terminalIds:R,layout:j,tabs:W,nextId:y,nextSplitId:b}),xe(pe(n())),m},splitTerminal:(r,a,l)=>{const i=n(),u=Et(i);if(!u||!u.layout)return"";const{nextId:f,nextSplitId:c,terminalsMap:p}=i,d=`t${f}`,m={id:d,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1},...l?{startCwd:l}:{}},h={type:"leaf",terminalId:d},g=`s${c}`,v=Pn(u.layout,r,a,h,g),C=[...u.terminalIds,d],j=f+1,b=c+1,R=$e(i.tabs,u.id,y=>({...y,terminalIds:C,layout:v}));return e({terminalsMap:{...p,[d]:m},terminalIds:C,layout:v,tabs:R,nextId:j,nextSplitId:b}),xe(pe(n())),d},removeTerminal:r=>{const a=en(n(),r);a&&(e(a),xe(pe(n())))},disconnectTerminal:r=>{const a=n();if(!a.terminalsMap[r])return;const{[r]:i,...u}=a.terminalsMap;e({terminalsMap:u})},reconnectTerminal:r=>{var f;const a=n();if(a.terminalsMap[r])return;const l=a.tabs.find(c=>c.terminalIds.includes(r)),i=((f=l==null?void 0:l.panelStates)==null?void 0:f[r])||{chatOpen:!1,planOpen:!1,gitHistoryOpen:!1},u={id:r,connected:!1,sessionResumed:!1,error:null,panels:i};e({terminalsMap:{...a.terminalsMap,[r]:u}})},setTerminalConnected:(r,a)=>{e(l=>{const i=l.terminalsMap[r];return!i||i.connected===a?l:{terminalsMap:{...l.terminalsMap,[r]:{...i,connected:a}}}})},setTerminalResumed:(r,a)=>{e(l=>{const i=l.terminalsMap[r];return!i||i.sessionResumed===a?l:{terminalsMap:{...l.terminalsMap,[r]:{...i,sessionResumed:a}}}})},setTerminalError:(r,a)=>{e(l=>{const i=l.terminalsMap[r];return!i||i.error===a?l:{terminalsMap:{...l.terminalsMap,[r]:{...i,error:a}}}})},toggleChat:r=>{jt("chatOpen")(r,n,e),xe(pe(n()))},togglePlan:r=>{jt("planOpen","gitHistoryOpen")(r,n,e),xe(pe(n()))},toggleGitHistory:r=>{jt("gitHistoryOpen","planOpen")(r,n,e),xe(pe(n()))},setSplitSizes:(r,a)=>{const l=n(),i=Et(l);if(!i||!i.layout)return;const u=Wn(i.layout,r,a),f=$e(l.tabs,i.id,c=>({...c,layout:u}));e({layout:u,tabs:f}),Zr(pe(n()))},killServerSession:async r=>{const a=n().token;if(!a)return;try{await fetch(`${Se}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:me(a)})}catch{}const l=en(n(),r);l&&(e(l),xe(pe(n()))),setTimeout(()=>n().fetchSessions(),500)}}});Yr(A);typeof document<"u"&&document.documentElement.setAttribute("data-theme",A.getState().theme);function rs(){const[t,e]=o.useState(""),n=A(a=>a.setToken),r=a=>{a.preventDefault(),t.trim()&&n(t.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:t,onChange:a=>e(a.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:!t.trim(),style:{width:"100%",padding:"11px",background:t.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:t.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:t.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 yt=new Map;function ss(t,e,n){yt.set(t,{onChunk:e,onControl:n})}function os(t){yt.delete(t)}function as(t,e){var n;(n=yt.get(t))==null||n.onChunk(e)}function is(t,e){var n;(n=yt.get(t))==null||n.onControl(e)}const ls=1,sn=2,cs=3,ds=4,us=5,fs=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,ot=500,ps=8e3,ms=1e4,on=4e3,hs=5e3,gs=10,xs=64*1024,bs=new TextDecoder,ys=new TextEncoder;function an(t,e){const n=ys.encode(e),r=new Uint8Array(1+n.length);return r[0]=t,r.set(n,1),r.buffer}function vs(t,e,n){const r=o.useRef(null),a=o.useRef(ot),l=o.useRef(null),i=o.useRef(null),u=o.useRef(null),f=o.useRef(null),c=o.useRef(!1),p=o.useRef(n),d=o.useRef(!1),m=o.useRef(0),h=o.useRef(!0),g=o.useRef(!navigator.onLine),v=o.useRef(""),C=o.useRef(null),j=o.useRef(""),b=o.useRef(null);p.current=n;const R=o.useCallback(()=>{i.current&&(clearInterval(i.current),i.current=null),u.current&&(clearTimeout(u.current),u.current=null),l.current&&(clearTimeout(l.current),l.current=null),f.current&&(clearTimeout(f.current),f.current=null),C.current&&(clearTimeout(C.current),C.current=null)},[]),y=o.useCallback(()=>{var U;const{token:E,setTerminalError:w}=A.getState();if(!E||c.current)return;if(r.current){const Z=r.current.readyState;if(Z===WebSocket.OPEN||Z===WebSocket.CONNECTING)return}d.current=!1;const I=(U=A.getState().terminalsMap[e])==null?void 0:U.startCwd;let X=`${fs}?sessionId=${encodeURIComponent(e)}`;I&&(X+=`&cwd=${encodeURIComponent(I)}`);const B=new WebSocket(X);B.binaryType="arraybuffer",f.current=window.setTimeout(()=>{B.readyState===WebSocket.CONNECTING&&B.close()},hs);const G=()=>{B.readyState===WebSocket.OPEN&&(m.current=performance.now(),B.send(JSON.stringify({type:"ping"})),u.current=window.setTimeout(()=>{m.current>0&&(m.current=0,B.close())},on))};B.onopen=()=>{f.current&&(clearTimeout(f.current),f.current=null),B.send(JSON.stringify({type:"auth",token:E})),w(e,null),a.current=ot,h.current=!0},B.onclose=Z=>{const{setTerminalConnected:ae,setTerminalError:_,setToken:N}=A.getState();if(ae(e,!1),R(),d.current)return;if(Z.code===4001){c.current=!0,_(e,"Authentication failed"),N(null),localStorage.removeItem("ai-cli-online-token");return}if(Z.code===4002)return;if(Z.code===4005){_(e,"Connection limit reached");return}if(!navigator.onLine){g.current=!0;return}if(h.current){h.current=!1,l.current=window.setTimeout(()=>y(),50);return}const H=a.current;a.current=Math.min(H*2,ps);const O=Math.round(H*(.5+Math.random()));l.current=window.setTimeout(()=>{y()},O)},B.onerror=()=>{},B.onmessage=Z=>{var ae,_;try{const N=t.current;if(Z.data instanceof ArrayBuffer){const O=new Uint8Array(Z.data);if(O.length<1)return;const V=O[0],ce=O.subarray(1);switch(V){case ls:N==null||N.write(ce),(ae=b.current)==null||ae.call(b,ce);break;case cs:N==null||N.write(ce);break;case ds:{(_=p.current)==null||_.call(p,bs.decode(ce));break}case us:{as(e,ce);break}}return}const H=JSON.parse(Z.data);switch(H.type){case"connected":{const O=A.getState();O.setTerminalConnected(e,!0),O.setTerminalResumed(e,H.resumed);const V=t.current;V&&B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"resize",cols:V.cols,rows:V.rows})),j.current&&(B.send(an(sn,j.current)),j.current=""),G(),i.current=window.setInterval(G,ms);break}case"error":A.getState().setTerminalError(e,H.error);break;case"pong":{if(u.current&&(clearTimeout(u.current),u.current=null),m.current>0){const O=Math.round(performance.now()-m.current),V=A.getState();(V.terminalIds.length===0||V.terminalIds[0]===e)&&V.setLatency(O),m.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":is(e,H);break}}catch{}},r.current=B},[e,t,R]),W=o.useCallback(E=>{const w=r.current;if(!w||w.readyState!==WebSocket.OPEN){j.current.length<xs&&(j.current+=E);return}v.current+=E,C.current||(C.current=window.setTimeout(()=>{const I=v.current;v.current="",C.current=null,I&&w.readyState===WebSocket.OPEN&&w.send(an(sn,I))},gs))},[]),T=o.useCallback((E,w)=>{var I;((I=r.current)==null?void 0:I.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:E,rows:w}))},[]),D=o.useCallback(()=>{var E;((E=r.current)==null?void 0:E.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),F=o.useCallback(E=>{var w;((w=r.current)==null?void 0:w.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:E}))},[]),z=o.useCallback(()=>{var E;((E=r.current)==null?void 0:E.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]),q=o.useCallback(E=>{b.current=E},[]);return o.useEffect(()=>{A.getState().token&&(c.current=!1,y());const w=()=>{g.current=!1,a.current=ot,h.current=!0;const B=r.current;(!B||B.readyState===WebSocket.CLOSED||B.readyState===WebSocket.CLOSING)&&y()},I=()=>{g.current=!0},X=()=>{if(document.visibilityState!=="visible")return;const B=r.current;if(!B||B.readyState!==WebSocket.OPEN){!g.current&&!d.current&&(a.current=ot,h.current=!0,y());return}m.current=performance.now(),B.send(JSON.stringify({type:"ping"})),u.current&&clearTimeout(u.current),u.current=window.setTimeout(()=>{m.current>0&&(m.current=0,B.close())},on)};return window.addEventListener("online",w),window.addEventListener("offline",I),document.addEventListener("visibilitychange",X),()=>{d.current=!0,R(),window.removeEventListener("online",w),window.removeEventListener("offline",I),document.removeEventListener("visibilitychange",X),r.current&&(r.current.close(),r.current=null)}},[y,R,e]),{sendInput:W,sendResize:T,requestScrollback:D,requestFileStream:F,cancelFileStream:z,setOutputMirror:q}}function ws(t){const e=o.useRef(null),n=o.useRef(null),r=o.useRef(t);r.current=t;const a=o.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null),e.current&&(e.current.remove(),e.current=null)},[]),l=o.useCallback((i,u)=>{a();const f=document.createElement("div");f.style.cssText=`position:fixed;left:${i}px;top:${u}px;z-index:1000;display:flex;align-items:center;gap:4px;padding:4px 6px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.4);font-family:inherit;`;const c=document.createElement("textarea");c.style.cssText="width:90px;height:22px;resize:none;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-size:11px;font-family:inherit;padding:2px 4px;outline:none;",c.placeholder="Ctrl+V",c.addEventListener("paste",p=>{var m;p.preventDefault();const d=(m=p.clipboardData)==null?void 0:m.getData("text/plain");d&&r.current(d),a()}),c.addEventListener("keydown",p=>{p.key==="Escape"&&a()}),f.appendChild(c),document.body.appendChild(f),e.current=f,requestAnimationFrame(()=>{const p=f.getBoundingClientRect();p.right>window.innerWidth&&(f.style.left=`${window.innerWidth-p.width-8}px`),p.bottom>window.innerHeight&&(f.style.top=`${window.innerHeight-p.height-8}px`),c.focus()}),n.current=setTimeout(a,8e3)},[a]);return o.useEffect(()=>{const i=()=>{e.current&&a()};return document.addEventListener("click",i),()=>{document.removeEventListener("click",i),a()}},[a]),{showPasteFloat:l,removePasteFloat:a}}const dt={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"},ut={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"},Hn="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",Ss=o.forwardRef(function({sessionId:e},n){const r=o.useRef(null),a=o.useRef(null),l=o.useRef(null),[i,u]=o.useState(!1),[f,c]=o.useState(""),p=A(T=>T.fontSize),d=A(T=>T.theme),m=o.useCallback(T=>{c(T),u(!0)},[]),{sendInput:h,sendResize:g,requestScrollback:v,requestFileStream:C,cancelFileStream:j,setOutputMirror:b}=vs(a,e,m);o.useImperativeHandle(n,()=>({sendInput:h,requestFileStream:C,cancelFileStream:j,setOutputMirror:b}),[h,C,j,b]);const R=o.useRef(h),y=o.useRef(g);R.current=h,y.current=g;const{removePasteFloat:W}=ws(T=>R.current(T));return o.useEffect(()=>{if(!r.current)return;let T=!1,D=null,F=null,z=null,q=null;if(T||!r.current)return;const E=new Ot({cursorBlink:!0,scrollback:1e4,fontSize:A.getState().fontSize,fontFamily:Hn,theme:A.getState().theme==="dark"?dt:ut,allowProposedApi:!0}),w=new Ft;E.loadAddon(w),E.loadAddon(new ur((_,N)=>{window.open(N,"_blank","noopener,noreferrer")})),E.open(r.current);try{const _=new Bt;_.onContextLoss(()=>{_.dispose()}),E.loadAddon(_)}catch{}a.current=E,l.current=w,E.onSelectionChange(()=>{const _=E.getSelection();_&&navigator.clipboard.writeText(_).catch(()=>{})});const I=E.element,X=_=>{var N;_.preventDefault(),W(),(N=navigator.clipboard)!=null&&N.readText&&navigator.clipboard.readText().then(H=>{H&&R.current(H)}).catch(()=>{})};I&&I.addEventListener("contextmenu",X);const B=()=>{try{const _=r.current;if(_&&_.clientWidth>0&&_.clientHeight>0)return w.fit(),y.current(E.cols,E.rows),!0}catch{}return!1};requestAnimationFrame(()=>B());let G=0;D=setInterval(()=>{G++,(B()||G>=10)&&(clearInterval(D),D=null)},100),document.fonts.ready.then(()=>{if(!T)try{w.fit(),y.current(E.cols,E.rows)}catch{}});let U=null;const Z=()=>{T||(U&&clearTimeout(U),U=setTimeout(()=>{if(!T)try{w.fit(),y.current(E.cols,E.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",Z),E.onData(_=>{R.current(_)});let ae=!1;return q=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!ae){ae=!0;const N=()=>{document.removeEventListener("mouseup",N),ae=!1,requestAnimationFrame(()=>{try{w.fit(),y.current(E.cols,E.rows)}catch{}})};document.addEventListener("mouseup",N)}return}F||(F=requestAnimationFrame(()=>{F=null;try{w.fit(),z&&clearTimeout(z),z=setTimeout(()=>{z=null,y.current(E.cols,E.rows)},50)}catch{}}))}),q.observe(r.current),()=>{T=!0,D&&clearInterval(D),F&&cancelAnimationFrame(F),z&&clearTimeout(z),U&&clearTimeout(U),document.fonts.removeEventListener("loadingdone",Z),q&&q.disconnect(),W(),I&&I.removeEventListener("contextmenu",X),a.current&&(a.current.dispose(),a.current=null),l.current=null}},[e]),o.useEffect(()=>{const T=a.current,D=l.current;if(!(!T||!D)&&T.options.fontSize!==p){T.options.fontSize=p;try{D.fit()}catch{}y.current(T.cols,T.rows)}},[p]),o.useEffect(()=>{a.current&&(a.current.options.theme=d==="dark"?dt:ut)},[d]),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:T=>{T.currentTarget.blur(),i?(u(!1),c("")):v()},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:T=>{T.currentTarget.style.opacity="1"},onMouseLeave:T=>{T.currentTarget.style.opacity="0.8"},children:i?"✕":s.jsx("span",{style:{fontSize:14},children:"👁"})}),i&&s.jsx(ks,{data:f,onClose:()=>{u(!1),c("")}})]})});function ks({data:t,onClose:e}){const n=o.useRef(null),r=o.useRef(e);r.current=e;const a=A(c=>c.fontSize),l=A(c=>c.theme),i=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!n.current)return;const c=new Ot({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:a,fontFamily:Hn,theme:l==="dark"?dt:ut});i.current=c;const p=new Ft;u.current=p,c.loadAddon(p),c.open(n.current);let d=null;try{d=new Bt,d.onContextLoss(()=>{d==null||d.dispose(),d=null}),c.loadAddon(d)}catch{d=null}c.onSelectionChange(()=>{const j=c.getSelection();j&&navigator.clipboard.writeText(j).catch(()=>{})}),c.attachCustomKeyEventHandler(j=>(j.key==="Escape"&&r.current(),!1)),c.write(t);let m=null;const h=()=>{const j=n.current;if(!j||j.clientWidth<=0||j.clientHeight<=0)return!1;try{return p.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!h()){let j=0;m=setInterval(()=>{j++,(h()||j>=30)&&(clearInterval(m),m=null)},50)}});let g=null;const v=new ResizeObserver(()=>{g||(g=requestAnimationFrame(()=>{g=null,h()}))});v.observe(n.current);const C=j=>{j.key==="Escape"&&r.current()};return document.addEventListener("keydown",C),()=>{if(m&&clearInterval(m),g&&cancelAnimationFrame(g),document.removeEventListener("keydown",C),v.disconnect(),d){try{d.dispose()}catch{}d=null}c.dispose(),i.current=null,u.current=null}},[t]),o.useEffect(()=>{var c;if(i.current){i.current.options.fontSize=a;try{(c=u.current)==null||c.fit()}catch{}}},[a]),o.useEffect(()=>{i.current&&(i.current.options.theme=l==="dark"?dt:ut)},[l]);const f=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[s.jsx("div",{style:{height:f,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:f,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const Cs=50;function At(){const t=o.useRef([]),e=o.useCallback(a=>{t.current.push(a),t.current.length>Cs&&t.current.shift()},[]),n=o.useCallback(()=>t.current.pop(),[]),r=o.useCallback(()=>{t.current=[]},[]);return o.useMemo(()=>({pushUndo:e,popUndo:n,clearUndo:r}),[e,n,r])}function $t(t,e,n){t.preventDefault();const r=t.currentTarget,a=r.selectionStart,l=r.selectionEnd,i=r.value;n==null||n(i);const u=i.slice(0,a)+" "+i.slice(l);e(u),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=a+2})}function ft(t,e=20){var n;return Math.min(e,Math.max(1,(((n=t.match(/\n/g))==null?void 0:n.length)??0)+1))}let Ue=null,Un="dark";const Ts=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],js={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"},Es={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"},Is={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function ln(t,e){return Un=e,t.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?js:Es,gantt:Is}),t}function Rs(t="dark"){return Ue?Un!==t?Ue.then(e=>ln(e,t)):Ue:(Ue=(async()=>{for(const e of Ts)try{const n=await import(e);return ln(n.default,t)}catch{}throw Ue=null,new Error("All mermaid CDN sources failed")})(),Ue)}let cn=0;function Ls(t,e,n="dark"){const r=o.useRef(n);o.useEffect(()=>{const a=t.current;if(!a)return;const l=r.current!==n;r.current=n;const i=a.querySelectorAll("code.language-mermaid, code.language-gantt"),u=l?a.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(i.length===0&&u.length===0)return;let f=!1;return(async()=>{let c;try{c=await Rs(n)}catch{if(f)return;for(const d of i){const m=d.parentElement;if(!m||m.tagName!=="PRE")continue;m.classList.add("mermaid-error");const h=document.createElement("div");h.className="mermaid-error__msg",h.textContent="Failed to load Mermaid library",m.appendChild(h)}return}if(!f){for(const p of u){if(f)break;const d=p.getAttribute("data-mermaid-source");if(!d)continue;const m=`mermaid-${++cn}`;try{const{svg:h}=await c.render(m,d);if(f)break;p.innerHTML=Nt.sanitize(h,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const p of i){if(f)break;const d=p.parentElement;if(!d||d.tagName!=="PRE")continue;const m=p.textContent||"";if(!m.trim())continue;const h=`mermaid-${++cn}`;try{const{svg:g}=await c.render(h,m);if(f)break;const v=document.createElement("div");v.className="mermaid-diagram",v.setAttribute("data-mermaid-source",m),v.innerHTML=Nt.sanitize(g,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),d.replaceWith(v)}catch{if(f)break;d.classList.add("mermaid-error");const g=document.createElement("div");g.className="mermaid-error__msg",g.textContent="Mermaid syntax error",d.appendChild(g)}}}})(),()=>{f=!0}},[e,n])}async function Ns(t,e,n){const r=await he.get(t,e,"annotations",{path:n});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function Kn(t,e,n,r,a){await he.put(t,e,"annotations",{path:n,content:r,updatedAt:a})}async function dn(t,e,n,r){return he.post(t,e,"task-annotations",{modulePath:n,content:r})}const zt={additions:[],deletions:[],replacements:[],comments:[]};let Ms=0;function je(){return`ann_${++Ms}_${Date.now()}`}function et(t,e){return`plan-annotations-${t}-${e}`}function un(t,e){return`plan-scroll-${t}-${e}`}function Ds(t){const e=String(Dn.parser([t],{async:!1}));return Nt.sanitize(e,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function at(t,e){let n=1;for(let r=0;r<e&&r<t.length;r++){const a=t[r].raw??"";for(const l of a)l===`
|
|
26
|
+
`&&n++}return n}function it(t,e,n,r){const a=t.join(`
|
|
27
|
+
`);let l=0;for(let h=0;h<e-1&&h<t.length;h++)l+=t[h].length+1;let i=0;for(let h=0;h<n&&h<t.length;h++)i+=t[h].length+1;let u=l,f=Math.min(a.length,i);if(r){const h=Math.max(0,l-10),g=Math.min(a.length,i+10),C=a.slice(h,g).indexOf(r);C>=0&&(u=h+C,f=u+r.length)}const c=Math.max(0,u-20),p=a.slice(c,u).replace(/\n/g,"↵"),d=Math.min(a.length,f+20),m=a.slice(f,d).replace(/\n/g,"↵");return{before:p,after:m}}function fn(t,e){const n=[],r=[],a=[],l=[];for(const i of t.additions){const{before:u,after:f}=it(e,i.sourceLine,i.sourceLine);n.push([`Line${i.sourceLine}:...${u}`,i.content,`${f}...`])}for(const i of t.deletions){const{before:u,after:f}=it(e,i.startLine,i.endLine,i.selectedText);r.push([`Line${i.startLine}:...${u}`,i.selectedText,`${f}...`])}for(const i of t.replacements){const{before:u,after:f}=it(e,i.startLine,i.endLine,i.selectedText);a.push([`Line${i.startLine}:...${u}`,i.selectedText,i.content,`${f}...`])}for(const i of t.comments){const{before:u,after:f}=it(e,i.startLine,i.endLine,i.selectedText);l.push([`Line${i.startLine}:...${u}`,i.selectedText,i.content,`${f}...`])}return{"Insert Annotations":n,"Delete Annotations":r,"Replace Annotations":a,"Comment Annotations":l}}function pn(t){return t.additions.length>0||t.deletions.length>0||t.replacements.length>0||t.comments.length>0}function mn(t){return/^[a-zA-Z0-9_./:@=-]+$/.test(t)?t:"'"+t.replace(/'/g,"'\\''")+"'"}function hn(t,e){return`/moonview:annotate ${mn(t)} ${mn(e)} --silent`}function gn(t){const e=t.split("/"),n=e.indexOf("AiTasks");return n>=0&&n+1<e.length?e.slice(0,n+2).join("/"):t.substring(0,t.lastIndexOf("/"))}function pt(t){const e=new Set;return t.additions.forEach(n=>e.add(n.id)),t.deletions.forEach(n=>e.add(n.id)),t.replacements.forEach(n=>e.add(n.id)),t.comments.forEach(n=>e.add(n.id)),e}function xn(t){return t.replacements||(t.replacements=[]),t.comments||(t.comments=[]),t}function As({sessionId:t,filePath:e,token:n,annotations:r,annLoadedRef:a,setAnnotations:l,baselineIdsRef:i}){const u=A(d=>d.latency),f=o.useRef(void 0),c=o.useRef(void 0),p=o.useRef(!1);o.useEffect(()=>{if(!a.current)return;const d=et(t,e),m=JSON.stringify(r);f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{try{localStorage.setItem(d,m)}catch{}},50),c.current&&clearTimeout(c.current);const h=Math.max(200,(u??30)*3);return c.current=setTimeout(()=>{p.current||(p.current=!0,Kn(n,t,e,m,Date.now()).catch(()=>{}).finally(()=>{p.current=!1}))},h),()=>{f.current&&clearTimeout(f.current),c.current&&clearTimeout(c.current)}},[r,t,e,n,u,a]),o.useEffect(()=>{a.current=!1;let d=zt,m=0;try{const g=localStorage.getItem(et(t,e));g&&(d=xn(JSON.parse(g)),m=Date.now())}catch{}l(d),i.current=pt(d);let h=!1;return Ns(n,t,e).then(g=>{if(!h&&g&&g.updatedAt>m)try{const v=xn(JSON.parse(g.content));l(v);try{localStorage.setItem(et(t,e),g.content)}catch{}i.current=pt(v)}catch{}}).catch(()=>{}).finally(()=>{a.current=!0}),a.current=!0,()=>{h=!0}},[t,e,n,a,l,i])}async function lt(t,e,n,r){const a={path:n};return r&&(a.since=String(r)),he.getOptional(t,e,"file-content",a)}async function bn(t,e,n,r){return he.putJson(t,e,"file-content",{path:n,content:r})}function Gn(t,e){let n=t.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");n||(n="heading");const r=e.get(n)||0;return r>0&&(n=`${n}-${r}`),e.set(n,r+1),n}function Jn(t){return t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function $s(t){if(!t)return[];const e=[],n=new Map,r=t.split(`
|
|
28
|
+
`);let a=!1;for(const l of r){if(/^```/.test(l.trim())){a=!a;continue}if(a)continue;const i=l.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(i){const u=i[1].length,f=Jn(i[2]),c=Gn(f,n);e.push({id:c,text:f,level:u})}}return e}const zs=160,_s=22;function Os({headings:t,scrollRef:e}){const[n,r]=o.useState(null),[a,l]=o.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),i=o.useRef(null),u=o.useRef(!1),f=o.useMemo(()=>Math.min(...t.map(d=>d.level)),[t]),c=o.useCallback(()=>{l(d=>{const m=!d;try{localStorage.setItem("md-toc-collapsed",String(m))}catch{}return m})},[]);o.useEffect(()=>{const d=e.current;if(!d||t.length===0)return;const m=()=>{u.current=!1;const g=d.scrollTop,v=50;let C=null;for(const j of t){const b=d.querySelector(`[id="${CSS.escape(j.id)}"]`);b&&b.offsetTop<=g+v&&(C=j.id)}r(C)},h=()=>{u.current||(u.current=!0,requestAnimationFrame(m))};return m(),d.addEventListener("scroll",h,{passive:!0}),()=>d.removeEventListener("scroll",h)},[t,e]);const p=o.useCallback(d=>{const m=e.current;if(!m)return;const h=m.querySelector(`[id="${CSS.escape(d)}"]`);h&&(h.scrollIntoView({behavior:"smooth",block:"start"}),r(d))},[e]);return o.useEffect(()=>{if(!n||a)return;const d=i.current;if(!d)return;const m=d.querySelector(`[data-toc-id="${CSS.escape(n)}"]`);if(m){const h=m.offsetTop-d.offsetTop,g=h+m.offsetHeight;(h<d.scrollTop||g>d.scrollTop+d.clientHeight)&&m.scrollIntoView({block:"nearest"})}},[n,a]),t.length<2?null:a?s.jsx("div",{style:{width:_s,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{onClick:c,title:"Show table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:13,cursor:"pointer",padding:"2px",lineHeight:1},onMouseEnter:d=>{d.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:d=>{d.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):s.jsxs("div",{ref:i,style:{width:zs,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),s.jsx("button",{onClick:c,title:"Hide table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:"0 2px",lineHeight:1},onMouseEnter:d=>{d.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:d=>{d.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:t.map((d,m)=>s.jsx("div",{"data-toc-id":d.id,onClick:()=>p(d.id),style:{padding:`2px 6px 2px ${(d.level-f)*10+6}px`,fontSize:11,lineHeight:1.5,color:n===d.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:n===d.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:d.level<=2?500:400,transition:"color 0.1s"},title:d.text,onMouseEnter:h=>{n!==d.id&&(h.currentTarget.style.color="var(--text-primary)"),h.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:h=>{n!==d.id&&(h.currentTarget.style.color="var(--text-secondary)"),h.currentTarget.style.backgroundColor="transparent"},children:d.text},`${d.id}-${m}`))})]})}const Fs={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 Bs({annotations:t,annCounts:e,isSent:n,onSendAll:r,onSendSingle:a,onDelete:l}){const[i,u]=o.useState(!1),f=o.useRef(null);o.useEffect(()=>{if(!i)return;const d=m=>{f.current&&!f.current.contains(m.target)&&u(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[i]);const c=o.useCallback((d,m,h)=>{const g=Fs[m],v=n(d);return s.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${m}`,children:[s.jsx("span",{className:"plan-anno-dropdown__type",style:{color:g.color},children:g.symbol}),s.jsxs("span",{className:"plan-anno-dropdown__text",children:[h.slice(0,60),h.length>60?"...":""]}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!v&&a(d,m),disabled:v,title:v?"Already sent":"Send to terminal",style:v?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(d,m),title:"Delete",children:"×"})]},d)},[n,a,l]),p=(()=>{const d=t.additions[0],m=t.deletions[0],h=t.replacements[0],g=t.comments[0],v=d?d.content:m?m.selectedText:h?h.content:g?g.content:"";return v?v.slice(0,40)+(v.length>40?"...":""):""})();return s.jsxs("div",{ref:f,style:{position:"relative",flex:1,minWidth:0},children:[s.jsxs("div",{className:`plan-anno-dropdown-trigger${i?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>u(d=>!d),title:e.total>0?`${e.total} annotations (${e.unsent} unsent)`:"No annotations",children:[s.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:p}),s.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),i&&s.jsxs("div",{className:"plan-anno-dropdown",children:[e.unsent>0&&s.jsx("div",{className:"plan-anno-dropdown__header",children:s.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",e.unsent,")"]})}),s.jsxs("div",{className:"plan-anno-dropdown__list",children:[t.additions.map(d=>c(d.id,"add",d.content)),t.deletions.map(d=>c(d.id,"del",d.selectedText)),t.replacements.map(d=>c(d.id,"rep",d.content)),t.comments.map(d=>c(d.id,"com",d.content)),e.total===0&&s.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const Ps={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 It({type:t,annotation:e,fontSize:n,onEdit:r,onRemove:a,onSend:l,isSent:i}){const u=Ps[t],[f,c]=o.useState(!1),[p,d]=o.useState(""),m=o.useRef(null),h=t==="del"?e.selectedText:e.content,g=o.useCallback(()=>{c(!0),d(h)},[h]),v=o.useCallback(()=>{const C=p.trim();C?r(e.id,C):a(e.id),c(!1)},[p,e.id,r,a]);return o.useEffect(()=>{f&&requestAnimationFrame(()=>{const C=m.current;C&&(C.focus(),C.selectionStart=C.selectionEnd=C.value.length)})},[f]),f?s.jsx("div",{className:u.className,children:s.jsx("textarea",{ref:m,className:"plan-annotation-textarea",value:p,onChange:C=>d(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.ctrlKey||C.metaKey)&&(C.preventDefault(),v()),C.key==="Escape"&&(C.preventDefault(),c(!1))},onBlur:v,rows:ft(p),style:{fontSize:`${n}px`,flex:1}})}):s.jsxs("div",{className:u.className,children:[u.icon&&s.jsx("span",{style:{color:u.color,flexShrink:0},children:u.icon}),t==="del"?s.jsx("span",{style:{flex:1,fontSize:`${n}px`,color:u.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:g,title:"Double-click to edit",children:e.selectedText}):t==="rep"?s.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:g,title:"Double-click to edit",children:[s.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:e.selectedText}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),s.jsx("span",{style:{color:"var(--accent-blue)"},children:e.content})]}):s.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:g,title:"Double-click to edit",children:[s.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',e.selectedText,'"']}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),s.jsx("span",{style:{color:"var(--accent-green)"},children:e.content})]}),l&&s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!i&&l(e.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:g,style:{color:"var(--accent-blue)"},title:`Edit ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>a(e.id),title:`Remove ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"×"})]})}function Ws({x:t,y:e,onDelete:n,onReplace:r,onComment:a}){return s.jsxs("div",{className:"plan-selection-float",style:{top:e,left:t},children:[s.jsx("button",{className:"plan-selection-float__delete",onMouseDown:l=>{l.preventDefault(),n()},title:"Delete selection",children:"−"}),s.jsx("button",{className:"plan-selection-float__replace",onMouseDown:l=>{l.preventDefault(),r()},title:"Replace selection",children:"⇄"}),s.jsx("button",{className:"plan-selection-float__comment",onMouseDown:l=>{l.preventDefault(),a()},title:"Comment on selection",children:"?"})]})}const Hs=o.forwardRef(function({markdown:e,filePath:n,sessionId:r,token:a,onExecute:l,onSend:i,onRefresh:u,onClose:f,onContentSaved:c,expanded:p,readOnly:d},m){const h=A(x=>x.fontSize),[g,v]=o.useState(null),C=o.useRef(void 0),j=o.useCallback((x,S)=>{clearTimeout(C.current),v({type:x,msg:S}),C.current=setTimeout(()=>v(null),x==="ok"?2500:5e3)},[]);o.useEffect(()=>()=>clearTimeout(C.current),[]);const[b,R]=o.useState(!1),[y,W]=o.useState(""),[T,D]=o.useState(!1),F=o.useRef(null),z=A(x=>x.latency),q=`plan-edit:${r}:${n}`,E=o.useRef(void 0),w=o.useRef(void 0),I=o.useRef(!1);o.useEffect(()=>{if(!b)return;clearTimeout(E.current),E.current=setTimeout(()=>{try{localStorage.setItem(q,y)}catch{}},50),clearTimeout(w.current);const x=Math.max(200,(z??30)*3);return w.current=setTimeout(()=>{I.current||(I.current=!0,bn(a,r,n,y).then(S=>{c==null||c(y,S.mtime)}).catch(()=>{}).finally(()=>{I.current=!1}))},x),()=>{clearTimeout(E.current),clearTimeout(w.current)}},[y,b,q,a,r,n,z,c]),o.useEffect(()=>{R(!1)},[n]),o.useEffect(()=>{b&&requestAnimationFrame(()=>{var x;return(x=F.current)==null?void 0:x.focus()})},[b]);const X=o.useCallback(()=>{if(d||b)return;const x=localStorage.getItem(`plan-edit:${r}:${n}`);W(x??e),R(!0)},[d,b,e,r,n]),B=o.useCallback(()=>{R(!1),W(""),localStorage.removeItem(`plan-edit:${r}:${n}`)},[r,n]),G=o.useCallback(async()=>{if(!T){D(!0);try{const x=await bn(a,r,n,y);c==null||c(y,x.mtime),R(!1),W(""),localStorage.removeItem(`plan-edit:${r}:${n}`),j("ok","Saved")}catch(x){const S=x instanceof Error?x.message:"Failed to save";j("err",S)}finally{D(!1)}}},[T,a,r,n,y,c,j]),U=o.useMemo(()=>e?Dn.lexer(e):[],[e]),Z=o.useMemo(()=>e.split(`
|
|
29
|
+
`),[e]),ae=o.useMemo(()=>$s(e),[e]),_=o.useMemo(()=>{const x=new Map,S=new Map;return U.forEach(($,M)=>{if($.type==="heading"){const oe=Jn($.text||""),ee=Gn(oe,S);x.set(M,ee)}}),x},[U]),N=o.useRef(new Set),H=o.useRef(!1),[O,V]=o.useState(()=>{try{const x=localStorage.getItem(et(r,n)),S=x?JSON.parse(x):zt;return N.current=pt(S),S.replacements||(S.replacements=[]),S.comments||(S.comments=[]),S}catch{return zt}});As({sessionId:r,filePath:n,token:a,annotations:O,annLoadedRef:H,setAnnotations:V,baselineIdsRef:N});const[ce,P]=o.useState(0),J=o.useMemo(()=>{const x=N.current,S=O.additions.length+O.deletions.length+O.replacements.length+O.comments.length;let $=0;return O.additions.forEach(M=>{x.has(M.id)&&$++}),O.deletions.forEach(M=>{x.has(M.id)&&$++}),O.replacements.forEach(M=>{x.has(M.id)&&$++}),O.comments.forEach(M=>{x.has(M.id)&&$++}),{total:S,sent:$,unsent:S-$}},[O,ce]),[Y,te]=o.useState(null),[Q,se]=o.useState(""),ye=o.useRef(null),[ne,ke]=o.useState(null),[Re,Le]=o.useState(""),_e=o.useRef(null),[de,Ce]=o.useState(null),ge=o.useRef(null),qe=o.useRef(0),Be=o.useRef(null);o.useEffect(()=>{const x=ge.current;if(!x)return;let S;const $=()=>{clearTimeout(S),S=setTimeout(()=>{const M=un(r,n);if(x.scrollTop>0)try{localStorage.setItem(M,String(x.scrollTop))}catch{}else localStorage.removeItem(M)},50)};return x.addEventListener("scroll",$,{passive:!0}),()=>{clearTimeout(S),x.removeEventListener("scroll",$)}},[r,n]),o.useEffect(()=>{if(!U.length)return;const x=localStorage.getItem(un(r,n));if(!x)return;const S=Number(x),$=ge.current;if(!$||($.scrollTop=S,$.scrollTop>=S-10))return;let M;const oe=()=>{$.scrollTop=S,ee.disconnect()},ee=new MutationObserver(()=>{clearTimeout(M),M=setTimeout(oe,80)});ee.observe($,{childList:!0,subtree:!0});const le=setTimeout(oe,500);return()=>{clearTimeout(M),clearTimeout(le),ee.disconnect()}},[r,n,U.length]),o.useEffect(()=>{Y!=null&&requestAnimationFrame(()=>{var x;return(x=ye.current)==null?void 0:x.focus()})},[Y]),o.useEffect(()=>{ne&&requestAnimationFrame(()=>{var x;return(x=_e.current)==null?void 0:x.focus()})},[ne]);const Pe=o.useRef({annotations:O,activeInsert:Y,insertText:Q,pendingAction:ne,pendingText:Re,tokens:U,filePath:n,sessionId:r,token:a});Pe.current={annotations:O,activeInsert:Y,insertText:Q,pendingAction:ne,pendingText:Re,tokens:U,filePath:n,sessionId:r,token:a},o.useEffect(()=>()=>{const x=Pe.current;let S=x.annotations,$=!1;if(x.activeInsert!=null&&x.insertText.trim()){const M=at(x.tokens,x.activeInsert+1);S={...S,additions:[...S.additions,{id:je(),afterTokenIndex:x.activeInsert,sourceLine:M,content:x.insertText.trim()}]},$=!0}if(x.pendingAction&&x.pendingText.trim()){const M=x.pendingAction,oe=x.pendingText.trim();M.type==="replace"?S={...S,replacements:[...S.replacements,{id:je(),tokenIndices:M.tokenIndices,startLine:M.startLine,endLine:M.endLine,selectedText:M.text,content:oe}]}:S={...S,comments:[...S.comments,{id:je(),tokenIndices:M.tokenIndices,startLine:M.startLine,endLine:M.endLine,selectedText:M.text,content:oe}]},$=!0}if($){const M=JSON.stringify(S);try{localStorage.setItem(et(x.sessionId,x.filePath),M)}catch{}Kn(x.token,x.sessionId,x.filePath,M,Date.now()).catch(()=>{})}},[]);const De=o.useCallback(x=>{if(!Q.trim()){te(null),se("");return}const S=at(U,x+1);V($=>({...$,additions:[...$.additions,{id:je(),afterTokenIndex:x,sourceLine:S,content:Q.trim()}]})),te(null),se("")},[Q,U]),Ae=o.useCallback(x=>{V(S=>({...S,additions:S.additions.filter($=>$.id!==x)}))},[]),tt=o.useCallback((x,S)=>{V($=>({...$,additions:$.additions.map(M=>M.id===x?{...M,id:je(),content:S}:M)}))},[]),vt=o.useCallback(()=>{var x;de&&(V(S=>({...S,deletions:[...S.deletions,{id:je(),tokenIndices:de.tokenIndices,startLine:de.startLine,endLine:de.endLine,selectedText:de.text.slice(0,80)}]})),Ce(null),(x=window.getSelection())==null||x.removeAllRanges())},[de]),k=o.useCallback(x=>{var S;de&&(ke({type:x,tokenIndices:de.tokenIndices,startLine:de.startLine,endLine:de.endLine,text:de.text.slice(0,80)}),Le(""),Ce(null),(S=window.getSelection())==null||S.removeAllRanges())},[de]),L=o.useCallback(()=>{if(!ne)return;const x=Re.trim();if(!x){ke(null),Le("");return}ne.type==="replace"?V(S=>({...S,replacements:[...S.replacements,{id:je(),tokenIndices:ne.tokenIndices,startLine:ne.startLine,endLine:ne.endLine,selectedText:ne.text,content:x}]})):V(S=>({...S,comments:[...S.comments,{id:je(),tokenIndices:ne.tokenIndices,startLine:ne.startLine,endLine:ne.endLine,selectedText:ne.text,content:x}]})),ke(null),Le("")},[ne,Re]),K=o.useCallback(x=>{V(S=>({...S,replacements:S.replacements.filter($=>$.id!==x)}))},[]),re=o.useCallback((x,S)=>{V($=>({...$,replacements:$.replacements.map(M=>M.id===x?{...M,id:je(),content:S}:M)}))},[]),ie=o.useCallback(x=>{V(S=>({...S,comments:S.comments.filter($=>$.id!==x)}))},[]),Te=o.useCallback((x,S)=>{V($=>({...$,comments:$.comments.map(M=>M.id===x?{...M,id:je(),content:S}:M)}))},[]),ue=o.useCallback(x=>{V(S=>({...S,deletions:S.deletions.filter($=>$.id!==x)}))},[]),ve=o.useCallback((x,S)=>{V($=>({...$,deletions:$.deletions.map(M=>M.id===x?{...M,id:je(),selectedText:S}:M)}))},[]),be=o.useCallback(x=>{let S=x instanceof Element?x:x.parentElement;for(;S&&S!==ge.current;){if(S.hasAttribute("data-token-index"))return S;S=S.parentElement}return null},[]),fe=o.useCallback(()=>{const x=window.getSelection();if(!x||x.isCollapsed||!ge.current){Ce(null);return}const S=x.toString().trim();if(!S){Ce(null);return}const $=x.getRangeAt(0);if(!ge.current.contains($.commonAncestorContainer)){Ce(null);return}const M=be($.startContainer),oe=be($.endContainer);if(!M||!oe){Ce(null);return}const ee=parseInt(M.getAttribute("data-token-index")||"0",10),le=parseInt(oe.getAttribute("data-token-index")||"0",10),Ut=[];for(let Ct=Math.min(ee,le);Ct<=Math.max(ee,le);Ct++)Ut.push(Ct);const or=at(U,Math.min(ee,le)),ar=at(U,Math.max(ee,le)+1),Kt=$.getBoundingClientRect(),kt=ge.current,Gt=kt.getBoundingClientRect();navigator.clipboard.writeText(S).catch(()=>{});const nt=Be.current,Jt=nt&&Date.now()-nt.time<500;qe.current=Date.now(),Ce({x:(Jt?nt.x:Kt.right)-Gt.left+kt.scrollLeft+6,y:(Jt?nt.y:Kt.top)-Gt.top+kt.scrollTop-44,tokenIndices:Ut,startLine:or,endLine:ar,text:S})},[U,be]),we=o.useRef(void 0);o.useEffect(()=>{const x=()=>{we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{const S=window.getSelection();if(!S||S.isCollapsed||!ge.current){if(Date.now()-qe.current<300)return;Ce(null);return}const $=S.anchorNode;$&&ge.current.contains($)&&fe()},120)};return document.addEventListener("selectionchange",x),()=>{document.removeEventListener("selectionchange",x),we.current&&clearTimeout(we.current)}},[fe]);const Ve=A(x=>x.theme);Ls(ge,U,Ve);const We=o.useCallback(()=>{const x=N.current;return{additions:O.additions.filter(S=>!x.has(S.id)),deletions:O.deletions.filter(S=>!x.has(S.id)),replacements:O.replacements.filter(S=>!x.has(S.id)),comments:O.comments.filter(S=>!x.has(S.id))}},[O]),wt=o.useCallback(async()=>{const x=We();if(!pn(x))return;const S=fn(x,Z),$=gn(n);try{const{path:M}=await dn(a,r,$,S),oe=hn(n,M);l(oe),N.current=pt(O),P(le=>le+1);const ee=x.additions.length+x.deletions.length+x.replacements.length+x.comments.length;j("ok",`Sent ${ee} annotation(s)`)}catch(M){const oe=M instanceof Error?M.message:"Failed to send";j("err",oe)}},[We,O,Z,l,n,a,r,j]),He=o.useCallback(async(x,S)=>{if(!i)return;const $={additions:[],deletions:[],replacements:[],comments:[]};if(S==="add"){const ee=O.additions.find(le=>le.id===x);if(!ee)return;$.additions.push(ee)}else if(S==="del"){const ee=O.deletions.find(le=>le.id===x);if(!ee)return;$.deletions.push(ee)}else if(S==="rep"){const ee=O.replacements.find(le=>le.id===x);if(!ee)return;$.replacements.push(ee)}else{const ee=O.comments.find(le=>le.id===x);if(!ee)return;$.comments.push(ee)}const M=fn($,Z),oe=gn(n);try{const{path:ee}=await dn(a,r,oe,M);i(hn(n,ee)),N.current.add(x),P(le=>le+1),j("ok","Sent 1 annotation")}catch(ee){const le=ee instanceof Error?ee.message:"Failed to send";j("err",le)}},[i,n,O,Z,a,r,j]),tr=o.useCallback((x,S)=>{S==="add"?Ae(x):S==="del"?ue(x):S==="rep"?K(x):ie(x)},[Ae,ue,K,ie]);o.useImperativeHandle(m,()=>({getSummary:()=>{const x=We();return pn(x)?"[pending annotations]":""},handleEscape:()=>b?(B(),!0):ne?(L(),!0):Y!=null?(De(Y),!0):!1,getScrollTop:()=>{var x;return((x=ge.current)==null?void 0:x.scrollTop)??0},setScrollTop:x=>{requestAnimationFrame(()=>{ge.current&&(ge.current.scrollTop=x)})}}),[We,b,B,Y,De,ne,L]);const nr=o.useMemo(()=>{const x=new Set;return O.deletions.forEach(S=>S.tokenIndices.forEach($=>x.add($))),x},[O.deletions]),rr=o.useMemo(()=>{const x=new Set;return O.replacements.forEach(S=>S.tokenIndices.forEach($=>x.add($))),x},[O.replacements]),sr=o.useMemo(()=>{const x=new Set;return O.comments.forEach(S=>S.tokenIndices.forEach($=>x.add($))),x},[O.comments]),Wt=o.useMemo(()=>{const x=new Map;return O.additions.forEach(S=>{const $=x.get(S.afterTokenIndex)||[];$.push(S),x.set(S.afterTokenIndex,$)}),x},[O.additions]),Ht=J.unsent>0,St=o.useCallback(x=>N.current.has(x),[]);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}),g&&s.jsx("span",{style:{fontSize:"10px",color:g.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:g.type==="err"?"pointer":void 0},title:g.type==="err"?"Click to copy":g.msg,onClick:g.type==="err"?()=>{navigator.clipboard.writeText(g.msg).catch(()=>{}),j("ok","Copied")}:void 0,children:g.msg}),b?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"pane-btn",onClick:G,disabled:T,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:T?"Saving...":"Save"}),s.jsx("button",{className:"pane-btn",onClick:B,disabled:T,title:"Cancel (Esc)",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[u&&s.jsx("button",{className:"pane-btn",onClick:u,title:"Refresh current file",children:"↻"}),!d&&s.jsx("button",{className:"pane-btn",onClick:X,title:"Edit file (double-click content)",children:"Edit"}),s.jsx("button",{className:"pane-btn",onClick:wt,disabled:!Ht,title:"Send all annotations",style:Ht?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),s.jsx(Bs,{annotations:O,annCounts:J,isSent:St,onSendAll:wt,onSendSingle:He,onDelete:tr}),f&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await wt(),f()},title:"Send annotations & close file",children:"×"})]})]}),s.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[b?s.jsx("textarea",{ref:F,className:"plan-edit-textarea",style:{fontSize:`${h}px`},value:y,onChange:x=>W(x.target.value),onKeyDown:x=>{if(x.key==="s"&&(x.ctrlKey||x.metaKey)){x.preventDefault(),G();return}if(x.key==="Escape"){x.preventDefault(),B();return}},spellCheck:!1}):s.jsxs("div",{ref:ge,className:`plan-anno-content md-preview${Y!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${h}px`,minWidth:0},onMouseUp:x=>{Be.current={x:x.clientX,y:x.clientY,time:Date.now()},fe()},onDoubleClick:x=>{d||x.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||X()},children:[!d&&s.jsx(yn,{index:-1,active:Y===-1,additions:Wt.get(-1),onOpen:()=>{te(-1),se("")},onSubmit:()=>De(-1),onRemoveAddition:Ae,onEditAddition:tt,onSendSingle:i?x=>He(x,"add"):void 0,isSent:St,insertText:Q,setInsertText:se,textareaRef:Y===-1?ye:void 0,expanded:p,alwaysShow:U.length===0,fontSize:h}),U.map((x,S)=>{const $=Ds(x);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":S,id:_.get(S),className:nr.has(S)?"plan-block--deleted":rr.has(S)?"plan-block--replaced":sr.has(S)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:$}}),O.deletions.filter(M=>M.tokenIndices[0]===S).map(M=>s.jsx(It,{type:"del",annotation:M,fontSize:h,onEdit:ve,onRemove:ue,onSend:i?oe=>He(oe,"del"):void 0,isSent:N.current.has(M.id)},M.id)),O.replacements.filter(M=>M.tokenIndices[0]===S).map(M=>s.jsx(It,{type:"rep",annotation:M,fontSize:h,onEdit:re,onRemove:K,onSend:i?oe=>He(oe,"rep"):void 0,isSent:N.current.has(M.id)},M.id)),O.comments.filter(M=>M.tokenIndices[0]===S).map(M=>s.jsx(It,{type:"com",annotation:M,fontSize:h,onEdit:Te,onRemove:ie,onSend:i?oe=>He(oe,"com"):void 0,isSent:N.current.has(M.id)},M.id)),ne&&ne.tokenIndices[0]===S&&s.jsxs("div",{className:ne.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[s.jsx("span",{style:{color:ne.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:ne.type==="replace"?"⇄":"?"}),s.jsx("textarea",{ref:_e,className:"plan-annotation-textarea",value:Re,onChange:M=>Le(M.target.value),onKeyDown:M=>{if(M.key==="Enter"&&(M.ctrlKey||M.metaKey)){M.preventDefault(),L();return}if(M.key==="Escape"){M.preventDefault(),L();return}},onBlur:L,placeholder:ne.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:ft(Re),style:{fontSize:`${h}px`,flex:1}})]}),!d&&s.jsx(yn,{index:S,active:Y===S,additions:Wt.get(S),onOpen:()=>{te(S),se("")},onSubmit:()=>De(S),onRemoveAddition:Ae,onEditAddition:tt,onSendSingle:i?M=>He(M,"add"):void 0,isSent:St,insertText:Q,setInsertText:se,textareaRef:Y===S?ye:void 0,expanded:p,fontSize:h})]},S)}),!d&&de&&s.jsx(Ws,{x:de.x,y:de.y,onDelete:vt,onReplace:()=>k("replace"),onComment:()=>k("comment")})]}),!b&&s.jsx(Os,{headings:ae,scrollRef:ge})]})]})});function yn({index:t,active:e,additions:n,onOpen:r,onSubmit:a,onRemoveAddition:l,onEditAddition:i,onSendSingle:u,isSent:f,insertText:c,setInsertText:p,textareaRef:d,expanded:m,alwaysShow:h,fontSize:g=14}){const[v,C]=o.useState(null),[j,b]=o.useState(""),R=o.useRef(null),y=At(),W=At();o.useEffect(()=>{v&&(y.clearUndo(),requestAnimationFrame(()=>{const E=R.current;E&&(E.focus(),E.selectionStart=E.selectionEnd=E.value.length)}))},[v]),o.useEffect(()=>{e&&W.clearUndo()},[e]);const T=o.useCallback(E=>{b(w=>(y.pushUndo(w),E))},[y]),D=o.useCallback(E=>{W.pushUndo(c),p(E)},[c,p,W]),F=o.useCallback(E=>{C(E.id),b(E.content)},[]),z=o.useCallback(()=>{if(!v)return;const E=j.trim();E?i(v,E):l(v),C(null),b("")},[v,j,i,l]),q=o.useCallback(()=>{C(null),b("")},[]);return s.jsxs("div",{className:`plan-insert-zone${h?" plan-insert-zone--empty":""}`,"data-zone-index":t,children:[n==null?void 0:n.map(E=>s.jsx("div",{className:"plan-annotation-card",children:v===E.id?s.jsx("textarea",{ref:R,className:"plan-annotation-textarea",value:j,onChange:w=>T(w.target.value),onKeyDown:w=>{if(w.key==="Enter"&&(w.ctrlKey||w.metaKey)){w.preventDefault(),z();return}if(w.key==="Escape"){w.preventDefault(),q();return}if(w.key==="Tab"){$t(w,T);return}},onBlur:z,rows:ft(j),style:{fontSize:`${g}px`,flex:1,...m?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${g}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>F(E),title:"Double-click to edit",children:E.content}),u&&(()=>{const w=(f==null?void 0:f(E.id))??!1;return s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!w&&u(E.id),disabled:w,title:w?"Already sent":"Send to terminal",style:w?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>F(E),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(E.id),children:"×"})]})},E.id)),e?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:d,className:"plan-annotation-textarea",value:c,onChange:E=>D(E.target.value),onKeyDown:E=>{if(E.key==="Enter"&&(E.ctrlKey||E.metaKey)){E.preventDefault(),a();return}if(E.key==="Escape"){E.preventDefault(),a();return}if(E.key==="Tab"){$t(E,D);return}},onBlur:a,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:ft(c),style:{fontSize:`${g}px`,...m?{minWidth:300}:void 0}})}):h&&!(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 Me(t,e,n){const r=n?{path:n}:void 0;return he.get(t,e,"files",r)}function Us(t,e,n,r){return new Promise((a,l)=>{const i=new FormData;for(const f of n)i.append("files",f);const u=new XMLHttpRequest;u.open("POST",`${Se}/api/sessions/${encodeURIComponent(e)}/upload`),u.setRequestHeader("Authorization",`Bearer ${t}`),u.upload.addEventListener("progress",f=>{f.lengthComputable&&r&&r(Math.round(f.loaded/f.total*100))}),u.addEventListener("load",()=>{u.status>=200&&u.status<300?a():l(new Error(`Upload failed: ${u.status}`))}),u.addEventListener("error",()=>l(new Error("Upload network error"))),u.addEventListener("abort",()=>l(new Error("Upload aborted"))),u.send(i)})}async function vn(t,e){return(await he.get(t,e,"cwd")).cwd}async function Ks(t,e,n){return he.post(t,e,"touch",{name:n})}async function Gs(t,e,n){return he.post(t,e,"mkdir",{path:n})}async function Js(t,e,n){return he.del(t,e,"rm",{path:n})}async function qs(t,e){const n=await he.getBlob(t,e,"download-cwd"),r=await n.blob(),a=URL.createObjectURL(r),l=document.createElement("a");l.href=a;const i=n.headers.get("Content-Disposition"),u=i==null?void 0:i.match(/filename="(.+)"/);l.download=u?decodeURIComponent(u[1]):"cwd.tar.gz",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(a)}async function Vs(t,e,n){const a=await(await he.getBlob(t,e,"download",{path:n})).blob(),l=URL.createObjectURL(a),i=document.createElement("a");i.href=l,i.download=n.split("/").pop()||"download",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(l)}function qn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function Ys(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function Vn(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function Xs({sessionId:t,token:e,planDir:n,selectedFile:r,onSelectFile:a,onCreateFile:l,onDeleteFile:i}){const[u,f]=o.useState([]),[c,p]=o.useState(!0),[d,m]=o.useState(""),[h,g]=o.useState(!1),v=o.useRef(null),[C,j]=o.useState(()=>{if(r&&r.startsWith(n+"/")){const I=r.substring(0,r.lastIndexOf("/"));if(I.startsWith(n))return I}return n});o.useEffect(()=>{if(r&&r.startsWith(n+"/")){const I=r.substring(0,r.lastIndexOf("/"));if(I.startsWith(n)){j(I);return}}j(n)},[r,n]);const b=o.useCallback(async()=>{if(!(!e||!C)){p(!0);try{const X=(await Me(e,t,C)).files.filter(B=>B.type==="file"&&(B.name.toLowerCase().endsWith(".md")||B.name===".index.json")||B.type==="directory").sort((B,G)=>{const U=B.type==="file"&&B.name===".index.json",Z=G.type==="file"&&G.name===".index.json";return U&&!Z?-1:!U&&Z?1:B.type==="directory"&&G.type!=="directory"?-1:B.type!=="directory"&&G.type==="directory"?1:B.name.localeCompare(G.name)});f(X)}catch{f([])}finally{p(!1)}}},[e,t,C]);o.useEffect(()=>{b()},[b]),o.useEffect(()=>{const I=setInterval(b,5e3);return()=>clearInterval(I)},[b]);const R=o.useCallback(()=>{const I=n.substring(0,n.lastIndexOf("/")+1);return C.startsWith(I)?C.substring(I.length):C},[n,C]),y=o.useCallback(async()=>{const I=d.trim();if(!I)return;const X=I.endsWith(".md")?I:`${I}.md`;g(!0);try{const B=await Ks(e,t,`${R()}/${X}`);B.ok&&(m(""),await b(),l(B.path))}catch{}finally{g(!1)}},[d,e,t,R,b,l]),W=o.useCallback(async()=>{const I=d.trim().replace(/\/+$/,"");if(I){g(!0);try{await Gs(e,t,`${R()}/${I}`),m(""),await b()}catch{}finally{g(!1)}}},[d,e,t,R,b]),T=o.useCallback(async I=>{const X=`${C}/${I.name}`,B=I.type==="directory"?`folder "${I.name}" and all its contents`:`"${I.name}"`;if(window.confirm(`Delete ${B}?`))try{await Js(e,t,X),i==null||i(X),await b()}catch{}},[e,t,C,b,i]),D=o.useCallback(I=>{j(X=>`${X}/${I}`)},[]),F=o.useCallback(()=>{C!==n&&j(I=>I.substring(0,I.lastIndexOf("/")))},[C,n]),z=n.split("/").pop()||"AiTasks",q=(()=>{const I=n.split("/");return I.length>=2?I[I.length-2]+"/":""})(),E=C===n?q+z+"/":q+z+"/"+C.substring(n.length+1)+"/",w=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:E,children:E}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:b,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),s.jsxs("div",{className:"plan-file-browser__create",children:[s.jsx("input",{ref:v,className:"plan-file-browser__input",value:d,onChange:I=>m(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),y())},placeholder:"name",disabled:h}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:y,disabled:h||!d.trim(),title:"Create new .md file",style:d.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:W,disabled:h||!d.trim(),title:"Create new folder",style:d.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),s.jsxs("div",{className:"plan-file-browser__list",children:[c&&u.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&u.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),C!==n&&s.jsxs("div",{className:"plan-file-browser__item",onClick:F,title:"Go up to parent directory",style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),s.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),u.map(I=>{const X=`${C}/${I.name}`,B=I.type==="file"&&I.name===w,G=I.type==="directory";return s.jsxs("div",{className:`plan-file-browser__item${B?" plan-file-browser__item--active":""}`,onClick:()=>G?D(I.name):a(X),title:G?`Open folder ${I.name}`:I.name,style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",children:G?"📁":I.name===".index.json"?"🔒":"□"}),s.jsxs("span",{className:"plan-file-browser__name",children:[I.name,G?"/":""]}),!G&&s.jsx("span",{className:"plan-file-browser__size",children:qn(I.size)}),!I.name.startsWith(".")&&s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:U=>{U.stopPropagation(),T(I)},title:`Delete ${I.name}`,children:"×"})]},I.name)})]})]})}const Rt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},Zs=200;function Qs(){const[t,e]=o.useState(Rt),n=o.useRef("lines"),r=o.useRef([]),a=o.useRef(""),l=o.useRef(""),i=o.useRef([]),u=o.useRef(0),f=o.useRef(0),c=o.useRef(null),p=o.useRef(null),d=o.useCallback(()=>{const j=n.current;e(b=>({...b,receivedBytes:u.current,...j==="lines"?{lines:[...r.current]}:{},...j==="content"?{content:l.current}:{}}))},[]),m=o.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,d()},Zs))},[d]),h=o.useCallback(j=>{n.current=j,r.current=[],a.current="",l.current="",i.current=[],u.current=0,f.current=0,p.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...Rt,mode:j,status:"streaming"})},[]),g=o.useCallback(j=>{u.current+=j.length;const b=n.current;if(b==="lines"){const y=p.current.decode(j,{stream:!0}).split(`
|
|
30
|
+
`);y[0]=a.current+y[0],a.current=y.pop(),y.length>0&&r.current.push(...y)}else if(b==="content"){const R=p.current.decode(j,{stream:!0});l.current+=R}else i.current.push(new Uint8Array(j));m()},[m]),v=o.useCallback(j=>{switch(j.type){case"file-stream-start":f.current=j.size,e(b=>({...b,totalSize:j.size,mtime:j.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const b=n.current;let R=r.current,y=l.current,W=null;if(b==="lines"){const T=p.current.decode(),D=a.current+T;D&&(R=[...R,D],r.current=R),a.current=""}else if(b==="content"){const T=p.current.decode();y=l.current+T,l.current=y}else{const T=i.current.reduce((F,z)=>F+z.length,0);W=new Uint8Array(T);let D=0;for(const F of i.current)W.set(F,D),D+=F.length;i.current=[]}e({status:"complete",mode:b,lines:b==="lines"?[...R]:[],content:b==="content"?y:"",buffer:b==="binary"?W:null,totalSize:f.current,receivedBytes:u.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(b=>({...b,status:"error",error:j.error}));break}},[]),C=o.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),r.current=[],a.current="",l.current="",i.current=[],u.current=0,f.current=0,p.current=null,e(Rt)},[]);return{state:t,startStream:h,handleChunk:g,handleControl:v,reset:C}}async function eo(t,e,n){const r=await fetch(`${Se}/api/sessions/${e}/task-auto`,{method:"POST",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const a=await r.json().catch(()=>({error:"Unknown error"}));throw new Error(a.error||`HTTP ${r.status}`)}}async function Lt(t,e){const n=await fetch(`${Se}/api/sessions/${e}/task-auto`,{headers:me(t)});return n.ok?n.json():null}async function wn(t,e){const n=await fetch(`${Se}/api/sessions/${e}/task-auto`,{method:"DELETE",headers:me(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`HTTP ${n.status}`)}}async function to(t,e){const n=await fetch(`${Se}/api/sessions/${e}/capture-pane`,{headers:me(t)});return n.ok&&(await n.json()).content||""}const no=t=>t?t==="complete"?"var(--accent-green)":t==="executing"||t==="review"?"var(--accent-blue)":t==="blocked"?"var(--accent-red)":t==="cancelled"?"var(--text-secondary)":"var(--accent-yellow)":"var(--text-secondary)";function Ke(){return s.jsx("span",{className:"auto-divider",children:"|"})}function Sn({value:t,onChange:e,min:n,max:r,width:a}){return s.jsxs("div",{className:"auto-spin-input",style:{width:a},children:[s.jsx("input",{type:"text",inputMode:"numeric",value:t,onChange:l=>{const i=parseInt(l.target.value,10);isNaN(i)||e(Math.max(n,Math.min(r,i)))}}),s.jsxs("div",{className:"auto-spin-btns",children:[s.jsx("button",{type:"button",tabIndex:-1,onClick:()=>e(Math.min(r,t+1)),children:"▲"}),s.jsx("button",{type:"button",tabIndex:-1,onClick:()=>e(Math.max(n,t-1)),children:"▼"})]})]})}const kn="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",Cn={background:"#000000",foreground:"#cccccc",cursor:"#aeafad",selectionBackground:"rgba(38, 79, 120, 0.5)"},Tn={background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"rgba(9, 105, 218, 0.2)"};function Yn(t,e){const n=new Date(t).getTime(),r=e?new Date(e).getTime():Date.now(),a=Math.round((r-n)/1e3);if(a<60)return`${a}s`;const l=Math.floor(a/60),i=a%60;return i>0?`${l}m${i}s`:`${l}m`}function ro(t){if(t<1)return`${Math.round(t*60)}s`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}m ${n}s`:`${e}m`}function so({sessionId:t,token:e,connected:n,moduleDir:r,moduleName:a,taskStatus:l,onSendToTerminal:i,onSetOutputMirror:u}){const[f,c]=o.useState(null),[p,d]=o.useState(!0),[m,h]=o.useState(!1),[g,v]=o.useState(null),[C,j]=o.useState(20),[b,R]=o.useState(1440);o.useEffect(()=>{if(!n)return;let z=!1;const q=async()=>{try{const w=await Lt(e,t);z||(c(w),d(!1))}catch{z||d(!1)}};q();const E=setInterval(q,2e3);return()=>{z=!0,clearInterval(E)}},[e,t,n]);const y=o.useCallback(async()=>{if(!(!n||m)){h(!0);try{await eo(e,t,{taskDir:r,maxIterations:C,timeoutMinutes:b}),i==null||i(`/moonview:auto AiTasks/${a}`);const z=await Lt(e,t);c(z)}catch{}finally{h(!1)}}},[n,m,e,t,r,C,b,a,i]),W=o.useCallback(async()=>{try{await wn(e,t);const z=await Lt(e,t);c(z)}catch{}},[e,t]),T=o.useCallback(()=>{v(null),u==null||u(null)},[u]);if(p)return null;if(!f)return s.jsxs(s.Fragment,{children:[s.jsx(Ke,{}),s.jsx("button",{className:"pane-btn",onClick:y,disabled:!n||m,style:{color:"var(--accent-green)",fontWeight:600,fontSize:11,opacity:!n||m?.4:1},title:`Start auto (${C} iterations, ${b}m timeout)`,children:m?"...":"▶"}),s.jsx(Ke,{}),s.jsx("span",{style:{fontSize:11,fontWeight:500,whiteSpace:"nowrap",color:no(l)},children:l}),s.jsx(Ke,{}),s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)"},children:"iter"}),s.jsx(Sn,{value:C,onChange:j,min:1,max:100,width:42}),s.jsx(Ke,{}),s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)"},children:"timeout"}),s.jsx(Sn,{value:b,onChange:R,min:5,max:2880,width:56}),s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)"},children:"m"})]});const D=f.steps,F=f.status==="running";return s.jsxs(s.Fragment,{children:[s.jsx(Ke,{}),s.jsx("div",{style:{display:"flex",alignItems:"center",gap:0,overflow:"auto",flex:1,minWidth:0},children:D.map((z,q)=>{const E=!z.endedAt&&F,w=!!z.endedAt,I=!z.endedAt&&!F;return s.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[q>0&&s.jsx("div",{className:`auto-connector${w||E?" completed":""}`}),s.jsxs("button",{className:`auto-step-node${E?" active":w?" completed":" pending"}`,onClick:()=>{w?v({stepIndex:q,type:"summary"}):E&&v({stepIndex:q,type:"terminal"})},title:`${z.step}${z.checkpoint?` (${z.checkpoint})`:""}${z.result?`: ${z.result}`:""}`,disabled:I,children:[s.jsx("div",{className:"auto-step-circle"}),s.jsx("span",{className:"auto-step-label",children:z.step}),s.jsx("span",{className:"auto-step-duration",children:E?"running":w?Yn(z.startedAt,z.endedAt):""})]})]},z.id)})}),s.jsx(Ke,{}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,flexShrink:0},children:[s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:ro(f.elapsedMinutes)}),F&&s.jsx("button",{className:"pane-btn",onClick:W,style:{color:"var(--accent-red)",fontWeight:600,fontSize:11},title:"Cancel auto mode",children:"■"}),!F&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:10,fontWeight:600,color:f.status==="completed"?"var(--accent-green)":"var(--accent-yellow)"},children:f.status}),s.jsx("button",{className:"pane-btn",onClick:async()=>{try{await wn(e,t),c(null)}catch{}},style:{fontSize:10,color:"var(--text-secondary)"},title:"Clear and reset",children:"×"})]})]}),g&&s.jsx(oo,{step:D[g.stepIndex],type:g.type,sessionId:t,token:e,moduleDir:r,onClose:T,onSetOutputMirror:u})]})}function oo({step:t,type:e,sessionId:n,token:r,moduleDir:a,onClose:l,onSetOutputMirror:i}){const[u,f]=o.useState(null),c=o.useRef(null),p=o.useRef(null),d=o.useRef(l);d.current=l;const m=A(v=>v.fontSize),h=A(v=>v.theme);o.useEffect(()=>{const v=C=>{C.key==="Escape"&&d.current()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[]),o.useEffect(()=>{if(e!=="summary")return;let v=!1;return(async()=>{try{const C=await lt(r,n,`${a}/.summary.md`);!v&&C?f(C.content):v||f("(No summary available)")}catch{v||f("(Failed to load summary)")}})(),()=>{v=!0}},[e,r,n,a]),o.useEffect(()=>{if(e!=="terminal"||!c.current)return;const v=new Ot({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:m,fontFamily:kn,theme:h==="dark"?Cn:Tn}),C=new Ft;v.loadAddon(C),v.open(c.current);let j=null;try{j=new Bt,j.onContextLoss(()=>{j==null||j.dispose(),j=null}),v.loadAddon(j)}catch{j=null}p.current=v,v.attachCustomKeyEventHandler(T=>(T.key==="Escape"&&d.current(),!1)),v.onSelectionChange(()=>{const T=v.getSelection();T&&navigator.clipboard.writeText(T).catch(()=>{})}),to(r,n).then(T=>{T&&v.write(T.replace(/\n/g,`\r
|
|
31
|
+
`)),i==null||i(D=>{v.write(D)})});let b=null;const R=()=>{const T=c.current;if(!T||T.clientWidth<=0||T.clientHeight<=0)return!1;try{return C.fit(),v.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!R()){let T=0;b=setInterval(()=>{T++,(R()||T>=20)&&(clearInterval(b),b=null)},50)}});let y=null;const W=new ResizeObserver(()=>{y||(y=requestAnimationFrame(()=>{y=null,R()}))});return W.observe(c.current),()=>{if(b&&clearInterval(b),y&&cancelAnimationFrame(y),W.disconnect(),i==null||i(null),j)try{j.dispose()}catch{}v.dispose(),p.current=null}},[e]),o.useEffect(()=>{p.current&&(p.current.options.fontSize=m)},[m]),o.useEffect(()=>{p.current&&(p.current.options.theme=h==="dark"?Cn:Tn)},[h]);const g=28;return s.jsxs("div",{className:"auto-step-popup",children:[s.jsxs("div",{style:{height:g,boxSizing:"border-box",padding:"0 12px",display:"flex",alignItems:"center",justifyContent:"space-between",background:"var(--bg-tertiary)",borderBottom:"1px solid var(--border)",fontSize:12},children:[s.jsxs("span",{style:{color:"var(--accent-blue)"},children:[t.step,t.checkpoint?` (${t.checkpoint})`:"",t.result?` → ${t.result}`:"",s.jsx("span",{style:{color:"var(--text-secondary)",marginLeft:8},children:Yn(t.startedAt,t.endedAt)})]}),s.jsx("button",{className:"pane-btn",onClick:l,style:{fontSize:14,padding:"0 4px"},children:"✕"})]}),e==="summary"?s.jsx("div",{style:{flex:1,overflow:"auto",padding:"8px 16px",fontSize:12,color:"var(--text-primary)",whiteSpace:"pre-wrap",fontFamily:kn,lineHeight:1.5},children:u??"Loading..."}):s.jsx("div",{ref:c,style:{position:"absolute",top:g,left:0,right:0,bottom:0,overflow:"hidden"}})]})}function jn({label:t,percent:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:t}),e!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function ao({sessionId:t,token:e,connected:n,onRequestFileStream:r,onSendToTerminal:a,onSetOutputMirror:l}){const i=Qs(),[u,f]=o.useState(!1),[c,p]=o.useState(null),[d,m]=o.useState(null),[h,g]=o.useState(""),[v,C]=o.useState(!1),[j,b]=o.useState(!1),R=o.useRef(null),y="plan-selected-file",W=o.useRef(void 0);o.useEffect(()=>{if(d)return clearTimeout(W.current),W.current=setTimeout(()=>{try{localStorage.setItem(y,d)}catch{}},50),()=>clearTimeout(W.current)},[d]);const T=o.useRef(null);o.useEffect(()=>{T.current=null;let P=!1;return C(!0),b(!1),(async()=>{let J="";try{const Y=await Me(e,t);if(P)return;if(J=Y.home||"",Y.files.find(Q=>Q.name==="AiTasks"&&Q.type==="directory")){const Q=Y.cwd+"/AiTasks";p(Q);const se=localStorage.getItem(y);se&&se.startsWith(Q+"/")&&m(se)}else p(null),m(null),b(!0)}catch{p(null)}finally{P||C(!1)}try{if(P)return;if(J){const Y=`${J}/.claude/plugins/installed_plugins.json`,te=await lt(e,t,Y,0);if(!P&&te)try{const Q=JSON.parse(te.content);"ai-cli-task@moonview"in(Q.plugins||Q)||f(!0)}catch{f(!0)}}}catch{}})(),()=>{P=!0}},[t,e]),o.useEffect(()=>{if(!j||!n)return;const P=setInterval(async()=>{try{const J=await Me(e,t);if(J.files.find(te=>te.name==="AiTasks"&&te.type==="directory")){const te=J.cwd+"/AiTasks";p(te),b(!1);const Q=localStorage.getItem(y);Q&&Q.startsWith(te+"/")&&m(Q)}}catch{}},3e3);return()=>clearInterval(P)},[j,n,e,t,y]),o.useEffect(()=>(ss(t,i.handleChunk,i.handleControl),()=>os(t)),[t,i.handleChunk,i.handleControl]),o.useEffect(()=>{!d||!n||T.current===d&&h||(T.current=d,i.reset(),i.startStream("content"),r==null||r(d))},[d,n]);const D=o.useRef(0);o.useEffect(()=>{i.state.status==="complete"&&d&&(g(i.state.content),D.current=Date.now())},[i.state.status,i.state.content,d]),o.useEffect(()=>{if(!d||!n||!h)return;const P=setInterval(async()=>{if(D.current)try{const J=await lt(e,t,d,D.current);J&&(g(J.content),D.current=J.mtime)}catch{}},3e3);return()=>clearInterval(P)},[d,n,h,e,t]);const F=o.useRef(new Map),z=o.useCallback(()=>{var J,Y;if(!d)return;const P=((Y=(J=R.current)==null?void 0:J.getScrollTop)==null?void 0:Y.call(J))??0;P>0&&F.current.set(d,P)},[d]);o.useEffect(()=>{if(!d||!h)return;const P=F.current.get(d);P!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var J,Y;(Y=(J=R.current)==null?void 0:J.setScrollTop)==null||Y.call(J,P)})})},[d,h]);const q=o.useCallback(P=>{P!==d&&(z(),m(P),g(""),T.current=null)},[d,z]),E=o.useCallback(P=>{d&&(d===P||d.startsWith(P+"/"))&&(m(null),g(""),T.current=null)},[d]),w=o.useCallback(P=>{m(P),g(""),T.current=null},[]),I=o.useCallback(P=>{P&&(a==null||a(P))},[a]),X=o.useCallback((P,J)=>{g(P),D.current=J},[]),B=o.useCallback(()=>{z(),m(null),g(""),T.current=null},[z]),G=o.useCallback(()=>{!d||!n||(T.current=null,g(""),i.reset(),i.startStream("content"),r==null||r(d),T.current=d)},[d,n,i,r]),[U,Z]=o.useState(()=>{const P=localStorage.getItem(`plan-fb-width-${t}`);if(P){const J=Number(P);if(Number.isFinite(J)&&J>=60&&J<=300)return J}return 130}),ae=o.useRef(U);if(U!==ae.current){ae.current=U;try{localStorage.setItem(`plan-fb-width-${t}`,String(Math.round(U)))}catch{}}const _=o.useCallback(P=>{P.preventDefault();const J=P.clientX,Y=U;document.body.classList.add("resizing-panes");const te=se=>{const ye=se.clientX-J;Z(Math.min(300,Math.max(60,Y+ye)))},Q=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",Q)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",Q)},[U]),N=o.useMemo(()=>{if(!c||!d||!d.startsWith(c+"/"))return null;const P=d.substring(c.length+1),J=P.indexOf("/");if(J<0)return null;const Y=P.substring(0,J);return!Y||Y.startsWith(".")?null:{name:Y,dir:`${c}/${Y}`}},[c,d]),H=N==null?void 0:N.dir,[O,V]=o.useState(null),ce=o.useRef(0);return o.useEffect(()=>{V(null),ce.current=0},[H]),o.useEffect(()=>{if(!H||!n)return;let P=!1;const J=async()=>{try{const te=await lt(e,t,`${H}/.index.json`,ce.current||void 0);if(P)return;if(te){ce.current=te.mtime;try{const Q=JSON.parse(te.content);V({status:Q.status||"draft",phase:Q.phase||"",type:Q.type||"",completed_steps:Q.completed_steps||0,title:Q.title||""})}catch{}}}catch{}};J();const Y=setInterval(J,3e3);return()=>{P=!0,clearInterval(Y)}},[H,n,e,t]),s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[u&&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:()=>{a&&a("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),f(!1)},children:"Install"}),s.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>f(!1),children:"×"})]}),s.jsxs("div",{className:"plan-overlay-body",children:[c&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:U,flexShrink:0,overflow:"hidden"},children:s.jsx(Xs,{sessionId:t,token:e,planDir:c,selectedFile:d,onSelectFile:q,onCreateFile:w,onDeleteFile:E})}),s.jsx("div",{onMouseDown:_,style:{width:3,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:P=>{P.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:P=>{P.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsx("div",{className:"plan-overlay-center",children:v?s.jsx(jn,{label:"Loading AiTasks/..."}):j?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),s.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",s.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/moonview:init <name>"})," in the terminal to create a task"]})]}):d&&!h&&(i.state.status==="streaming"||i.state.status==="idle")?s.jsx(jn,{label:`Loading ${d.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):d?s.jsx(Hs,{ref:R,markdown:h,filePath:d,sessionId:t,token:e,onExecute:I,onSend:a,onRefresh:G,onClose:B,onContentSaved:X,readOnly:d.endsWith("/.index.json")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]}),N&&O&&s.jsxs("div",{className:"auto-timeline",style:{backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{fontSize:11,color:"var(--text-primary)",fontWeight:500,whiteSpace:"nowrap"},title:O.title,children:N.name}),s.jsx(so,{sessionId:t,token:e,connected:n,moduleDir:N.dir,moduleName:N.name,taskStatus:O.status,onSendToTerminal:a,onSetOutputMirror:l})]})]})}async function En(t,e,n={}){const r={};return n.page&&(r.page=String(n.page)),n.limit&&(r.limit=String(n.limit)),n.file&&(r.file=n.file),n.all&&(r.all="true"),n.branch&&(r.branch=n.branch),he.get(e,t,"git-log",r)}async function io(t,e,n,r){const a={commit:n};return r&&(a.file=r),(await he.get(e,t,"git-diff",a)).diff}async function lo(t,e){return he.get(e,t,"git-branches")}const mt=["#0085d9","#d9008f","#3fb950","#d98500","#a300d9","#56d4dd","#e05050","#00d9a3"];function co(t){const e=new Map;if(t.length===0)return e;const n=[],r=[];let a=1;const l=new Map,i=new Map;function u(f){for(let p=0;p<n.length;p++)if(n[p]===null)return n[p]=f,r[p]=p===0?0:a++%mt.length,p;const c=n.length;return n.push(f),r[c]=c===0?0:a++%mt.length,c}for(const f of t){const{hash:c,parents:p}=f,d=p.length>1,m=n.indexOf(c)!==-1;let h=m?n.indexOf(c):u(c);const g=r[h],v=[],C=[];for(let b=0;b<n.length;b++)b!==h&&n[b]===c&&(v.push({fromLane:b,toLane:h,colorIndex:r[b],type:"merge-in"}),n[b]=null);if(p.length===0)n[h]=null;else{n[h]=p[0];for(let b=1;b<p.length;b++){const R=p[b],y=n.indexOf(R);if(y!==-1)v.push({fromLane:y,toLane:h,colorIndex:r[y],type:"merge-in"});else if(l.has(R)){const W=l.get(R),T=i.get(R);v.push({fromLane:W,toLane:h,colorIndex:T,type:"merge-in"})}else{const W=u(R);C.push(W),v.push({fromLane:h,toLane:W,colorIndex:r[W],type:"branch-out"})}}}for(;n.length>0&&n[n.length-1]===null;)n.pop(),r.pop();const j=[];for(let b=0;b<n.length;b++)n[b]!==null&&j.push({lane:b,colorIndex:r[b]});l.set(c,h),i.set(c,g),e.set(c,{lane:h,activeLanes:j,connections:v,colorIndex:g,isMerge:d,newLanes:C,wasExpected:m})}return e}function uo(t){const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<1)return"now";if(n<60)return`${n}m`;const r=Math.floor(n/60);if(r<24)return`${r}h`;const a=Math.floor(r/24);if(a<30)return`${a}d`;const l=Math.floor(a/30);return l<12?`${l}mo`:`${Math.floor(l/12)}y`}const ht=20,ze=32,fo=4,po=5,Ee=ze/2;function Ne(t){return t*ht+ht/2}function Ye(t){return mt[t%mt.length]}function mo(t){if(t.type==="branch-out"){const e=Ne(t.fromLane),n=Ne(t.toLane);if(e===n)return`M ${e} ${Ee} L ${e} ${ze}`;const r=(ze-Ee)*.8;return`M ${e} ${Ee} C ${e} ${Ee+r}, ${n} ${ze-r}, ${n} ${ze}`}else{const e=Ne(t.fromLane),n=Ne(t.toLane);if(e===n)return`M ${e} 0 L ${e} ${Ee}`;const r=Ee*.8;return`M ${e} 0 C ${e} ${r}, ${n} ${Ee-r}, ${n} ${Ee}`}}const ho=o.memo(function({laneNode:e,maxLanes:n}){const r=n*ht,a=e.newLanes;return s.jsxs("svg",{width:r,height:ze,style:{flexShrink:0,display:"block"},children:[e.activeLanes.map(l=>a.includes(l.lane)?null:s.jsx("line",{x1:Ne(l.lane),y1:0,x2:Ne(l.lane),y2:ze,stroke:Ye(l.colorIndex),strokeWidth:2,strokeLinecap:"round"},`active-${l.lane}`)),e.connections.map((l,i)=>s.jsx("path",{d:mo(l),stroke:Ye(l.colorIndex),strokeWidth:2,fill:"none",strokeLinecap:"round"},`conn-${i}`)),e.wasExpected&&!e.activeLanes.some(l=>l.lane===e.lane)&&!a.includes(e.lane)&&s.jsx("line",{x1:Ne(e.lane),y1:0,x2:Ne(e.lane),y2:Ee,stroke:Ye(e.colorIndex),strokeWidth:2,strokeLinecap:"round"}),e.isMerge?s.jsx("circle",{cx:Ne(e.lane),cy:Ee,r:po,fill:"var(--bg-primary)",stroke:Ye(e.colorIndex),strokeWidth:2}):s.jsx("circle",{cx:Ne(e.lane),cy:Ee,r:fo,fill:Ye(e.colorIndex)})]})}),go={head:{bg:"var(--accent-red)",color:"#fff"},branch:{bg:"var(--accent-blue)",color:"#fff"},remote:{bg:"var(--accent-purple)",color:"#fff"},tag:{bg:"var(--accent-green)",color:"#fff"}};function xo({refs:t,fontSize:e}){if(t.length===0)return null;const n=e-4;return s.jsx(s.Fragment,{children:t.map((r,a)=>{const l=go[r.type];return s.jsx("span",{style:{display:"inline-block",padding:"0 4px",borderRadius:3,fontSize:n,lineHeight:`${n+6}px`,backgroundColor:l.bg,color:l.color,whiteSpace:"nowrap",flexShrink:0,fontFamily:"'JetBrains Mono', monospace"},children:r.type==="head"&&r.name!=="HEAD"?`HEAD → ${r.name}`:r.name},a)})})}function bo(t){const e=t.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return e?[parseInt(e[1],10),parseInt(e[2],10)]:[1,1]}const yo=o.memo(function({diff:e,fontSize:n}){if(!e.trim())return s.jsx("div",{style:{padding:8,color:"var(--text-secondary)",fontSize:n},children:"No diff available"});const r=[];let a=null,l=1,i=1;for(const f of e.split(`
|
|
32
|
+
`))if(f.startsWith("@@")){const[c,p]=bo(f);l=c,i=p,a={header:f,lines:[]},r.push(a)}else f.startsWith("diff ")||f.startsWith("index ")||f.startsWith("---")||f.startsWith("+++")||a&&(f.startsWith("+")?a.lines.push({type:"add",text:f,oldNum:null,newNum:i++}):f.startsWith("-")?a.lines.push({type:"del",text:f,oldNum:l++,newNum:null}):a.lines.push({type:"context",text:f,oldNum:l++,newNum:i++}));const u=n*2.6;return s.jsx("div",{style:{fontSize:n,fontFamily:"'JetBrains Mono', monospace",overflow:"auto"},children:r.map((f,c)=>s.jsxs("div",{children:[s.jsx("div",{style:{padding:"2px 8px",paddingLeft:u*2+12,backgroundColor:"var(--bg-secondary)",color:"var(--accent-cyan)",fontSize:n-1,borderTop:c>0?"1px solid var(--border)":void 0},children:f.header}),f.lines.map((p,d)=>s.jsxs("div",{style:{display:"flex",whiteSpace:"pre",backgroundColor:p.type==="add"?"rgba(63, 185, 80, 0.12)":p.type==="del"?"rgba(248, 81, 73, 0.12)":"transparent"},children:[s.jsx("span",{style:{display:"inline-block",width:u,textAlign:"right",paddingRight:4,color:"var(--text-secondary)",opacity:.5,flexShrink:0,userSelect:"none"},children:p.oldNum??""}),s.jsx("span",{style:{display:"inline-block",width:u,textAlign:"right",paddingRight:6,color:"var(--text-secondary)",opacity:.5,flexShrink:0,userSelect:"none",borderRight:"1px solid var(--border)",marginRight:6},children:p.newNum??""}),s.jsx("span",{style:{flex:1,color:p.type==="add"?"var(--accent-green)":p.type==="del"?"var(--accent-red)":"var(--text-primary)"},children:p.text})]},d))]},c))})}),vo=o.memo(function({commit:e,sessionId:n,token:r,fontSize:a,laneNode:l,maxLanes:i}){const[u,f]=o.useState(!1),[c,p]=o.useState(null),[d,m]=o.useState(""),[h,g]=o.useState(!1),[v,C]=o.useState(!1),j=o.useRef(c);j.current=c;const b=o.useCallback(async T=>{if(j.current===T){p(null);return}p(T),g(!0);try{const D=await io(n,r,e.hash,T);m(D)}catch{m("Failed to load diff")}finally{g(!1)}},[n,r,e.hash]),R=a-2,y=a-4,W=i*ht;return s.jsxs("div",{children:[s.jsxs("div",{onClick:()=>f(!u),style:{padding:"2px 8px",cursor:"pointer",display:"flex",flexDirection:"row",alignItems:"center",gap:4,height:ze},onMouseEnter:T=>{T.currentTarget.style.backgroundColor="var(--bg-hover)"},onMouseLeave:T=>{T.currentTarget.style.backgroundColor="transparent"},children:[l&&i>0&&s.jsx(ho,{laneNode:l,maxLanes:i}),s.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:6},children:[s.jsx(xo,{refs:e.refs,fontSize:a}),s.jsx("span",{style:{fontSize:R,color:"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:e.message}),s.jsxs("span",{style:{fontSize:y,color:"var(--text-secondary)",flexShrink:0,whiteSpace:"nowrap"},children:[e.author.split(" ")[0]," · ",uo(e.date)]}),s.jsx("span",{title:"Click to copy full hash",style:{fontSize:y,color:v?"var(--accent-green)":"var(--accent-yellow)",fontFamily:"'JetBrains Mono', monospace",flexShrink:0,opacity:v?1:.6,cursor:"pointer",transition:"color 0.2s, opacity 0.2s"},onClick:T=>{T.stopPropagation(),navigator.clipboard.writeText(e.hash).then(()=>{C(!0),setTimeout(()=>C(!1),1500)})},children:v?"Copied":e.shortHash}),s.jsx("span",{style:{fontSize:y,color:"var(--text-secondary)",flexShrink:0},children:u?"▼":"▶"})]})]}),u&&s.jsx("div",{style:{padding:"0 10px 6px",marginLeft:W+10},children:e.files.length===0?s.jsx("div",{style:{fontSize:R,color:"var(--text-secondary)",padding:"4px 0"},children:"No files changed"}):e.files.map(T=>s.jsxs("div",{children:[s.jsxs("div",{onClick:()=>b(T.path),style:{display:"flex",alignItems:"center",gap:6,padding:"2px 4px",cursor:"pointer",fontSize:a,borderRadius:3},onMouseEnter:D=>{D.currentTarget.style.backgroundColor="var(--bg-hover)"},onMouseLeave:D=>{D.currentTarget.style.backgroundColor="transparent"},children:[s.jsxs("span",{style:{fontSize:y,color:"var(--accent-green)",fontFamily:"'JetBrains Mono', monospace",minWidth:28,textAlign:"right"},children:["+",T.additions]}),s.jsxs("span",{style:{fontSize:y,color:"var(--accent-red)",fontFamily:"'JetBrains Mono', monospace",minWidth:28,textAlign:"right"},children:["-",T.deletions]}),s.jsx("span",{style:{color:c===T.path?"var(--accent-blue)":"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:T.path})]}),c===T.path&&s.jsx("div",{style:{margin:"2px 0 4px",border:"1px solid var(--border)",borderRadius:4,overflow:"hidden",maxHeight:400,overflowY:"auto"},children:h?s.jsx("div",{style:{padding:8,color:"var(--text-secondary)",fontSize:a},children:"Loading..."}):s.jsx(yo,{diff:d,fontSize:a})})]},T.path))})]})}),wo=o.memo(function({sessionId:e,token:n}){const r=A(N=>N.fontSize),[a,l]=o.useState([]),[i,u]=o.useState(1),[f,c]=o.useState(!1),[p,d]=o.useState(!1),[m,h]=o.useState(null),[g,v]=o.useState(""),[C,j]=o.useState(""),[b,R]=o.useState(!1),[y,W]=o.useState([]),[T,D]=o.useState(""),[F,z]=o.useState(""),q=o.useRef(0),E=o.useRef(null);o.useEffect(()=>{lo(e,n).then(({current:N,branches:H})=>{D(N),W(H)}).catch(()=>{})},[e,n]);const w=o.useCallback(async(N,H,O,V,ce)=>{d(!0),h(null);try{const P=await En(e,n,{page:N,file:H||void 0,all:V||void 0,branch:ce||void 0});P.error&&h(P.error),l(J=>O?[...J,...P.commits]:P.commits),c(P.hasMore),u(N)}catch(P){h(P instanceof Error?P.message:"Failed to load")}finally{d(!1)}},[e,n]);o.useEffect(()=>{w(1,g,!1,b,F)},[g,b,F,w]);const I=o.useRef("");o.useEffect(()=>{a.length>0&&(I.current=a[0].hash)},[a]),o.useEffect(()=>{const N=window.setInterval(async()=>{try{const H=await En(e,n,{page:1,limit:1,all:b||void 0,branch:F||void 0,file:g||void 0});H.commits.length>0&&H.commits[0].hash!==I.current&&w(1,g,!1,b,F)}catch{}},3e3);return()=>clearInterval(N)},[e,n,g,b,F,w]);const X=o.useCallback(N=>{const H=N.target.value;j(H),q.current&&clearTimeout(q.current),q.current=window.setTimeout(()=>v(H),300)},[]);o.useEffect(()=>()=>{q.current&&clearTimeout(q.current)},[]);const B=o.useCallback(()=>{!p&&f&&w(i+1,g,!0,b,F)},[p,f,i,g,b,F,w]),G=o.useRef(0),U=o.useCallback(()=>{G.current||(G.current=requestAnimationFrame(()=>{G.current=0;const N=E.current;!N||p||!f||N.scrollTop+N.clientHeight>=N.scrollHeight-50&&B()}))},[p,f,B]);o.useEffect(()=>()=>{G.current&&cancelAnimationFrame(G.current)},[]);const Z=o.useMemo(()=>co(a),[a]),ae=o.useMemo(()=>{let N=0;for(const H of Z.values()){let O=H.lane+1;for(let V=0;V<H.activeLanes.length;V++){const ce=H.activeLanes[V].lane+1;ce>O&&(O=ce)}O>N&&(N=O)}return Math.min(N,15)},[Z]),_=r-2;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",gap:6,borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[s.jsxs("select",{value:b?"__all__":F,onChange:N=>{const H=N.target.value;H==="__all__"?(R(!0),z("")):(R(!1),z(H))},style:{fontSize:_,padding:"1px 2px",border:"1px solid var(--border)",borderRadius:3,backgroundColor:"var(--bg-primary)",color:"var(--text-primary)",outline:"none",flexShrink:0,maxWidth:130},title:"Select branch",children:[s.jsx("option",{value:"",children:T||"HEAD"}),y.filter(N=>N!==T).map(N=>s.jsx("option",{value:N,children:N},N)),s.jsx("option",{value:"__all__",children:"-- All branches --"})]}),s.jsx("input",{type:"text",value:C,onChange:X,placeholder:"Filter by file...",style:{flex:1,fontSize:_,padding:"2px 6px",border:"1px solid var(--border)",borderRadius:3,backgroundColor:"var(--bg-primary)",color:"var(--text-primary)",outline:"none",minWidth:0}})]}),m&&s.jsx("div",{style:{padding:"4px 8px",fontSize:_,color:"var(--accent-red)",backgroundColor:"var(--bg-secondary)"},children:m}),s.jsxs("div",{ref:E,onScroll:U,style:{flex:1,overflowY:"auto",minHeight:0},children:[a.map(N=>s.jsx(vo,{commit:N,sessionId:e,token:n,fontSize:r,laneNode:Z.get(N.hash),maxLanes:ae},N.hash)),p&&s.jsx("div",{style:{padding:12,textAlign:"center",color:"var(--text-secondary)",fontSize:r},children:"Loading..."}),!p&&a.length===0&&!m&&s.jsx("div",{style:{padding:12,textAlign:"center",color:"var(--text-secondary)",fontSize:r},children:"No commits found"}),!p&&f&&s.jsx("div",{style:{padding:8,textAlign:"center"},children:s.jsx("button",{className:"pane-btn",onClick:B,style:{fontSize:_},children:"Load more"})})]})]})});async function So(t,e){try{return(await he.get(t,e,"draft")).content??""}catch{return""}}async function In(t,e,n){try{await he.put(t,e,"draft",{content:n})}catch{}}const Pt="chat-history",Rn=50;function Xn(){try{const t=localStorage.getItem(Pt);return t?JSON.parse(t):[]}catch{return[]}}function ko(t){const n=Xn().filter(r=>r.text!==t);n.unshift({text:t,ts:Date.now()}),n.length>Rn&&(n.length=Rn),localStorage.setItem(Pt,JSON.stringify(n))}const Ln=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/moonview:ai-cli-task",desc:"Task lifecycle management (13 skills)"},{cmd:"/moonview:init",desc:"Initialize task module + branch"},{cmd:"/moonview:plan",desc:"Generate implementation plan"},{cmd:"/moonview:research",desc:"Collect external references"},{cmd:"/moonview:check",desc:"Check feasibility (post-plan/mid/post-exec)"},{cmd:"/moonview:verify",desc:"Run domain-adapted tests"},{cmd:"/moonview:exec",desc:"Execute implementation plan"},{cmd:"/moonview:merge",desc:"Merge task branch to main"},{cmd:"/moonview:report",desc:"Generate completion report"},{cmd:"/moonview:auto",desc:"Autonomous full lifecycle loop"},{cmd:"/moonview:cancel",desc:"Cancel task + optional cleanup"},{cmd:"/moonview:list",desc:"Query task status (read-only)"},{cmd:"/moonview:annotate",desc:"Process Plan panel annotations"},{cmd:"/moonview:summarize",desc:"Regenerate context summary"}],Co=o.forwardRef(function({onSend:e,onContentChange:n,sessionId:r,token:a},l){const i=A(k=>k.fontSize),[u,f]=o.useState(""),c=o.useRef(null),p=o.useRef(void 0),d=o.useRef(!1),m=o.useRef(!1),{pushUndo:h,popUndo:g}=At(),v=o.useRef(u);v.current=u;const C=o.useCallback(()=>h(v.current),[h]),[j,b]=o.useState(!1),[R,y]=o.useState(""),[W,T]=o.useState(0),[D,F]=o.useState(!1),[z,q]=o.useState([]),[E,w]=o.useState(0),[I,X]=o.useState(""),B=o.useRef(null),G=o.useMemo(()=>{if(!I)return z;const k=I.toLowerCase();return z.filter(L=>L.text.toLowerCase().includes(k))},[z,I]),[U,Z]=o.useState(!1),[ae,_]=o.useState(""),[N,H]=o.useState(""),[O,V]=o.useState(0),[ce,P]=o.useState([]),[J,Y]=o.useState(!1),te=o.useRef(""),Q=o.useRef(null),se=o.useMemo(()=>{if(!R)return Ln;const k=R.toLowerCase();return Ln.filter(L=>L.cmd.toLowerCase().includes(k)||L.desc.toLowerCase().includes(k))},[R]),ye=o.useMemo(()=>{let k=ce;if(ae){const L=ae.toLowerCase();k=k.filter(K=>K.name.toLowerCase().includes(L))}return[...k].sort((L,K)=>L.type==="directory"&&K.type!=="directory"?-1:L.type!=="directory"&&K.type==="directory"?1:L.name.localeCompare(K.name))},[ce,ae]),ne=A(k=>k.latency),ke=`chat-draft-${r}`,Re=o.useRef(!1),Le=o.useRef(void 0);o.useEffect(()=>{try{const L=localStorage.getItem(ke);L&&!m.current&&f(L)}catch{}let k=!1;return So(a,r).then(L=>{if(k||m.current){d.current=!0;return}if(L){f(L);try{localStorage.setItem(ke,L)}catch{}}d.current=!0}).catch(()=>{d.current=!0}),()=>{k=!0}},[a,r,ke]),o.useEffect(()=>{if(!d.current)return;p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(ke,u)}catch{}},50),Le.current&&clearTimeout(Le.current);const k=Math.max(200,(ne??30)*3);return Le.current=setTimeout(()=>{Re.current||(Re.current=!0,In(a,r,u).catch(()=>{}).finally(()=>{Re.current=!1}))},k),()=>{p.current&&clearTimeout(p.current),Le.current&&clearTimeout(Le.current)}},[u,a,r,ne,ke]),o.useEffect(()=>{var k;(k=c.current)==null||k.focus()},[]),o.useEffect(()=>{if(!U)return;let k=!1;return Y(!0),(async()=>{try{if(N){if(!te.current){const re=await Me(a,r);if(k)return;te.current=re.cwd}const L=`${te.current}/${N.replace(/\/$/,"")}`,K=await Me(a,r,L);if(k)return;P(K.files)}else{const L=await Me(a,r);if(k)return;te.current=L.cwd,P(L.files)}Y(!1)}catch{if(k)return;P([]),Y(!1)}})(),()=>{k=!0}},[U,N,a,r]),o.useEffect(()=>{if(!U||!Q.current)return;const k=Q.current.querySelector(".file-item--active");k==null||k.scrollIntoView({block:"nearest"})},[O,U]);const _e=o.useCallback(()=>{const k=v.current.trim();if(k){ko(k),e(k),f("");try{localStorage.removeItem(ke)}catch{}In(a,r,"").catch(()=>{})}},[e,a,r,ke]),de=o.useCallback(k=>{C(),f(k),m.current=!0},[C]),Ce=o.useCallback(k=>{const L=c.current;C();const K=v.current;if(L){const re=L.selectionStart,ie=L.selectionEnd,Te=K.slice(0,re)+k+K.slice(ie);f(Te);const ue=re+k.length;requestAnimationFrame(()=>{L.selectionStart=L.selectionEnd=ue,L.focus()})}else f(K+k)},[C]);o.useImperativeHandle(l,()=>({send:_e,fillContent:de,insertAtCursor:Ce}),[_e,de,Ce]),o.useEffect(()=>{n==null||n(u.trim().length>0)},[u,n]);const ge=o.useCallback(()=>{const k=c.current;if(!k)return;const{selectionStart:L,selectionEnd:K}=k;if(L!==K){const re=k.value.substring(L,K);re&&navigator.clipboard.writeText(re).catch(()=>{})}},[]),qe=o.useCallback(()=>{const k=Xn();b(!1),y("");const L=c.current;if(L){const K=L.selectionStart,re=u.slice(0,K),ie=u.slice(K),Te=re.match(/(?:^|\s)(\/history)\s*$/);if(Te){const ue=re.length-Te[1].length;f(u.slice(0,ue)+ie)}}k.length!==0&&(q(k),w(0),X(""),F(!0))},[u]),Be=o.useCallback(k=>{C(),f(k.text),F(!1),requestAnimationFrame(()=>{const L=c.current;L&&(L.selectionStart=L.selectionEnd=k.text.length,L.focus())})},[C]),Pe=o.useCallback(k=>{const L=G[k];if(!L)return;const K=z.filter(ie=>ie.ts!==L.ts||ie.text!==L.text);q(K),localStorage.setItem(Pt,JSON.stringify(K));const re=I?K.filter(ie=>ie.text.toLowerCase().includes(I.toLowerCase())):K;E>=re.length&&w(Math.max(0,re.length-1))},[G,z,E,I]);o.useEffect(()=>{if(!D||!B.current)return;const k=B.current.querySelector(".history-item--active");k==null||k.scrollIntoView({block:"nearest"})},[E,D]);const De=o.useCallback(k=>{if(k==="/history"){qe();return}const L=c.current;if(!L)return;C();const K=L.selectionStart,re=u.slice(0,K),ie=u.slice(K),ue=re.lastIndexOf(`
|
|
33
|
+
`)+1,be=re.slice(ue).match(/\/[a-zA-Z:-]*$/);if(be){const fe=ue+(be.index??0),we=k+" ",Ve=u.slice(0,fe)+we+ie;f(Ve);const We=fe+we.length;requestAnimationFrame(()=>{L.selectionStart=L.selectionEnd=We,L.focus()})}else{const fe=re+k+ie;f(fe);const we=K+k.length;requestAnimationFrame(()=>{L.selectionStart=L.selectionEnd=we,L.focus()})}b(!1),y(""),T(0)},[u,C,qe]),Ae=o.useCallback(k=>{const L=c.current;if(!L)return;C();const K=L.selectionStart,re=u.slice(0,K),ie=u.slice(K),Te=re.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!Te)return;const ue=re.length-Te[0].length;if(k.type==="directory"){const ve="@"+N+k.name+"/",be=u.slice(0,ue)+ve+ie;f(be);const fe=ue+ve.length;H(N+k.name+"/"),_(""),V(0),requestAnimationFrame(()=>{L.selectionStart=L.selectionEnd=fe,L.focus()})}else{const ve=k.name+" ",be=u.slice(0,ue)+ve+ie;f(be);const fe=ue+ve.length;Z(!1),_(""),H(""),V(0),P([]),te.current="",requestAnimationFrame(()=>{L.selectionStart=L.selectionEnd=fe,L.focus()})}},[u,N,C]),tt=o.useCallback(k=>{const L=k.target.value;if(f(L),D){const ve=L.trim();ve?(X(ve),w(0)):X("");return}const K=k.target.selectionStart,re=L.slice(0,K),ie=re.lastIndexOf(`
|
|
34
|
+
`),ue=re.slice(ie+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(ue)b(!0),y(ue[1]),T(0),Z(!1);else{b(!1);const ve=re.match(/@([a-zA-Z0-9_.\-/]*)$/);if(ve){const be=ve[1],fe=be.lastIndexOf("/"),we=fe>=0?be.slice(0,fe+1):"",Ve=fe>=0?be.slice(fe+1):be;_(Ve),V(0),H(we),Z(!0)}else Z(!1)}},[D]),vt=o.useCallback(k=>{if(j&&se.length>0){if(k.key==="ArrowDown"){k.preventDefault(),T(L=>(L+1)%se.length);return}if(k.key==="ArrowUp"){k.preventDefault(),T(L=>(L-1+se.length)%se.length);return}if(k.key==="Enter"||k.key==="Tab"){k.preventDefault(),De(se[W].cmd);return}if(k.key==="Escape"){k.preventDefault(),b(!1);return}}if(U&&ye.length>0){if(k.key==="ArrowDown"){k.preventDefault(),V(L=>(L+1)%ye.length);return}if(k.key==="ArrowUp"){k.preventDefault(),V(L=>(L-1+ye.length)%ye.length);return}if(k.key==="Tab"||k.key==="Enter"){k.preventDefault(),Ae(ye[O]);return}if(k.key==="Escape"){k.preventDefault(),Z(!1);return}}if(D&&G.length>0){if(k.key==="ArrowDown"){k.preventDefault(),w(L=>(L+1)%G.length);return}if(k.key==="ArrowUp"){k.preventDefault(),w(L=>(L-1+G.length)%G.length);return}if(k.key==="Enter"){k.preventDefault(),Be(G[E]);return}if(k.key==="Delete"||k.key==="Backspace"&&(k.ctrlKey||k.metaKey)){k.preventDefault(),Pe(E);return}if(k.key==="Escape"){k.preventDefault(),F(!1);return}}if(k.key==="Tab"){$t(k,f,h);return}k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),_e())},[_e,j,se,W,De,U,ye,O,Ae,h,g,D,G,E,Be,Pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[j&&se.length>0&&s.jsx("div",{className:"slash-dropdown",children:se.map((k,L)=>s.jsxs("div",{className:`slash-item${L===W?" slash-item--active":""}`,onMouseDown:K=>{K.preventDefault(),De(k.cmd)},onMouseEnter:()=>T(L),children:[s.jsx("span",{className:"slash-cmd",children:k.cmd}),s.jsx("span",{className:"slash-desc",children:k.desc})]},k.cmd))}),U&&(J||ye.length>0)&&s.jsx("div",{className:"file-dropdown",ref:Q,children:J?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):ye.map((k,L)=>s.jsxs("div",{className:`file-item${L===O?" file-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ae(k)},onMouseEnter:()=>V(L),children:[s.jsx("span",{className:"file-icon",children:k.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:k.name})]},k.name))}),D&&s.jsx("div",{className:"history-dropdown",ref:B,children:G.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):G.map((k,L)=>s.jsxs("div",{className:`history-item${L===E?" history-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Be(k)},onMouseEnter:()=>w(L),children:[s.jsx("span",{className:"history-text",children:k.text.length>120?k.text.slice(0,120)+"...":k.text}),s.jsx("span",{className:"history-time",children:new Date(k.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:K=>{K.preventDefault(),K.stopPropagation(),Pe(L)},title:"Delete (Del key)",children:"×"})]},`${k.ts}-${L}`))}),s.jsx("textarea",{ref:c,className:"md-editor-textarea",value:u,onChange:tt,onKeyDown:vt,onMouseUp:ge,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${i}px`}})]})});function To({token:t,sessionId:e,onClose:n}){const[r,a]=o.useState([]),[l,i]=o.useState(""),[u,f]=o.useState([]),[c,p]=o.useState(!0),[d,m]=o.useState(!1),h=o.useRef(null);o.useEffect(()=>{let b=!1;return(async()=>{try{const R=await Me(t,e);b||(i(R.cwd),a(R.files))}catch{b||n()}finally{b||p(!1)}})(),()=>{b=!0}},[t,e,n]),o.useEffect(()=>{const b=W=>{W.key==="Escape"&&n()},R=W=>{h.current&&!h.current.contains(W.target)&&n()};document.addEventListener("keydown",b);const y=setTimeout(()=>document.addEventListener("mousedown",R),50);return()=>{document.removeEventListener("keydown",b),document.removeEventListener("mousedown",R),clearTimeout(y)}},[n]);const g=o.useCallback(async b=>{p(!0);try{const R=await Me(t,e,b);f(y=>[...y,l]),i(b),a(R.files)}catch{}finally{p(!1)}},[t,e,l]),v=o.useCallback(async()=>{if(u.length===0)return;const b=u[u.length-1];p(!0);try{const R=await Me(t,e,b);f(y=>y.slice(0,-1)),i(b),a(R.files)}catch{}finally{p(!1)}},[t,e,u]),C=o.useCallback(async b=>{try{await Vs(t,e,b)}catch(R){alert(`Download failed: ${R instanceof Error?R.message:"Unknown error"}`)}},[t,e]),j=o.useCallback(async()=>{m(!0),n();try{await qs(t,e)}catch(b){alert(`Download failed: ${b instanceof Error?b.message:"Unknown error"}`)}finally{m(!1)}},[t,e,n]);return s.jsxs("div",{ref:h,style:{position:"absolute",top:"100%",right:0,marginTop:4,width:300,maxHeight:360,backgroundColor:"var(--bg-primary)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:100,display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[u.length>0&&s.jsx("button",{className:"pane-btn",onClick:v,disabled:c,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),s.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:l.split("/").slice(-2).join("/")||l}),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:c?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(b=>s.jsxs("div",{onClick:()=>{const R=l+"/"+b.name;b.type==="directory"?g(R):C(R)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:R=>{R.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:R=>{R.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{flexShrink:0,fontSize:13},children:b.type==="directory"?"📁":Ys(b.name,b.type)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.name}),b.type==="directory"?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):b.size!=null?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:qn(b.size)}):null]},b.name))}),s.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{className:"pane-btn",onClick:j,disabled:d,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:d?"Downloading...":"Download All (tar.gz)"})})]})}function Nn(t,e,{containerRef:n,axis:r,offset:a=0,min:l,max:i,invert:u=!1,bodyClass:f}){const[c,p]=o.useState(()=>{const h=localStorage.getItem(t);if(h){const g=Number(h);if(Number.isFinite(g)&&g>=l&&g<=i)return g}return e}),d=o.useRef(c);if(c!==d.current){d.current=c;try{localStorage.setItem(t,String(Math.round(c)))}catch{}}const m=o.useCallback(h=>{h.preventDefault();const g=n.current;if(!g)return;const v=g.getBoundingClientRect(),C=r==="x"?v.width:v.height-a,j=r==="x"?v.left:v.top+a;document.body.classList.add(f);const b=y=>{let T=((r==="x"?y.clientX:y.clientY)-j)/C*100;u&&(T=100-T),p(Math.min(i,Math.max(l,T)))},R=()=>{document.body.classList.remove(f),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",R)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",R)},[n,r,a,l,i,u,f]);return[c,m]}const jo=600,Ge=typeof window<"u"?window.matchMedia(`(max-width: ${jo-1}px)`):null;function Eo(){const[t,e]=o.useState(()=>(Ge==null?void 0:Ge.matches)??!1);return o.useEffect(()=>{if(!Ge)return;const n=r=>e(r.matches);return Ge.addEventListener("change",n),()=>Ge.removeEventListener("change",n)},[]),t}const Io=o.memo(function({terminal:e}){const n=Eo(),r=A(_=>_.splitTerminal),a=A(_=>_.token),l=A(_=>_.toggleChat),i=A(_=>_.togglePlan),u=A(_=>_.toggleGitHistory),{chatOpen:f,planOpen:c,gitHistoryOpen:p}=e.panels,d=o.useRef(null),m=o.useRef(null),h=o.useRef(null),g=o.useRef(null),v=o.useRef(null),[C,j]=Nn(`plan-width-${e.id}`,50,{containerRef:m,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[b,R]=Nn(`doc-height-${e.id}`,35,{containerRef:d,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[y,W]=o.useState("");o.useEffect(()=>{if(!a||!e.connected)return;let _=!1;const N=async()=>{try{const O=await vn(a,e.id);_||W(O)}catch{}};N();const H=setInterval(N,5e3);return()=>{_=!0,clearInterval(H)}},[a,e.id,e.connected]);const T=o.useCallback(async _=>{let N;if(a)try{N=await vn(a,e.id)}catch{}r(e.id,_,N)},[a,e.id,r]),[D,F]=o.useState(!1),[z,q]=o.useState(0),[E,w]=o.useState(!1),[I,X]=o.useState(!1),B=async _=>{const N=_.target.files;if(!(!N||N.length===0||!a)){F(!0),q(0);try{await Us(a,e.id,N,H=>{q(H)})}catch(H){alert(`Upload failed: ${H instanceof Error?H.message:"Unknown error"}`)}finally{F(!1),q(0),h.current&&(h.current.value="")}}},G=o.useRef(void 0),U=o.useCallback(_=>{if(g.current){const N=_.replace(/\r?\n/g," ").trimEnd();g.current.sendInput(N),G.current=window.setTimeout(()=>{var H;return(H=g.current)==null?void 0:H.sendInput("\r")},50)}},[]);o.useEffect(()=>()=>{G.current&&clearTimeout(G.current)},[]);const Z=o.useCallback(_=>{if(g.current){const N=_.replace(/\r?\n/g," ").trimEnd();g.current.sendInput(N),setTimeout(()=>{var H;return(H=g.current)==null?void 0:H.sendInput("\r")},50)}},[]),ae=o.useCallback(()=>X(!1),[]);return s.jsxs("div",{ref:d,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),s.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]}),y&&s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:y,children:y})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:h,type:"file",multiple:!0,style:{display:"none"},onChange:B}),s.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=h.current)==null?void 0:_.click()},disabled:D,style:D?{color:"var(--accent-yellow)"}:void 0,title:D?`Uploading ${z}%`:"Upload files","aria-label":"Upload files",children:D?`${z}%`:"↑"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>X(!0),title:"Download files","aria-label":"Download files",children:"↓"}),I&&a&&s.jsx(To,{token:a,sessionId:e.id,onClose:ae})]}),s.jsx("button",{className:`pane-btn${f?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${c?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),s.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>u(e.id),title:"Toggle Git history panel","aria-label":"Toggle Git history panel",children:"Git"}),s.jsx("button",{className:"pane-btn",onClick:()=>T(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:()=>T("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{ref:m,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[(c||p)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{width:`${C}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:[c&&s.jsx(ao,{sessionId:e.id,token:a||"",connected:e.connected,onRequestFileStream:_=>{var N;return(N=g.current)==null?void 0:N.requestFileStream(_)},onSendToTerminal:Z,onSetOutputMirror:_=>{var N;return(N=g.current)==null?void 0:N.setOutputMirror(_)}}),p&&s.jsx(wo,{sessionId:e.id,token:a||""})]}),s.jsx("div",{className:"md-editor-divider-h",onMouseDown:j,style:{width:"3px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:_=>{_.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:_=>{_.currentTarget.style.backgroundColor="var(--border)"}})]}),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(Ss,{ref:g,sessionId:e.id}),!e.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),f&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:R}),s.jsxs("div",{style:{height:`${b}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",height:"22px",flexShrink:0,backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),s.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=v.current)==null?void 0:_.send()},disabled:!E,title:"Send to terminal (Ctrl+Enter)",style:E?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(Co,{ref:v,onSend:U,onContentChange:w,sessionId:e.id,token:a||""})})]})]})]})]}),e.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--accent-red)",color:"var(--accent-red)",fontSize:"11px",flexShrink:0},children:e.error})]})});class Zn extends o.Component{constructor(){super(...arguments);qt(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 Ro=4,Mn=10;function Lo(){const t=A(a=>a.layout),e=A(a=>a.terminalIds.length),n=A(a=>a.addTerminal);if(!t)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=e>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(Qn,{node:t,canClose:r})})}const Qn=o.memo(function({node:e,canClose:n}){return e.type==="leaf"?s.jsx(No,{terminalId:e.terminalId,canClose:n}):s.jsx(Mo,{node:e,canClose:n})}),No=o.memo(function({terminalId:e,canClose:n}){const r=A(l=>l.terminalsMap[e]),a=A(l=>l.reconnectTerminal);return r?s.jsx(Zn,{inline:!0,children:s.jsx(Io,{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:()=>a(e),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",e]})})}),Mo=o.memo(function({node:e,canClose:n}){const r=A(c=>c.setSplitSizes),a=o.useRef(null),l=e.direction==="horizontal",i=o.useRef(e.sizes);i.current=e.sizes;const u=o.useCallback((c,p)=>{p.preventDefault();const d=l?"resizing-panes":"resizing-panes-v";document.body.classList.add(d);const m=l?p.clientX:p.clientY,h=[...i.current],g=a.current,v=l?(g==null?void 0:g.clientWidth)||1:(g==null?void 0:g.clientHeight)||1;let C=null;const j=R=>{C||(C=requestAnimationFrame(()=>{C=null;const T=((l?R.clientX:R.clientY)-m)/v*100,D=h[c]+T,F=h[c+1]-T;if(D>=Mn&&F>=Mn){const z=[...h];z[c]=D,z[c+1]=F,r(e.id,z)}}))},b=()=>{C&&cancelAnimationFrame(C),document.body.classList.remove(d),document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",j),document.addEventListener("mouseup",b)},[l,e.id,r]),f=[];return e.children.forEach((c,p)=>{const d=c.type==="leaf"?c.terminalId:c.id;f.push(s.jsx("div",{style:{flex:`${e.sizes[p]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(Qn,{node:c,canClose:n})},d)),p<e.children.length-1&&f.push(s.jsx("div",{onMouseDown:m=>u(p,m),style:{flex:`0 0 ${Ro}px`,cursor:l?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${p}`))}),s.jsx("div",{ref:a,style:{display:"flex",flexDirection:l?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:f})});function Do({tabId:t}){const e=A(w=>w.tabs.find(I=>I.id===t)),n=A(w=>w.activeTabId),r=A(w=>w.switchTab),a=A(w=>w.closeTab),l=A(w=>w.reopenTab),i=A(w=>w.deleteTab),u=A(w=>w.renameTab),f=A(w=>e?e.terminalIds.map(I=>{const X=w.terminalsMap[I];return X?{id:I,connected:X.connected,active:!0}:{id:I,connected:!1,active:!1}}):[]),c=A(w=>w.disconnectTerminal),p=A(w=>w.reconnectTerminal),d=A(w=>w.killServerSession),[m,h]=o.useState(!1),[g,v]=o.useState(""),[C,j]=o.useState(!1),b=o.useRef(null);if(!e)return null;const R=n===t,y=e.status==="open",W=()=>{y&&r(t)},T=w=>{y&&(w.stopPropagation(),v(e.name),h(!0),setTimeout(()=>{var I;return(I=b.current)==null?void 0:I.focus()},0))},D=()=>{const w=g.trim();w&&u(t,w),h(!1)},F=w=>{w.stopPropagation(),l(t)},z=w=>{w.stopPropagation(),a(t)},q=async w=>{w.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await i(t)},E=w=>{w.stopPropagation(),j(!C)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:W,style:{padding:"8px 12px",cursor:y?"pointer":"default",borderLeft:R?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:R?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:y?1:.5},onMouseEnter:w=>{y&&!R&&(w.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:w=>{R||(w.currentTarget.style.backgroundColor="transparent")},children:[y&&e.terminalIds.length>0&&s.jsx("button",{onClick:E,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:[m?s.jsx("input",{ref:b,value:g,onChange:w=>v(w.target.value),onBlur:D,onKeyDown:w=>{w.key==="Enter"&&D(),w.key==="Escape"&&h(!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:T,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:y?"Double-click to rename":e.name,children:e.name}),s.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",Vn(Math.floor(e.createdAt/1e3))]})]}),y?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:z,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:F,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:q,title:"Delete tab",children:"×"})]})]}),y&&C&&f.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:f.map(w=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${w.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:w.id}),s.jsx("span",{style:{marginLeft:"8px",color:w.active?w.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:w.active?w.connected?"●":"◐":"○"}),w.active?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:I=>{I.stopPropagation(),c(w.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:I=>{I.stopPropagation(),p(w.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:I=>{I.stopPropagation(),window.confirm(`Kill terminal "${w.id}"? This will destroy the tmux session.`)&&d(w.id)},title:"Kill session",children:"×"})]})]},w.id))})]})}function Ao({sessionId:t,active:e,createdAt:n}){const r=A(u=>u.addTerminal),a=A(u=>u.killServerSession),l=()=>{r("horizontal",t)},i=u=>{u.stopPropagation(),window.confirm(`Delete orphaned session "${t}"? This will kill the tmux session.`)&&a(t)};return s.jsxs("div",{onClick:l,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s"},onMouseEnter:u=>{u.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:Vn(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:i,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function $o(){const t=A(c=>c.sidebarOpen),e=A(c=>c.toggleSidebar),n=A(c=>c.fetchSessions),r=A(c=>t?c.serverSessions:[]),a=A(c=>t?c.tabs:[]),l=A(c=>c.terminalIds.length),i=A(c=>c.tabsLoading),u=new Set(a.flatMap(c=>c.terminalIds)),f=r.filter(c=>!u.has(c.sessionId));return o.useEffect(()=>{if(!t)return;n();let c=setInterval(n,5e3);const p=()=>{document.hidden?c&&(clearInterval(c),c=null):(n(),c||(c=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",p),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",p)}},[t,n]),o.useEffect(()=>{if(!t)return;const c=setTimeout(n,800);return()=>clearTimeout(c)},[l,t,n]),s.jsxs("div",{className:"session-sidebar",style:{width:t?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:t?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),s.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),a.length===0?s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):a.map(c=>s.jsx(Do,{tabId:c.id},c.id))]}),!i&&f.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"}),f.map(c=>s.jsx(Ao,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const er=_t.memo(()=>{const t=A(y=>y.tabs),e=A(y=>y.activeTabId),n=A(y=>y.addTab),r=A(y=>y.switchTab),a=A(y=>y.closeTab),l=A(y=>y.renameTab),[i,u]=o.useState(null),[f,c]=o.useState(""),p=o.useRef(null),d=t.filter(y=>y.status==="open");o.useEffect(()=>{i&&p.current&&(p.current.focus(),p.current.select())},[i]);const m=y=>{u(y.id),c(y.name)},h=()=>{i&&f.trim()&&l(i,f.trim()),u(null),c("")},g=()=>{u(null),c("")},v=y=>{y.key==="Enter"?h():y.key==="Escape"&&g()},C=y=>{i||r(y)},j=(y,W)=>{y.stopPropagation(),a(W)},b=(y,W)=>{y.button===1&&(y.preventDefault(),a(W))},R=d.length>1;return s.jsxs("div",{className:"tab-bar",children:[d.map(y=>{const W=y.id===e,T=i===y.id,D=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${W?"tab-item--active":""}`,onClick:()=>C(y.id),onDoubleClick:()=>m(y),onMouseDown:F=>b(F,y.id),children:T?s.jsx("input",{ref:p,type:"text",value:f,onChange:F=>c(F.target.value),onBlur:h,onKeyDown:v,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",D>0&&`(${D})`]}),R&&s.jsx("button",{className:"tab-item__close",onClick:F=>j(F,y.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},y.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});er.displayName="TabBar";function zo(){return localStorage.getItem("ai-cli-online-token")}function _o(){const t=A(p=>p.token),e=A(p=>p.setToken),n=A(p=>p.tabs),r=A(p=>p.addTab),a=A(p=>p.toggleSidebar),l=A(p=>p.fontSize),i=A(p=>p.setFontSize),u=A(p=>p.tabsLoading),f=A(p=>p.theme),c=A(p=>p.toggleTheme);return o.useEffect(()=>{const p=zo();p&&!t&&e(p)},[]),o.useEffect(()=>{t&&!u&&n.filter(p=>p.status==="open").length===0&&r("Default")},[t,u]),t?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.20"]})]}),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(l-1),disabled:l<=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:l}),s.jsx("button",{className:"header-btn",onClick:()=>i(l+1),disabled:l>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(Fo,{}),s.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${f==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:f==="dark"?"☀":"🌙"}),s.jsx("button",{className:"header-btn",onClick:a,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Lo,{})}),s.jsx($o,{})]}),s.jsx(er,{})]}):s.jsx(rs,{})}const Oo=[1,2,3,4];function Fo(){const t=A(r=>r.latency);if(t===null)return s.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let e,n;return t<50?(e="var(--accent-green)",n=4):t<150?(e="var(--accent-yellow)",n=3):t<300?(e="var(--accent-orange)",n=2):(e="var(--accent-red)",n=1),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: ${t}ms`,children:[Oo.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[t,"ms"]})]})}Mt.createRoot(document.getElementById("root")).render(s.jsx(_t.StrictMode,{children:s.jsx(Zn,{children:s.jsx(_o,{})})}));
|
package/web/dist/index.html
CHANGED
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
<!-- LXGW WenKai Mono (中文等宽字体, CDN unicode-range 按需加载) -->
|
|
11
11
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkaimono-regular.css" />
|
|
12
12
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkaimono-bold.css" />
|
|
13
|
-
<script type="module" crossorigin src="/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/assets/index-DG0BJZ53.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">
|
|
17
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
17
|
+
<link rel="stylesheet" crossorigin href="/assets/index-D7cmVR0X.css">
|
|
18
18
|
</head>
|
|
19
19
|
<body>
|
|
20
20
|
<div id="root"></div>
|