ai-cli-online 2.4.2 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
var sn=Object.defineProperty;var an=(e,t,n)=>t in e?sn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var dt=(e,t,n)=>an(e,typeof t!="symbol"?t+"":t,n);import{r as i,a as ln,g as cn,R as rt}from"./react-vendor-BCIvbQoU.js";import{D as Dt,o as Ot,L as dn,x as At}from"./terminal-DnNpv9tw.js";import{d as ot,p as $t}from"./markdown-BERZKN_L.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();var Pt={exports:{}},$e={};/**
|
|
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 un=i,fn=Symbol.for("react.element"),pn=Symbol.for("react.fragment"),mn=Object.prototype.hasOwnProperty,hn=un.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,xn={key:!0,ref:!0,__self:!0,__source:!0};function _t(e,t,n){var r,o={},l=null,c=null;n!==void 0&&(l=""+n),t.key!==void 0&&(l=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)mn.call(t,r)&&!xn.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:fn,type:e,key:l,ref:c,props:o,_owner:hn.current}}$e.Fragment=pn;$e.jsx=_t;$e.jsxs=_t;Pt.exports=$e;var s=Pt.exports,Xe={},ut=ln;Xe.createRoot=ut.createRoot,Xe.hydrateRoot=ut.hydrateRoot;const gn={},ft=e=>{let t;const n=new Set,r=(f,m)=>{const p=typeof f=="function"?f(t):f;if(!Object.is(p,t)){const b=t;t=m??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(h=>h(t,b))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>u,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},u=t=e(r,o,a);return a},bn=e=>e?ft(e):ft;var Bt={exports:{}},Ft={},Ut={exports:{}},Wt={};/**
|
|
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 Ie=i;function yn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var vn=typeof Object.is=="function"?Object.is:yn,wn=Ie.useState,Sn=Ie.useEffect,kn=Ie.useLayoutEffect,Cn=Ie.useDebugValue;function Tn(e,t){var n=t(),r=wn({inst:{value:n,getSnapshot:t}}),o=r[0].inst,l=r[1];return kn(function(){o.value=n,o.getSnapshot=t,Fe(o)&&l({inst:o})},[e,n,t]),Sn(function(){return Fe(o)&&l({inst:o}),e(function(){Fe(o)&&l({inst:o})})},[e]),Cn(n),n}function Fe(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!vn(e,n)}catch{return!0}}function In(e,t){return t()}var En=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?In:Tn;Wt.useSyncExternalStore=Ie.useSyncExternalStore!==void 0?Ie.useSyncExternalStore:En;Ut.exports=Wt;var jn=Ut.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 Pe=i,Rn=jn;function zn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ln=typeof Object.is=="function"?Object.is:zn,Nn=Rn.useSyncExternalStore,Mn=Pe.useRef,Dn=Pe.useEffect,On=Pe.useMemo,An=Pe.useDebugValue;Ft.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var l=Mn(null);if(l.current===null){var c={hasValue:!1,value:null};l.current=c}else c=l.current;l=On(function(){function a(b){if(!u){if(u=!0,f=b,b=r(b),o!==void 0&&c.hasValue){var h=c.value;if(o(h,b))return m=h}return m=b}if(h=m,Ln(f,b))return h;var y=r(b);return o!==void 0&&o(h,y)?(f=b,h):(f=b,m=y)}var u=!1,f,m,p=n===void 0?null:n;return[function(){return a(t())},p===null?void 0:function(){return a(p())}]},[t,n,r,o]);var d=Nn(e,l[0],l[1]);return Dn(function(){c.hasValue=!0,c.value=d},[d]),An(d),d};Bt.exports=Ft;var $n=Bt.exports;const Pn=cn($n),Ht={},{useDebugValue:_n}=rt,{useSyncExternalStoreWithSelector:Bn}=Pn;let pt=!1;const Fn=e=>e;function Un(e,t=Fn,n){(Ht?"production":void 0)!=="production"&&n&&!pt&&(pt=!0);const r=Bn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return _n(r),r}const mt=e=>{const t=typeof e=="function"?bn(e):e,n=(r,o)=>Un(t,r,o);return Object.assign(n,t),n},Wn=e=>e?mt(e):mt,Q="";function se(e){return{Authorization:`Bearer ${e}`}}async function Hn(e){try{const t=await fetch(`${Q}/api/settings/font-size`,{headers:se(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function Kn(e,t){try{await fetch(`${Q}/api/settings/font-size`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function Vn(e){try{const t=await fetch(`${Q}/api/settings/tabs-layout`,{headers:se(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function Gn(e,t){try{await fetch(`${Q}/api/settings/tabs-layout`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function ht(e,t){try{const n=`${Q}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const Oe="ai-cli-online-tabs",xt="ai-cli-online-layout",gt="ai-cli-online-session-names";function Ae(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let c=0;c<e.children.length;c++){const d=Ae(e.children[c],t);d!==null&&(n.push(d),r.push(e.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,d)=>c+d,0),l=r.map(c=>c/o*100);return{...e,children:n,sizes:l}}function Kt(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(l=>Kt(l,t,n,r,o))}}function Vt(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Vt(r,t,n))}}function Ue(e){return e.tabs.find(t=>t.id===e.activeTabId)}function ye(e,t,n){return e.map(r=>r.id===t?n(r):r)}function oe(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(Oe,JSON.stringify(t))}catch{}Jn(t)}let Ne=null,Me=null,Se=null,Re=null;function Jn(e){Re=e,Se&&clearTimeout(Se),Se=setTimeout(()=>{Se=null,Re=null;const t=M.getState().token;t&&Gn(t,e)},2e3)}function Yn(e){Ne&&clearTimeout(Ne),Ne=setTimeout(()=>{Ne=null,oe(e)},500)}function qn(){try{const e=localStorage.getItem(Oe);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(xt);if(e){const t=JSON.parse(e);let n="Default";try{const l=localStorage.getItem(gt);if(l){const c=JSON.parse(l),d=Object.values(c)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Oe,JSON.stringify(o))}catch{}return localStorage.removeItem(xt),localStorage.removeItem(gt),o}}catch{}return null}function te(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function Xn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.tabs){if(c.status!=="open"){const u=c.terminalIds.filter(f=>n.has(f));if(u.length>0){let f=c.layout;for(const m of c.terminalIds)!n.has(m)&&f&&(f=Ae(f,m));r.push({...c,terminalIds:u,layout:f})}continue}const d=c.terminalIds.filter(u=>n.has(u));if(d.length===0)continue;let a=c.layout;for(const u of c.terminalIds)!n.has(u)&&a&&(a=Ae(a,u));r.push({...c,terminalIds:d,layout:a})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(d=>d.status==="open");o=(c==null?void 0:c.id)||""}return{...e,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var t,n;const e=(n=(t=M==null?void 0:M.getState)==null?void 0:t.call(M))==null?void 0:n.token;if(e)if(Re)Se&&(clearTimeout(Se),Se=null),ht(e,Re),Re=null;else{const r=M.getState();r.tabs.length>0&&ht(e,te(r))}});function bt(e,t){const n=e.tabs.find(u=>u.terminalIds.includes(t));if(!n){const{[t]:u,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(u=>u!==t),o=n.layout?Ae(n.layout,t):null,l=ye(e.tabs,n.id,u=>({...u,terminalIds:r,layout:o})),{[t]:c,...d}=e.terminalsMap,a={terminalsMap:d,tabs:l};return n.id===e.activeTabId&&(a.terminalIds=r,a.layout=o),a}const M=Wn((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{var r;if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Hn(n).then(l=>{t().token===n&&e({fontSize:l})});const o=qn();if(o&&o.tabs.length>0){const l={};for(const a of o.tabs)if(a.status==="open")for(const u of a.terminalIds)l[u]={id:u,connected:!1,sessionResumed:!1,error:null,panelMode:((r=a.panelModes)==null?void 0:r[u])||"none"};const c=o.tabs.find(a=>a.id===o.activeTabId&&a.status==="open")||o.tabs.find(a=>a.status==="open"),d=(c==null?void 0:c.id)||"";e({token:n,tabsLoading:!0,terminalsMap:l,tabs:o.tabs,activeTabId:d,nextId:o.nextId,nextSplitId:o.nextSplitId,nextTabId:o.nextTabId,terminalIds:(c==null?void 0:c.terminalIds)||[],layout:(c==null?void 0:c.layout)||null})}else e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Zn(n,o);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(Oe),e({token:n,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:n=>{const r=t(),o=`tab${r.nextTabId}`,l=`t${r.nextId}`,c={id:l,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},d={type:"leaf",terminalId:l},a={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[l],layout:d,createdAt:Date.now()};return e({tabs:[...r.tabs,a],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[l]:c},terminalIds:a.terminalIds,layout:a.layout}),oe(te(t())),o},switchTab:n=>{const o=t().tabs.find(l=>l.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),oe(te(t())))},closeTab:n=>{const r=t(),o=r.tabs.find(m=>m.id===n);if(!o||o.status!=="open"||r.tabs.filter(m=>m.status==="open").length<=1)return;const c={...r.terminalsMap};for(const m of o.terminalIds)delete c[m];const d=ye(r.tabs,n,m=>({...m,status:"closed"}));let a=r.activeTabId,u=r.terminalIds,f=r.layout;if(r.activeTabId===n){const m=r.tabs.findIndex(h=>h.id===n),p=d.filter(h=>h.status==="open"),b=p.find(h=>d.findIndex(k=>k.id===h.id)>m)||p[p.length-1];b&&(a=b.id,u=b.terminalIds,f=b.layout)}e({tabs:d,activeTabId:a,terminalsMap:c,terminalIds:u,layout:f}),oe(te(t()))},reopenTab:n=>{var d;const r=t(),o=r.tabs.find(a=>a.id===n);if(!o||o.status!=="closed")return;const l={...r.terminalsMap};for(const a of o.terminalIds)l[a]={id:a,connected:!1,sessionResumed:!1,error:null,panelMode:((d=o.panelModes)==null?void 0:d[a])||"none"};const c=ye(r.tabs,n,a=>({...a,status:"open"}));e({tabs:c,activeTabId:n,terminalsMap:l,terminalIds:o.terminalIds,layout:o.layout}),oe(te(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(b=>b.id===n);if(!o)return;const l=r.token;l&&await Promise.all(o.terminalIds.map(b=>fetch(`${Q}/api/sessions/${encodeURIComponent(b)}`,{method:"DELETE",headers:se(l)}).catch(()=>{})));const c=t(),d=c.tabs.find(b=>b.id===n);if(!d)return;const a={...c.terminalsMap};for(const b of d.terminalIds)delete a[b];const u=c.tabs.filter(b=>b.id!==n);let f=c.activeTabId,m=c.terminalIds,p=c.layout;if(c.activeTabId===n){const b=u.find(h=>h.status==="open");b?(f=b.id,m=b.terminalIds,p=b.layout):(f="",m=[],p=null)}e({tabs:u,activeTabId:f,terminalsMap:a,terminalIds:m,layout:p}),oe(te(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=ye(t().tabs,n,l=>({...l,name:r}));e({tabs:o}),oe(te(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const l=Ue(o);if(!l){const O=`tab${o.nextTabId}`,D=r||`t${o.nextId}`;let R=o.nextId;const j=D.match(/^t(\d+)$/);j&&(R=Math.max(R,parseInt(j[1],10)+1));const v=r?R:R+1,x={id:D,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},z={type:"leaf",terminalId:D},A={id:O,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[D],layout:z,createdAt:Date.now()};return e({tabs:[...o.tabs,A],activeTabId:O,nextTabId:o.nextTabId+1,nextId:v,terminalsMap:{...o.terminalsMap,[D]:x},terminalIds:[D],layout:z}),oe(te(t())),D}const{nextId:c,nextSplitId:d,terminalsMap:a}=o,{terminalIds:u,layout:f}=l,m=r||`t${c}`;let p=c;const b=m.match(/^t(\d+)$/);b&&(p=Math.max(p,parseInt(b[1],10)+1));const h={id:m,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},y={type:"leaf",terminalId:m};let k,I=d;if(!f)k=y;else if(f.type==="leaf"){const O=n||"horizontal";k={id:`s${I}`,type:"split",direction:O,children:[f,y],sizes:[50,50]},I++}else if(f.direction===(n||"horizontal")){const D=100/(f.children.length+1),R=(100-D)/100,j=[...f.sizes.map(v=>v*R),D];k={...f,children:[...f.children,y],sizes:j}}else{const O=n||"horizontal";k={id:`s${I}`,type:"split",direction:O,children:[f,y],sizes:[50,50]},I++}const C=[...u,m],S=r?p:p+1,w=ye(o.tabs,l.id,O=>({...O,terminalIds:C,layout:k}));return e({terminalsMap:{...a,[m]:h},terminalIds:C,layout:k,tabs:w,nextId:S,nextSplitId:I}),oe(te(t())),m},splitTerminal:(n,r)=>{const o=t(),l=Ue(o);if(!l||!l.layout)return"";const{nextId:c,nextSplitId:d,terminalsMap:a}=o,u=`t${c}`,f={id:u,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},m={type:"leaf",terminalId:u},p=`s${d}`,b=Kt(l.layout,n,r,m,p),h=[...l.terminalIds,u],y=c+1,k=d+1,I=ye(o.tabs,l.id,C=>({...C,terminalIds:h,layout:b}));return e({terminalsMap:{...a,[u]:f},terminalIds:h,layout:b,tabs:I,nextId:y,nextSplitId:k}),oe(te(t())),u},removeTerminal:n=>{const r=bt(t(),n);r&&(e(r),oe(te(t())))},setTerminalConnected:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,error:r}}}})},setTerminalPanelMode:(n,r)=>{const o=t(),l=o.terminalsMap[n];if(!l||l.panelMode===r)return;const c={...o.terminalsMap,[n]:{...l,panelMode:r}},d=o.tabs.find(u=>u.terminalIds.includes(n));let a=o.tabs;if(d){const u={...d.panelModes,[n]:r};a=ye(o.tabs,d.id,f=>({...f,panelModes:u}))}e({terminalsMap:c,tabs:a}),oe(te(t()))},setSplitSizes:(n,r)=>{const o=t(),l=Ue(o);if(!l||!l.layout)return;const c=Vt(l.layout,n,r),d=ye(o.tabs,l.id,a=>({...a,layout:c}));e({layout:c,tabs:d}),Yn(te(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),Me&&clearTimeout(Me),Me=setTimeout(()=>{Me=null;const o=t().token;o&&Kn(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${Q}/api/sessions`,{headers:se(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}},killServerSession:async n=>{const r=t().token;if(!r)return;try{await fetch(`${Q}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:se(r)})}catch{}const o=bt(t(),n);o&&(e(o),oe(te(t()))),setTimeout(()=>t().fetchSessions(),500)}}));async function Zn(e,t){var o,l;const{setState:n,getState:r}=M;try{const[c,d]=await Promise.all([Vn(e),fetch(`${Q}/api/sessions`,{headers:se(e)}).then(h=>h.ok?h.json():[]).catch(()=>[])]);if(r().token!==e)return;const a=c&&((o=c.tabs)==null?void 0:o.length)>0?c:t;if(!a||a.tabs.length===0){n({tabsLoading:!1});return}const u=Xn(a,d);if(!u){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:a.nextId,nextSplitId:a.nextSplitId,nextTabId:a.nextTabId,terminalIds:[],layout:null});return}const f=r().terminalsMap,m={};for(const h of u.tabs)if(h.status==="open")for(const y of h.terminalIds)m[y]=f[y]||{id:y,connected:!1,sessionResumed:!1,error:null,panelMode:((l=h.panelModes)==null?void 0:l[y])||"none"};const p=u.tabs.find(h=>h.id===u.activeTabId&&h.status==="open")||u.tabs.find(h=>h.status==="open"),b=(p==null?void 0:p.id)||"";n({tabsLoading:!1,terminalsMap:m,tabs:u.tabs,activeTabId:b,nextId:u.nextId,nextSplitId:u.nextSplitId,nextTabId:u.nextTabId,terminalIds:(p==null?void 0:p.terminalIds)||[],layout:(p==null?void 0:p.layout)||null}),oe(te(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function Qn(){const[e,t]=i.useState(""),n=M(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, #1a1b26 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"#24283b",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid #292e42"},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, #7aa2f7 0%, #bb9af7 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"#1a1b26",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"#c0caf5",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"#565f89",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:"#7aa2f7",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"#1a1b26",color:"#c0caf5",border:"1px solid #292e42",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:e.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#414868",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"#1a1b26",padding:"2px 6px",borderRadius:"4px",border:"1px solid #292e42",fontSize:"11px"},children:"server/.env"})]})})]})})}const _e=new Map;function er(e,t,n){_e.set(e,{onChunk:t,onControl:n})}function tr(e){_e.delete(e)}function nr(e,t){var n;(n=_e.get(e))==null||n.onChunk(t)}function rr(e,t){var n;(n=_e.get(e))==null||n.onControl(t)}const or=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,De=500,sr=8e3,ir=1e4,yt=4e3,ar=5e3,lr=10,cr=64*1024,dr=1,vt=2,ur=3,fr=4,pr=5,mr=new TextDecoder,hr=new TextEncoder;function wt(e,t){const n=hr.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function xr(e,t,n){const r=i.useRef(null),o=i.useRef(De),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),a=i.useRef(null),u=i.useRef(!1),f=i.useRef(n),m=i.useRef(!1),p=i.useRef(0),b=i.useRef(!0),h=i.useRef(!navigator.onLine),y=i.useRef(""),k=i.useRef(null),I=i.useRef("");f.current=n;const C=i.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),d.current&&(clearTimeout(d.current),d.current=null),l.current&&(clearTimeout(l.current),l.current=null),a.current&&(clearTimeout(a.current),a.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),S=i.useCallback(()=>{const{token:v,setTerminalError:x}=M.getState();if(!v||u.current)return;if(r.current){const N=r.current.readyState;if(N===WebSocket.OPEN||N===WebSocket.CONNECTING)return}m.current=!1;const z=`${or}?sessionId=${encodeURIComponent(t)}`,A=new WebSocket(z);A.binaryType="arraybuffer",a.current=window.setTimeout(()=>{A.readyState===WebSocket.CONNECTING&&A.close()},ar);const _=()=>{A.readyState===WebSocket.OPEN&&(p.current=performance.now(),A.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{p.current>0&&(p.current=0,A.close())},yt))};A.onopen=()=>{a.current&&(clearTimeout(a.current),a.current=null),A.send(JSON.stringify({type:"auth",token:v})),x(t,null),o.current=De,b.current=!0},A.onclose=N=>{const{setTerminalConnected:F,setTerminalError:H,setToken:G}=M.getState();if(F(t,!1),C(),m.current)return;if(N.code===4001){u.current=!0,H(t,"Authentication failed"),G(null),localStorage.removeItem("ai-cli-online-token");return}if(N.code===4002)return;if(N.code===4005){H(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(b.current){b.current=!1,l.current=window.setTimeout(()=>S(),50);return}const J=o.current;o.current=Math.min(J*2,sr);const V=Math.round(J*(.5+Math.random()));l.current=window.setTimeout(()=>{S()},V)},A.onerror=()=>{},A.onmessage=N=>{var F;try{const H=e.current;if(N.data instanceof ArrayBuffer){const J=new Uint8Array(N.data);if(J.length<1)return;const V=J[0],Y=J.subarray(1);switch(V){case dr:H==null||H.write(Y);break;case ur:H==null||H.write(Y);break;case fr:{(F=f.current)==null||F.call(f,mr.decode(Y));break}case pr:{nr(t,Y);break}}return}const G=JSON.parse(N.data);switch(G.type){case"connected":{const J=M.getState();J.setTerminalConnected(t,!0),J.setTerminalResumed(t,G.resumed);const V=e.current;V&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"resize",cols:V.cols,rows:V.rows})),I.current&&(A.send(wt(vt,I.current)),I.current=""),_(),c.current=window.setInterval(_,ir);break}case"error":M.getState().setTerminalError(t,G.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),p.current>0){const J=Math.round(performance.now()-p.current),V=M.getState();(V.terminalIds.length===0||V.terminalIds[0]===t)&&V.setLatency(J),p.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":rr(t,G);break}}catch{}},r.current=A},[t,e,C]),w=i.useCallback(v=>{const x=r.current;if(!x||x.readyState!==WebSocket.OPEN){I.current.length<cr&&(I.current+=v);return}y.current+=v,k.current||(k.current=window.setTimeout(()=>{const z=y.current;y.current="",k.current=null,z&&x.readyState===WebSocket.OPEN&&x.send(wt(vt,z))},lr))},[]),O=i.useCallback((v,x)=>{var z;((z=r.current)==null?void 0:z.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:v,rows:x}))},[]),D=i.useCallback(()=>{var v;((v=r.current)==null?void 0:v.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),R=i.useCallback(v=>{var x;((x=r.current)==null?void 0:x.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:v}))},[]),j=i.useCallback(()=>{var v;((v=r.current)==null?void 0:v.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return i.useEffect(()=>{M.getState().token&&(u.current=!1,S());const x=()=>{h.current=!1,o.current=De,b.current=!0;const _=r.current;(!_||_.readyState===WebSocket.CLOSED||_.readyState===WebSocket.CLOSING)&&S()},z=()=>{h.current=!0},A=()=>{if(document.visibilityState!=="visible")return;const _=r.current;if(!_||_.readyState!==WebSocket.OPEN){!h.current&&!m.current&&(o.current=De,b.current=!0,S());return}p.current=performance.now(),_.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{p.current>0&&(p.current=0,_.close())},yt)};return window.addEventListener("online",x),window.addEventListener("offline",z),document.addEventListener("visibilitychange",A),()=>{m.current=!0,C(),window.removeEventListener("online",x),window.removeEventListener("offline",z),document.removeEventListener("visibilitychange",A),r.current&&(r.current.close(),r.current=null)}},[S,C,t]),{sendInput:w,sendResize:O,requestScrollback:D,requestFileStream:R,cancelFileStream:j}}const Gt={background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",selectionBackground:"#33467c",black:"#15161e",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#414868",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},Jt="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",gr=i.forwardRef(function({sessionId:t},n){const r=i.useRef(null),o=i.useRef(null),l=i.useRef(null),[c,d]=i.useState(!1),[a,u]=i.useState(""),f=M(S=>S.fontSize),m=i.useCallback(S=>{u(S),d(!0)},[]),{sendInput:p,sendResize:b,requestScrollback:h,requestFileStream:y,cancelFileStream:k}=xr(o,t,m);i.useImperativeHandle(n,()=>({sendInput:p,requestFileStream:y,cancelFileStream:k}),[p,y,k]);const I=i.useRef(p),C=i.useRef(b);return I.current=p,C.current=b,i.useEffect(()=>{if(!r.current)return;let S=!1,w=null,O=null,D=null,R=null;if(S||!r.current)return;const j=new Dt({cursorBlink:!0,scrollback:1e4,fontSize:M.getState().fontSize,fontFamily:Jt,theme:Gt,allowProposedApi:!0}),v=new Ot;j.loadAddon(v),j.loadAddon(new dn((N,F)=>{window.open(F,"_blank","noopener,noreferrer")})),j.open(r.current);try{const N=new At;N.onContextLoss(()=>{N.dispose()}),j.loadAddon(N)}catch{}o.current=j,l.current=v,j.onSelectionChange(()=>{const N=j.getSelection();N&&navigator.clipboard.writeText(N).catch(()=>{})});const x=j.element,z=N=>{N.preventDefault(),navigator.clipboard.readText().then(F=>{F&&I.current(F)}).catch(()=>{})};x&&x.addEventListener("contextmenu",z);const A=()=>{try{const N=r.current;if(N&&N.clientWidth>0&&N.clientHeight>0)return v.fit(),C.current(j.cols,j.rows),!0}catch{}return!1};requestAnimationFrame(()=>A());let _=0;return w=setInterval(()=>{_++,(A()||_>=10)&&(clearInterval(w),w=null)},100),document.fonts.ready.then(()=>{if(!S)try{v.fit(),C.current(j.cols,j.rows)}catch{}}),j.onData(N=>{I.current(N)}),R=new ResizeObserver(()=>{O||(O=requestAnimationFrame(()=>{O=null;try{v.fit(),D&&clearTimeout(D),D=setTimeout(()=>{D=null,C.current(j.cols,j.rows)},50)}catch{}}))}),R.observe(r.current),()=>{S=!0,w&&clearInterval(w),O&&cancelAnimationFrame(O),D&&clearTimeout(D),R&&R.disconnect(),x&&x.removeEventListener("contextmenu",z),o.current&&(o.current.dispose(),o.current=null),l.current=null}},[t]),i.useEffect(()=>{const S=o.current,w=l.current;if(!(!S||!w)&&S.options.fontSize!==f){S.options.fontSize=f;try{w.fit()}catch{}C.current(S.cols,S.rows)}},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"#1a1b26",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:S=>{S.currentTarget.blur(),c?(d(!1),u("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:S=>{S.currentTarget.style.opacity="1"},onMouseLeave:S=>{S.currentTarget.style.opacity="0.8"},children:c?"✕":s.jsx("span",{style:{fontSize:16},children:"👁"})}),c&&s.jsx(br,{data:a,onClose:()=>{d(!1),u("")}})]})});function br({data:e,onClose:t}){const n=i.useRef(null),r=i.useRef(t);r.current=t;const o=M(a=>a.fontSize),l=i.useRef(null),c=i.useRef(null);i.useEffect(()=>{if(!n.current)return;const a=new Dt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:Jt,theme:Gt});l.current=a;const u=new Ot;c.current=u,a.loadAddon(u),a.open(n.current);try{const y=new At;y.onContextLoss(()=>y.dispose()),a.loadAddon(y)}catch{}a.onSelectionChange(()=>{const y=a.getSelection();y&&navigator.clipboard.writeText(y).catch(()=>{})}),a.attachCustomKeyEventHandler(y=>(y.key==="Escape"&&r.current(),!1)),a.write(e);let f=null;const m=()=>{const y=n.current;if(!y||y.clientWidth<=0||y.clientHeight<=0)return!1;try{return u.fit(),a.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!m()){let y=0;f=setInterval(()=>{y++,(m()||y>=30)&&(clearInterval(f),f=null)},50)}});let p=null;const b=new ResizeObserver(()=>{p||(p=requestAnimationFrame(()=>{p=null,m()}))});b.observe(n.current);const h=y=>{y.key==="Escape"&&r.current()};return document.addEventListener("keydown",h),()=>{f&&clearInterval(f),p&&cancelAnimationFrame(p),document.removeEventListener("keydown",h),b.disconnect(),a.dispose(),l.current=null,c.current=null}},[e]),i.useEffect(()=>{var a;if(l.current){l.current.options.fontSize=o;try{(a=c.current)==null||a.fit()}catch{}}},[o]);const d=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26"},children:[s.jsx("div",{style:{height:d,boxSizing:"border-box",padding:"0 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",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:d,left:0,right:0,bottom:0,overflow:"hidden"}})]})}async function Te(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:se(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function yr(e,t,n,r){return new Promise((o,l)=>{const c=new FormData;for(const a of n)c.append("files",a);const d=new XMLHttpRequest;d.open("POST",`${Q}/api/sessions/${encodeURIComponent(t)}/upload`),d.setRequestHeader("Authorization",`Bearer ${e}`),d.upload.addEventListener("progress",a=>{a.lengthComputable&&r&&r(Math.round(a.loaded/a.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?o():l(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>l(new Error("Upload network error"))),d.addEventListener("abort",()=>l(new Error("Upload aborted"))),d.send(c)})}async function vr(e,t){const n=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:se(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function wr(e,t,n){const r=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/touch`,{method:"POST",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error("Failed to create file");return r.json()}async function Sr(e,t,n){const r=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:se(e)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),l=URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l)}function st({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=M(S=>S.token),[l,c]=i.useState(""),[d,a]=i.useState([]),[u,f]=i.useState(!0),[m,p]=i.useState(null),b=i.useRef(""),h=i.useCallback(async S=>{if(o){f(!0),p(null);try{const w=await Te(o,e,S);S||(b.current=w.cwd),c(w.cwd),a(n?n(w.files):w.files)}catch(w){p(w instanceof Error?w.message:"Failed to load files")}finally{f(!1)}}},[o,e,n]);i.useEffect(()=>{h()},[h]),i.useEffect(()=>{if(!r||!o)return;let S=!1;const w=setInterval(async()=>{if(!S)try{const O=await vr(o,e);if(S)return;if(O!==b.current){b.current=O;const D=await Te(o,e);if(S)return;c(D.cwd),a(n?n(D.files):D.files)}}catch{}},r);return()=>{S=!0,clearInterval(w)}},[r,o,e,n]);const y=i.useRef(t);y.current=t,i.useEffect(()=>{const S=w=>{w.key==="Escape"&&y.current()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[]);const k=i.useCallback(S=>{h(l+"/"+S)},[h,l]),I=i.useCallback(()=>{const S=l.replace(/\/[^/]+$/,"")||"/";h(S)},[h,l]),C=i.useCallback(()=>{h(l)},[h,l]);return{cwd:l,files:d,loading:u,error:m,setError:p,handleNavigate:k,handleGoUp:I,handleRefresh:C}}function it(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Yt(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function qt(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function at({cwd:e,onGoUp:t,onRefresh:n,onClose:r}){return s.jsxs("div",{style:{padding:"6px 12px",background:"#24283b",borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[s.jsx("button",{onClick:t,style:{background:"none",border:"1px solid #414868",color:"#7aa2f7",borderRadius:3,padding:"1px 8px",fontSize:12,cursor:"pointer",flexShrink:0},title:"Go to parent directory",children:".."}),s.jsx("span",{style:{color:"#7aa2f7",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e||"..."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[s.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Refresh",children:"↻"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Close (ESC)",children:"✕"})]})]})}function lt({loading:e,error:t,empty:n,emptyText:r="Empty directory"}){return e?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):t?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:t}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function kr({sessionId:e,onClose:t}){const n=M(h=>h.token),{cwd:r,files:o,loading:l,error:c,setError:d,handleNavigate:a,handleGoUp:u,handleRefresh:f}=st({sessionId:e,onClose:t}),[m,p]=i.useState(null),b=async h=>{if(n){p(h);try{await Sr(n,e,r+"/"+h)}catch(y){d(y instanceof Error?y.message:"Download failed")}finally{p(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(at,{cwd:r,onGoUp:u,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(lt,{loading:l,error:c,empty:o.length===0,emptyText:"Empty directory"}),!l&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&a(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:y=>{y.stopPropagation(),b(h.name)},disabled:m===h.name,style:{background:"none",border:"1px solid #414868",color:m===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:m===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:m===h.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:h.type==="directory"?"#7aa2f7":"#565f89"},children:h.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:h.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:h.type==="file"?it(h.size):""})]},h.name))]})]})}let Ee=null;const Cr=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"];function Tr(e){return e.initialize({startOnLoad:!1,theme:"dark",themeVariables:{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"},gantt:{titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800}}),e}function Ir(){return Ee||(Ee=(async()=>{for(const e of Cr)try{const t=await import(e);return Tr(t.default)}catch{}throw Ee=null,new Error("All mermaid CDN sources failed")})(),Ee)}let Er=0;function Xt(e,t){i.useEffect(()=>{const n=e.current;if(!n)return;const r=n.querySelectorAll("code.language-mermaid, code.language-gantt");if(r.length===0)return;let o=!1;return(async()=>{let l;try{l=await Ir()}catch{if(o)return;for(const d of r){const a=d.parentElement;if(!a||a.tagName!=="PRE")continue;a.classList.add("mermaid-error");const u=document.createElement("div");u.className="mermaid-error__msg",u.textContent="Failed to load Mermaid library",a.appendChild(u)}return}if(!o)for(const c of r){if(o)break;const d=c.parentElement;if(!d||d.tagName!=="PRE")continue;const a=c.textContent||"";if(!a.trim())continue;const u=`mermaid-${++Er}`;try{const{svg:f}=await l.render(u,a);if(o)break;const m=document.createElement("div");m.className="mermaid-diagram",m.innerHTML=f,d.replaceWith(m)}catch{if(o)break;d.classList.add("mermaid-error");const f=document.createElement("div");f.className="mermaid-error__msg",f.textContent="Mermaid syntax error",d.appendChild(f)}}})(),()=>{o=!0}},[t])}function jr({content:e}){const t=M(o=>o.fontSize),n=i.useRef(null),r=i.useMemo(()=>{if(!e)return"";const o=ot.parse(e,{async:!1});return $t.sanitize(o,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[e]);return Xt(n,r),e?s.jsx("div",{ref:n,className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${t}px`},dangerouslySetInnerHTML:{__html:r}}):s.jsx("div",{className:"md-preview",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#414868",fontStyle:"italic",fontSize:"13px"},children:"Waiting for plan output..."})}async function Rr(e,t){const n=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:se(e)});return n.ok?(await n.json()).content??"":""}async function St(e,t,n){await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const zr=50;function Ze(){const e=i.useRef([]),t=i.useCallback(o=>{e.current.push(o),e.current.length>zr&&e.current.shift()},[]),n=i.useCallback(()=>e.current.pop(),[]),r=i.useCallback(()=>{e.current=[]},[]);return i.useMemo(()=>({pushUndo:t,popUndo:n,clearUndo:r}),[t,n,r])}function Qe(e,t,n){e.preventDefault();const r=e.currentTarget,o=r.selectionStart,l=r.selectionEnd,c=r.value;n==null||n(c);const d=c.slice(0,o)+" "+c.slice(l);t(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function et(e,t,n){const r=t();return r!==void 0?(e.preventDefault(),n(r),!0):!1}function tt(e,t=10){var n;return Math.min(t,Math.max(1,(((n=e.match(/\n/g))==null?void 0:n.length)??0)+1))}const ct="chat-history",kt=50;function Zt(){try{const e=localStorage.getItem(ct);return e?JSON.parse(e):[]}catch{return[]}}function Lr(e){const n=Zt().filter(r=>r.text!==e);n.unshift({text:e,ts:Date.now()}),n.length>kt&&(n.length=kt),localStorage.setItem(ct,JSON.stringify(n))}const Ct=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],Nr=i.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},l){const c=M(g=>g.fontSize),[d,a]=i.useState(""),u=i.useRef(null),f=i.useRef(void 0),m=i.useRef(!1),{pushUndo:p,popUndo:b}=Ze(),h=i.useRef(d);h.current=d;const y=i.useCallback(()=>p(h.current),[p]),[k,I]=i.useState(!1),[C,S]=i.useState(""),[w,O]=i.useState(0),[D,R]=i.useState(!1),[j,v]=i.useState([]),[x,z]=i.useState(0),[A,_]=i.useState(""),N=i.useRef(null),F=i.useMemo(()=>{if(!A)return j;const g=A.toLowerCase();return j.filter(T=>T.text.toLowerCase().includes(g))},[j,A]),[H,G]=i.useState(!1),[J,V]=i.useState(""),[Y,me]=i.useState(""),[he,ee]=i.useState(0),[de,xe]=i.useState([]),[ue,be]=i.useState(!1),ae=i.useRef(""),fe=i.useRef(null),L=i.useMemo(()=>{if(!C)return Ct;const g=C.toLowerCase();return Ct.filter(T=>T.cmd.toLowerCase().includes(g)||T.desc.toLowerCase().includes(g))},[C]),E=i.useMemo(()=>{let g=de;if(J){const T=J.toLowerCase();g=g.filter(U=>U.name.toLowerCase().includes(T))}return[...g].sort((T,U)=>T.type==="directory"&&U.type!=="directory"?-1:T.type!=="directory"&&U.type==="directory"?1:T.name.localeCompare(U.name))},[de,J]);i.useEffect(()=>{let g=!1;return Rr(o,r).then(T=>{!g&&T&&a(T),m.current=!0}).catch(()=>{m.current=!0}),()=>{g=!0}},[o,r]),i.useEffect(()=>{if(m.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{St(o,r,d).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[d,o,r]),i.useEffect(()=>{var g;(g=u.current)==null||g.focus()},[]),i.useEffect(()=>{if(!H)return;let g=!1;return be(!0),(async()=>{try{if(Y){if(!ae.current){const q=await Te(o,r);if(g)return;ae.current=q.cwd}const T=`${ae.current}/${Y.replace(/\/$/,"")}`,U=await Te(o,r,T);if(g)return;xe(U.files)}else{const T=await Te(o,r);if(g)return;ae.current=T.cwd,xe(T.files)}be(!1)}catch{if(g)return;xe([]),be(!1)}})(),()=>{g=!0}},[H,Y,o,r]),i.useEffect(()=>{if(!H||!fe.current)return;const g=fe.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[he,H]);const $=i.useCallback(()=>{const g=h.current.trim();g&&(Lr(g),t(g),a(""),St(o,r,"").catch(()=>{}))},[t,o,r]),B=i.useCallback(g=>{y(),a(g)},[y]);i.useImperativeHandle(l,()=>({send:$,fillContent:B}),[$,B]),i.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const W=i.useCallback(()=>{const g=Zt();I(!1),S("");const T=u.current;if(T){const U=T.selectionStart,q=d.slice(0,U),re=d.slice(U),we=q.match(/(?:^|\s)(\/history)\s*$/);if(we){const le=q.length-we[1].length;a(d.slice(0,le)+re)}}g.length!==0&&(v(g),z(0),_(""),R(!0))},[d]),ne=i.useCallback(g=>{y(),a(g.text),R(!1),requestAnimationFrame(()=>{const T=u.current;T&&(T.selectionStart=T.selectionEnd=g.text.length,T.focus())})},[y]),P=i.useCallback(g=>{const T=F[g];if(!T)return;const U=j.filter(re=>re.ts!==T.ts||re.text!==T.text);v(U),localStorage.setItem(ct,JSON.stringify(U));const q=A?U.filter(re=>re.text.toLowerCase().includes(A.toLowerCase())):U;x>=q.length&&z(Math.max(0,q.length-1))},[F,j,x,A]);i.useEffect(()=>{if(!D||!N.current)return;const g=N.current.querySelector(".history-item--active");g==null||g.scrollIntoView({block:"nearest"})},[x,D]);const K=i.useCallback(g=>{if(g==="/history"){W();return}const T=u.current;if(!T)return;y();const U=T.selectionStart,q=d.slice(0,U),re=d.slice(U),le=q.lastIndexOf(`
|
|
26
|
+
`)+1,pe=q.slice(le).match(/\/[a-zA-Z:-]*$/);if(pe){const ie=le+(pe.index??0),ke=g+" ",Be=d.slice(0,ie)+ke+re;a(Be);const on=ie+ke.length;requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=on,T.focus()})}else{const ie=q+g+re;a(ie);const ke=U+g.length;requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=ke,T.focus()})}I(!1),S(""),O(0)},[d,y,W]),X=i.useCallback(g=>{const T=u.current;if(!T)return;y();const U=T.selectionStart,q=d.slice(0,U),re=d.slice(U),we=q.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!we)return;const le=q.length-we[0].length;if(g.type==="directory"){const ce="@"+Y+g.name+"/",pe=d.slice(0,le)+ce+re;a(pe);const ie=le+ce.length;me(Y+g.name+"/"),V(""),ee(0),requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=ie,T.focus()})}else{const ce=g.name+" ",pe=d.slice(0,le)+ce+re;a(pe);const ie=le+ce.length;G(!1),V(""),me(""),ee(0),xe([]),ae.current="",requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=ie,T.focus()})}},[d,Y,y]),Z=i.useCallback(g=>{const T=g.target.value;if(a(T),D){const ce=T.trim();ce?(_(ce),z(0)):_("");return}const U=g.target.selectionStart,q=T.slice(0,U),re=q.lastIndexOf(`
|
|
27
|
+
`),le=q.slice(re+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(le)I(!0),S(le[1]),O(0),G(!1);else{I(!1);const ce=q.match(/@([a-zA-Z0-9_.\-/]*)$/);if(ce){const pe=ce[1],ie=pe.lastIndexOf("/"),ke=ie>=0?pe.slice(0,ie+1):"",Be=ie>=0?pe.slice(ie+1):pe;V(Be),ee(0),me(ke),G(!0)}else G(!1)}},[D]),ge=i.useCallback(g=>{if(k&&L.length>0){if(g.key==="ArrowDown"){g.preventDefault(),O(T=>(T+1)%L.length);return}if(g.key==="ArrowUp"){g.preventDefault(),O(T=>(T-1+L.length)%L.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),K(L[w].cmd);return}if(g.key==="Escape"){g.preventDefault(),I(!1);return}}if(H&&E.length>0){if(g.key==="ArrowDown"){g.preventDefault(),ee(T=>(T+1)%E.length);return}if(g.key==="ArrowUp"){g.preventDefault(),ee(T=>(T-1+E.length)%E.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),X(E[he]);return}if(g.key==="Escape"){g.preventDefault(),G(!1);return}}if(D&&F.length>0){if(g.key==="ArrowDown"){g.preventDefault(),z(T=>(T+1)%F.length);return}if(g.key==="ArrowUp"){g.preventDefault(),z(T=>(T-1+F.length)%F.length);return}if(g.key==="Enter"){g.preventDefault(),ne(F[x]);return}if(g.key==="Delete"||g.key==="Backspace"&&(g.ctrlKey||g.metaKey)){g.preventDefault(),P(x);return}if(g.key==="Escape"){g.preventDefault(),R(!1);return}}if(g.key==="z"&&(g.ctrlKey||g.metaKey)&&!g.shiftKey){et(g,b,a);return}if(g.key==="Tab"){Qe(g,a,p);return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),$())},[$,k,L,w,K,H,E,he,X,p,b,D,F,x,ne,P]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[k&&L.length>0&&s.jsx("div",{className:"slash-dropdown",children:L.map((g,T)=>s.jsxs("div",{className:`slash-item${T===w?" slash-item--active":""}`,onMouseDown:U=>{U.preventDefault(),K(g.cmd)},onMouseEnter:()=>O(T),children:[s.jsx("span",{className:"slash-cmd",children:g.cmd}),s.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),H&&(ue||E.length>0)&&s.jsx("div",{className:"file-dropdown",ref:fe,children:ue?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):E.map((g,T)=>s.jsxs("div",{className:`file-item${T===he?" file-item--active":""}`,onMouseDown:U=>{U.preventDefault(),X(g)},onMouseEnter:()=>ee(T),children:[s.jsx("span",{className:"file-icon",children:g.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:g.name})]},g.name))}),D&&s.jsx("div",{className:"history-dropdown",ref:N,children:F.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):F.map((g,T)=>s.jsxs("div",{className:`history-item${T===x?" history-item--active":""}`,onMouseDown:U=>{U.preventDefault(),ne(g)},onMouseEnter:()=>z(T),children:[s.jsx("span",{className:"history-text",children:g.text.length>120?g.text.slice(0,120)+"...":g.text}),s.jsx("span",{className:"history-time",children:new Date(g.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:U=>{U.preventDefault(),U.stopPropagation(),P(T)},title:"Delete (Del key)",children:"×"})]},`${g.ts}-${T}`))}),s.jsx("textarea",{ref:u,className:"md-editor-textarea",value:d,onChange:Z,onKeyDown:ge,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function Mr({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:l,error:c,handleNavigate:d,handleGoUp:a,handleRefresh:u}=st({sessionId:e,onClose:n}),f=(m,p)=>{t(r+"/"+m,p)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(at,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(lt,{loading:l,error:c,empty:o.length===0,emptyText:"No files found"}),!l&&!c&&o.map(m=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent"},onClick:()=>{m.type==="directory"?d(m.name):f(m.name,m.size)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:m.type==="directory"?"#7aa2f7":"#565f89"},children:Yt(m.name,m.type)}),s.jsx("span",{style:{flex:1,color:m.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m.name}),m.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:it(m.size)})]},m.name))]})]})}const Dr="modulepreload",Or=function(e){return"/"+e},Tt={},Ar=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(a=>{if(a=Or(a),a in Tt)return;Tt[a]=!0;const u=a.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${f}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":Dr,u||(m.as="script"),m.crossOrigin="",m.href=a,d&&m.setAttribute("nonce",d),document.head.appendChild(m),u)return new Promise((p,b)=>{m.addEventListener("load",p),m.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${a}`)))})}))}function l(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&l(d.reason);return t().catch(l)})};let nt=null,We=null;function $r(){return We||(We=Ar(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(nt=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),We}function Pr({data:e,scrollRef:t}){const n=i.useRef(null),[r,o]=i.useState(null),[l,c]=i.useState(!0),d=i.useRef(0),a=u=>{n.current=u,t==null||t(u)};return i.useEffect(()=>{if(!e)return;const u=++d.current;return c(!0),o(null),(async()=>{try{if(await $r(),!nt||u!==d.current)return;let f;if(e instanceof Uint8Array)f=e;else{const h=atob(e);f=new Uint8Array(h.length);for(let y=0;y<h.length;y++)f[y]=h.charCodeAt(y)}const m=await nt.getDocument({data:f}).promise;if(u!==d.current)return;const p=n.current;if(!p)return;for(;p.firstChild;)p.removeChild(p.firstChild);const b=p.clientWidth-24;for(let h=1;h<=m.numPages;h++){const y=await m.getPage(h);if(u!==d.current)return;const k=y.getViewport({scale:1}),I=Math.min(b/k.width,2),C=y.getViewport({scale:I}),S=document.createElement("canvas");S.width=C.width,S.height=C.height,S.style.display="block",S.style.margin="0 auto 8px",S.style.maxWidth="100%";const w=S.getContext("2d");if(w){if(await y.render({canvasContext:w,viewport:C,canvas:S}).promise,u!==d.current)return;p.appendChild(S)}}c(!1)}catch(f){if(u!==d.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{d.current++}},[e]),s.jsxs("div",{ref:a,className:"pdf-renderer",children:[l&&s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading PDF..."}),r&&s.jsxs("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:["PDF Error: ",r]})]})}const Le=typeof window<"u"?i.useLayoutEffect:i.useEffect;function It(e){if(e!==void 0)switch(typeof e){case"number":return e;case"string":{if(e.endsWith("px"))return parseFloat(e);break}}}function _r({box:e,defaultHeight:t,defaultWidth:n,disabled:r,element:o,mode:l,style:c}){const{styleHeight:d,styleWidth:a}=i.useMemo(()=>({styleHeight:It(c==null?void 0:c.height),styleWidth:It(c==null?void 0:c.width)}),[c==null?void 0:c.height,c==null?void 0:c.width]),[u,f]=i.useState({height:t,width:n}),m=r||d!==void 0||l==="only-width"||d!==void 0&&a!==void 0;return Le(()=>{if(o===null||m)return;const p=new ResizeObserver(b=>{for(const h of b){const{contentRect:y,target:k}=h;o===k&&f(I=>I.height===y.height&&I.width===y.width?I:{height:y.height,width:y.width})}});return p.observe(o,{box:e}),()=>{p==null||p.unobserve(o)}},[e,m,o,d,a]),i.useMemo(()=>({height:d??u.height,width:a??u.width}),[u,d,a])}function Br(e){const t=i.useRef(()=>{throw new Error("Cannot call during render.")});return Le(()=>{t.current=e},[e]),i.useCallback(n=>{var r;return(r=t.current)==null?void 0:r.call(t,n)},[t])}function He({containerElement:e,direction:t,isRtl:n,scrollOffset:r}){return r}function ve(e,t="Assertion error"){if(!e)throw Error(t)}function ze(e,t){if(e===t)return!0;if(!!e!=!!t||(ve(e!==void 0),ve(t!==void 0),Object.keys(e).length!==Object.keys(t).length))return!1;for(const n in e)if(!Object.is(t[n],e[n]))return!1;return!0}function Qt({cachedBounds:e,itemCount:t,itemSize:n}){if(t===0)return 0;if(typeof n=="number")return t*n;{const r=e.get(e.size===0?0:e.size-1);ve(r!==void 0,"Unexpected bounds cache miss");const o=(r.scrollOffset+r.size)/e.size;return t*o}}function Fr({align:e,cachedBounds:t,index:n,itemCount:r,itemSize:o,containerScrollOffset:l,containerSize:c}){if(n<0||n>=r)throw RangeError(`Invalid index specified: ${n}`,{cause:`Index ${n} is not within the range of 0 - ${r-1}`});const d=Qt({cachedBounds:t,itemCount:r,itemSize:o}),a=t.get(n),u=Math.max(0,Math.min(d-c,a.scrollOffset)),f=Math.max(0,a.scrollOffset-c+a.size);switch(e==="smart"&&(l>=f&&l<=u?e="auto":e="center"),e){case"start":return u;case"end":return f;case"center":return a.scrollOffset<=c/2?0:a.scrollOffset+a.size/2>=d-c/2?d-c:a.scrollOffset+a.size/2-c/2;case"auto":default:return l>=f&&l<=u?l:l<f?f:u}}function Ke({cachedBounds:e,containerScrollOffset:t,containerSize:n,itemCount:r,overscanCount:o}){const l=r-1;let c=0,d=-1,a=0,u=-1,f=0;for(;f<l;){const m=e.get(f);if(m.scrollOffset+m.size>t)break;f++}for(c=f,a=Math.max(0,c-o);f<l;){const m=e.get(f);if(m.scrollOffset+m.size>=t+n)break;f++}return d=Math.min(l,f),u=Math.min(r-1,d+o),c<0&&(c=0,d=-1,a=0,u=-1),{startIndexVisible:c,stopIndexVisible:d,startIndexOverscan:a,stopIndexOverscan:u}}function Ur({itemCount:e,itemProps:t,itemSize:n}){const r=new Map;return{get(o){for(ve(o<e,`Invalid index ${o}`);r.size-1<o;){const c=r.size;let d;switch(typeof n){case"function":{d=n(c,t);break}case"number":{d=n;break}}if(c===0)r.set(c,{size:d,scrollOffset:0});else{const a=r.get(c-1);ve(a!==void 0,`Unexpected bounds cache miss for index ${o}`),r.set(c,{scrollOffset:a.scrollOffset+a.size,size:d})}}const l=r.get(o);return ve(l!==void 0,`Unexpected bounds cache miss for index ${o}`),l},set(o,l){r.set(o,l)},get size(){return r.size}}}function Wr({itemCount:e,itemProps:t,itemSize:n}){return i.useMemo(()=>Ur({itemCount:e,itemProps:t,itemSize:n}),[e,t,n])}function Hr({containerSize:e,itemSize:t}){let n;switch(typeof t){case"string":{ve(t.endsWith("%"),`Invalid item size: "${t}"; string values must be percentages (e.g. "100%")`),ve(e!==void 0,"Container size must be defined if a percentage item size is specified"),n=e*parseInt(t)/100;break}default:{n=t;break}}return n}function Kr({containerElement:e,containerStyle:t,defaultContainerSize:n=0,direction:r,isRtl:o=!1,itemCount:l,itemProps:c,itemSize:d,onResize:a,overscanCount:u}){const{height:f=n,width:m=n}=_r({defaultHeight:n,defaultWidth:void 0,element:e,mode:"only-height",style:t}),p=i.useRef({height:0,width:0}),b=f,h=Hr({containerSize:b,itemSize:d});i.useLayoutEffect(()=>{if(typeof a=="function"){const x=p.current;(x.height!==f||x.width!==m)&&(a({height:f,width:m},{...x}),x.height=f,x.width=m)}},[f,a,m]);const y=Wr({itemCount:l,itemProps:c,itemSize:h}),k=i.useCallback(x=>y.get(x),[y]),[I,C]=i.useState(()=>Ke({cachedBounds:y,containerScrollOffset:0,containerSize:b,itemCount:l,overscanCount:u})),{startIndexVisible:S,startIndexOverscan:w,stopIndexVisible:O,stopIndexOverscan:D}={startIndexVisible:Math.min(l-1,I.startIndexVisible),startIndexOverscan:Math.min(l-1,I.startIndexOverscan),stopIndexVisible:Math.min(l-1,I.stopIndexVisible),stopIndexOverscan:Math.min(l-1,I.stopIndexOverscan)},R=i.useCallback(()=>Qt({cachedBounds:y,itemCount:l,itemSize:h}),[y,l,h]),j=i.useCallback(x=>{const z=He({containerElement:e,direction:r,isRtl:o,scrollOffset:x});return Ke({cachedBounds:y,containerScrollOffset:z,containerSize:b,itemCount:l,overscanCount:u})},[y,e,b,r,o,l,u]);Le(()=>{const x=(e==null?void 0:e.scrollTop)??0;C(j(x))},[e,r,j]),Le(()=>{if(!e)return;const x=()=>{C(z=>{const{scrollLeft:A,scrollTop:_}=e,N=He({containerElement:e,direction:r,isRtl:o,scrollOffset:_}),F=Ke({cachedBounds:y,containerScrollOffset:N,containerSize:b,itemCount:l,overscanCount:u});return ze(F,z)?z:F})};return e.addEventListener("scroll",x),()=>{e.removeEventListener("scroll",x)}},[y,e,b,r,l,u]);const v=Br(({align:x="auto",containerScrollOffset:z,index:A})=>{let _=Fr({align:x,cachedBounds:y,containerScrollOffset:z,containerSize:b,index:A,itemCount:l,itemSize:h});if(e){if(_=He({containerElement:e,direction:r,isRtl:o,scrollOffset:_}),typeof e.scrollTo!="function"){const N=j(_);ze(I,N)||C(N)}return _}});return{getCellBounds:k,getEstimatedSize:R,scrollToIndex:v,startIndexOverscan:w,startIndexVisible:S,stopIndexOverscan:D,stopIndexVisible:O}}function Vr(e){return i.useMemo(()=>e,Object.values(e))}function Gr(e,t){const{ariaAttributes:n,style:r,...o}=e,{ariaAttributes:l,style:c,...d}=t;return ze(n,l)&&ze(r,c)&&ze(o,d)}function Jr(e){return e!=null&&typeof e=="object"&&"getAverageRowHeight"in e&&typeof e.getAverageRowHeight=="function"}const Yr="data-react-window-index";function qr({children:e,className:t,defaultHeight:n=0,listRef:r,onResize:o,onRowsRendered:l,overscanCount:c=3,rowComponent:d,rowCount:a,rowHeight:u,rowProps:f,tagName:m="div",style:p,...b}){const h=Vr(f),y=i.useMemo(()=>i.memo(d,Gr),[d]),[k,I]=i.useState(null),C=Jr(u),S=i.useMemo(()=>C?_=>u.getRowHeight(_)??u.getAverageRowHeight():u,[C,u]),{getCellBounds:w,getEstimatedSize:O,scrollToIndex:D,startIndexOverscan:R,startIndexVisible:j,stopIndexOverscan:v,stopIndexVisible:x}=Kr({containerElement:k,containerStyle:p,defaultContainerSize:n,direction:"vertical",itemCount:a,itemProps:h,itemSize:S,onResize:o,overscanCount:c});i.useImperativeHandle(r,()=>({get element(){return k},scrollToRow({align:_="auto",behavior:N="auto",index:F}){const H=D({align:_,containerScrollOffset:(k==null?void 0:k.scrollTop)??0,index:F});typeof(k==null?void 0:k.scrollTo)=="function"&&k.scrollTo({behavior:N,top:H})}}),[k,D]),Le(()=>{if(!k)return;const _=Array.from(k.children).filter((N,F)=>{if(N.hasAttribute("aria-hidden"))return!1;const H=`${R+F}`;return N.setAttribute(Yr,H),!0});if(C)return u.observeRowElements(_)},[k,C,u,R,v]),i.useEffect(()=>{R>=0&&v>=0&&l&&l({startIndex:j,stopIndex:x},{startIndex:R,stopIndex:v})},[l,R,j,v,x]);const z=i.useMemo(()=>{const _=[];if(a>0)for(let N=R;N<=v;N++){const F=w(N);_.push(i.createElement(y,{...h,ariaAttributes:{"aria-posinset":N+1,"aria-setsize":a,role:"listitem"},key:N,index:N,style:{position:"absolute",left:0,transform:`translateY(${F.scrollOffset}px)`,height:C?void 0:F.size,width:"100%"}}))}return _},[y,w,C,a,h,R,v]),A=s.jsx("div",{"aria-hidden":!0,style:{height:O(),width:"100%",zIndex:-1}});return i.createElement(m,{role:"list",...b,className:t,ref:I,style:{position:"relative",maxHeight:"100%",flexGrow:1,overflowY:"auto",...p}},z,e,A)}const Xr='"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',Zr=20;function Qr({index:e,style:t,lines:n}){return s.jsx("div",{style:{...t,padding:"0 12px",color:"#a9b1d6",whiteSpace:"pre",overflow:"hidden",boxSizing:"border-box"},children:n[e]})}function Et({lines:e,totalSize:t,receivedBytes:n,streaming:r}){const o=i.useRef(null),[,l]=i.useState(0),c=M(b=>b.fontSize),d=Math.round(c*1.5);i.useEffect(()=>{const b=o.current;if(!b)return;const h=new ResizeObserver(()=>l(y=>y+1));return h.observe(b),()=>h.disconnect()},[]);const a=t>0?Math.round(n/t*100):0,u=e.length.toLocaleString(),f=o.current,m=(f==null?void 0:f.clientWidth)||0,p=(f==null?void 0:f.clientHeight)||0;return s.jsxs("div",{ref:o,style:{height:"100%",width:"100%",position:"relative",fontFamily:Xr,fontSize:c,lineHeight:`${d}px`},children:[p>0&&s.jsx(qr,{rowComponent:Qr,rowCount:e.length,rowHeight:d,rowProps:{lines:e},overscanCount:Zr,style:{height:p,width:m}}),s.jsxs("div",{style:{position:"absolute",bottom:6,right:14,fontSize:10,color:"#565f89",background:"rgba(22, 22, 30, 0.85)",padding:"2px 8px",borderRadius:4,pointerEvents:"none",userSelect:"none"},children:[u," lines",r&&` (${a}%)`]})]})}const je={additions:[],deletions:[]};let eo=0;function jt(){return`ann_${++eo}_${Date.now()}`}function Ve(e,t){return`plan-annotations-${e}-${t}`}function to(e){const t=ot.parser([e],{async:!1});return $t.sanitize(t,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function Ge(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++){const o=e[r].raw??"";for(const l of o)l===`
|
|
28
|
+
`&&n++}return n}function Rt(e,t){const n=[];return e.additions.length>0&&(n.push("[增加批注]"),e.additions.forEach((r,o)=>{var c;const l=((c=t[r.sourceLine-1])==null?void 0:c.trim().slice(0,50))??"";n.push(`${o+1}. 在第${r.sourceLine}行 ("${l}") 之后添加: "${r.content}"`)})),e.deletions.length>0&&(n.length>0&&n.push(""),n.push("[删除标记]"),e.deletions.forEach((r,o)=>{const l=t.slice(r.startLine-1,r.endLine).join(" ").trim();n.push(`${o+1}. 删除第${r.startLine}-${r.endLine}行: "${l.slice(0,60)}${l.length>60?"...":""}"`)})),n.length===0?"":`请根据以下用户批注修改 PLAN.md:
|
|
29
|
+
|
|
30
|
+
`+n.join(`
|
|
31
|
+
`)}const zt=i.forwardRef(function({markdown:t,filePath:n,sessionId:r,onExecute:o,onClear:l,expanded:c},d){const a=M(L=>L.fontSize),u=i.useMemo(()=>t?ot.lexer(t):[],[t]),f=i.useMemo(()=>t.split(`
|
|
32
|
+
`),[t]),m=i.useRef(new Set),[p,b]=i.useState(()=>{try{const L=localStorage.getItem(Ve(r,n)),E=L?JSON.parse(L):je,$=new Set;return E.additions.forEach(B=>$.add(B.id)),E.deletions.forEach(B=>$.add(B.id)),m.current=$,E}catch{return je}}),h=i.useRef([]),y=30,k=i.useCallback(()=>{h.current.push(JSON.parse(JSON.stringify(p))),h.current.length>y&&h.current.shift()},[p]),I=i.useRef(void 0);i.useEffect(()=>(I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{localStorage.setItem(Ve(r,n),JSON.stringify(p))},300),()=>{I.current&&clearTimeout(I.current)}),[p,r,n]),i.useEffect(()=>{try{const L=localStorage.getItem(Ve(r,n)),E=L?JSON.parse(L):je;b(E);const $=new Set;E.additions.forEach(B=>$.add(B.id)),E.deletions.forEach(B=>$.add(B.id)),m.current=$,h.current=[]}catch{b(je),m.current=new Set}},[r,n]);const[C,S]=i.useState(null),[w,O]=i.useState(""),D=i.useRef(null),[R,j]=i.useState(null),[v,x]=i.useState(""),z=i.useRef(null),[A,_]=i.useState(null),N=i.useRef(null);i.useEffect(()=>{C!=null&&requestAnimationFrame(()=>{var L;return(L=D.current)==null?void 0:L.focus()})},[C]);const F=i.useCallback(L=>{if(!w.trim()){S(null),O("");return}k();const E=Ge(u,L+1);b($=>({...$,additions:[...$.additions,{id:jt(),afterTokenIndex:L,sourceLine:E,content:w.trim()}]})),S(null),O("")},[w,k,u]),H=i.useCallback(L=>{k(),b(E=>({...E,additions:E.additions.filter($=>$.id!==L)}))},[k]),G=i.useCallback((L,E)=>{k(),b($=>({...$,additions:$.additions.map(B=>B.id===L?{...B,content:E}:B)}))},[k]),J=i.useCallback(()=>{var L;A&&(k(),b(E=>({...E,deletions:[...E.deletions,{id:jt(),tokenIndices:A.tokenIndices,startLine:A.startLine,endLine:A.endLine,selectedText:A.text.slice(0,80)}]})),_(null),(L=window.getSelection())==null||L.removeAllRanges())},[A,k]),V=i.useCallback(L=>{k(),b(E=>({...E,deletions:E.deletions.filter($=>$.id!==L)}))},[k]),Y=i.useCallback((L,E)=>{k(),b($=>({...$,deletions:$.deletions.map(B=>B.id===L?{...B,selectedText:E}:B)}))},[k]),me=i.useCallback(L=>{let E=L instanceof Element?L:L.parentElement;for(;E&&E!==N.current;){if(E.hasAttribute("data-token-index"))return E;E=E.parentElement}return null},[]),he=i.useCallback(()=>{const L=window.getSelection();if(!L||L.isCollapsed||!N.current){_(null);return}const E=L.toString().trim();if(!E){_(null);return}const $=L.getRangeAt(0);if(!N.current.contains($.commonAncestorContainer)){_(null);return}const B=me($.startContainer),W=me($.endContainer);if(!B||!W){_(null);return}const ne=parseInt(B.getAttribute("data-token-index")||"0",10),P=parseInt(W.getAttribute("data-token-index")||"0",10),K=[];for(let U=Math.min(ne,P);U<=Math.max(ne,P);U++)K.push(U);const X=Ge(u,Math.min(ne,P)),Z=Ge(u,Math.max(ne,P)+1),ge=$.getBoundingClientRect(),g=N.current,T=g.getBoundingClientRect();navigator.clipboard.writeText(E).catch(()=>{}),_({x:ge.right-T.left+g.scrollLeft+6,y:ge.top-T.top+g.scrollTop-2,tokenIndices:K,startLine:X,endLine:Z,text:E})},[u,me]),ee=i.useRef(void 0);i.useEffect(()=>{const L=()=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{const E=window.getSelection();if(!E||E.isCollapsed||!N.current){_(null);return}const $=E.anchorNode;$&&N.current.contains($)&&he()},120)};return document.addEventListener("selectionchange",L),()=>{document.removeEventListener("selectionchange",L),ee.current&&clearTimeout(ee.current)}},[he]),Xt(N,u),i.useEffect(()=>{const L=E=>{var $;if((E.ctrlKey||E.metaKey)&&E.key==="z"&&!E.shiftKey){if((($=document.activeElement)==null?void 0:$.tagName)==="TEXTAREA")return;const B=h.current.pop();B&&(E.preventDefault(),b(B))}};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[]);const de=i.useCallback(()=>({additions:p.additions.filter(L=>!m.current.has(L.id)),deletions:p.deletions.filter(L=>!m.current.has(L.id))}),[p]),xe=i.useCallback(()=>{const L=Rt(de(),f);if(L){o(L);const E=new Set;p.additions.forEach($=>E.add($.id)),p.deletions.forEach($=>E.add($.id)),m.current=E}},[de,p,f,o]);i.useImperativeHandle(d,()=>({getSummary:()=>Rt(de(),f)}),[de,f]);const ue=i.useCallback(()=>{k(),b(je),l==null||l()},[k,l]),be=i.useMemo(()=>{const L=new Set;return p.deletions.forEach(E=>E.tokenIndices.forEach($=>L.add($))),L},[p.deletions]),ae=i.useMemo(()=>{const L=new Map;return p.additions.forEach(E=>{const $=L.get(E.afterTokenIndex)||[];$.push(E),L.set(E.afterTokenIndex,$)}),L},[p.additions]),fe=p.additions.length>0||p.deletions.length>0;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("button",{className:"pane-btn",onClick:xe,disabled:!fe,title:"Save annotations to editor",style:fe?{color:"#9ece6a"}:{opacity:.4},children:"Save"}),s.jsx("button",{className:"pane-btn",onClick:ue,disabled:!fe,title:"Clear all annotations",style:fe?{}:{opacity:.4},children:"Clear"}),fe&&s.jsxs("span",{style:{fontSize:10,color:"#565f89",marginLeft:4},children:["+",p.additions.length," −",p.deletions.length]})]}),s.jsxs("div",{ref:N,className:"plan-anno-content md-preview",style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${a}px`},onMouseUp:he,children:[s.jsx(Lt,{index:-1,active:C===-1,additions:ae.get(-1),onOpen:()=>{S(-1),O("")},onSubmit:()=>F(-1),onRemoveAddition:H,onEditAddition:G,insertText:w,setInsertText:O,textareaRef:C===-1?D:void 0,expanded:c,alwaysShow:u.length===0,fontSize:a}),u.map((L,E)=>{const $=to(L);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":E,className:be.has(E)?"plan-block--deleted":void 0,dangerouslySetInnerHTML:{__html:$}}),p.deletions.filter(B=>B.tokenIndices.includes(E)&&B.tokenIndices[0]===E).map(B=>s.jsx("div",{className:"plan-deletion-card",children:R===B.id?s.jsx("textarea",{ref:z,className:"plan-annotation-textarea",value:v,onChange:W=>x(W.target.value),onKeyDown:W=>{if(W.key==="Enter"&&(W.ctrlKey||W.metaKey)){W.preventDefault();const ne=v.trim();ne?Y(B.id,ne):V(B.id),j(null)}W.key==="Escape"&&(W.preventDefault(),j(null))},onBlur:()=>{const W=v.trim();W?Y(B.id,W):V(B.id),j(null)},rows:tt(v),style:{fontSize:`${a}px`,flex:1}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${a}px`,color:"#f7768e",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{j(B.id),x(B.selectedText),requestAnimationFrame(()=>{const W=z.current;W&&(W.focus(),W.selectionStart=W.selectionEnd=W.value.length)})},title:"Double-click to edit",children:B.selectedText}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{j(B.id),x(B.selectedText),requestAnimationFrame(()=>{const W=z.current;W&&(W.focus(),W.selectionStart=W.selectionEnd=W.value.length)})},style:{color:"#7aa2f7"},title:"Edit deletion annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>V(B.id),title:"Remove deletion",children:"×"})]})},B.id)),s.jsx(Lt,{index:E,active:C===E,additions:ae.get(E),onOpen:()=>{S(E),O("")},onSubmit:()=>F(E),onRemoveAddition:H,onEditAddition:G,insertText:w,setInsertText:O,textareaRef:C===E?D:void 0,expanded:c,fontSize:a})]},E)}),A&&s.jsx("button",{className:"plan-delete-float",style:{top:A.y,left:A.x},onMouseDown:L=>{L.preventDefault(),J()},children:"−"})]})]})});function Lt({index:e,active:t,additions:n,onOpen:r,onSubmit:o,onRemoveAddition:l,onEditAddition:c,insertText:d,setInsertText:a,textareaRef:u,expanded:f,alwaysShow:m,fontSize:p=14}){const[b,h]=i.useState(null),[y,k]=i.useState(""),I=i.useRef(null),C=Ze(),S=Ze();i.useEffect(()=>{b&&(C.clearUndo(),requestAnimationFrame(()=>{const v=I.current;v&&(v.focus(),v.selectionStart=v.selectionEnd=v.value.length)}))},[b]),i.useEffect(()=>{t&&S.clearUndo()},[t]);const w=i.useCallback(v=>{k(x=>(C.pushUndo(x),v))},[C]),O=i.useCallback(v=>{S.pushUndo(d),a(v)},[d,a,S]),D=i.useCallback(v=>{h(v.id),k(v.content)},[]),R=i.useCallback(()=>{if(!b)return;const v=y.trim();v?c(b,v):l(b),h(null),k("")},[b,y,c,l]),j=i.useCallback(()=>{h(null),k("")},[]);return s.jsxs("div",{className:`plan-insert-zone${m?" plan-insert-zone--empty":""}`,"data-zone-index":e,children:[n==null?void 0:n.map(v=>s.jsx("div",{className:"plan-annotation-card",children:b===v.id?s.jsx("textarea",{ref:I,className:"plan-annotation-textarea",value:y,onChange:x=>w(x.target.value),onKeyDown:x=>{if(x.key==="Enter"&&(x.ctrlKey||x.metaKey)){x.preventDefault(),R();return}if(x.key==="Escape"){x.preventDefault(),j();return}if(x.key==="Tab"){Qe(x,w);return}if(x.key==="z"&&(x.ctrlKey||x.metaKey)&&!x.shiftKey){et(x,C.popUndo,k);return}},onBlur:R,rows:tt(y),style:{fontSize:`${p}px`,flex:1,...f?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${p}px`,color:"#e0af68",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>D(v),title:"Double-click to edit",children:v.content}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>D(v),style:{color:"#7aa2f7"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(v.id),children:"×"})]})},v.id)),t?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:d,onChange:v=>O(v.target.value),onKeyDown:v=>{if(v.key==="Enter"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),o();return}if(v.key==="Escape"){v.preventDefault(),o();return}if(v.key==="Tab"){Qe(v,O);return}if(v.key==="z"&&(v.ctrlKey||v.metaKey)&&!v.shiftKey){et(v,S.popUndo,a);return}},placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:tt(d),style:{fontSize:`${p}px`,...f?{minWidth:300}:void 0}})}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}const Je={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},no=200;function ro(){const[e,t]=i.useState(Je),n=i.useRef("lines"),r=i.useRef([]),o=i.useRef(""),l=i.useRef(""),c=i.useRef([]),d=i.useRef(0),a=i.useRef(0),u=i.useRef(null),f=i.useRef(null),m=i.useCallback(()=>{const I=n.current;t(C=>({...C,receivedBytes:d.current,...I==="lines"?{lines:[...r.current]}:{},...I==="content"?{content:l.current}:{}}))},[]),p=i.useCallback(()=>{u.current===null&&(u.current=window.setTimeout(()=>{u.current=null,m()},no))},[m]),b=i.useCallback(I=>{n.current=I,r.current=[],o.current="",l.current="",c.current=[],d.current=0,a.current=0,f.current=new TextDecoder,u.current!==null&&(clearTimeout(u.current),u.current=null),t({...Je,mode:I,status:"streaming"})},[]),h=i.useCallback(I=>{d.current+=I.length;const C=n.current;if(C==="lines"){const w=f.current.decode(I,{stream:!0}).split(`
|
|
33
|
+
`);w[0]=o.current+w[0],o.current=w.pop(),w.length>0&&r.current.push(...w)}else if(C==="content"){const S=f.current.decode(I,{stream:!0});l.current+=S}else c.current.push(new Uint8Array(I));p()},[p]),y=i.useCallback(I=>{switch(I.type){case"file-stream-start":a.current=I.size,t(C=>({...C,totalSize:I.size,mtime:I.mtime}));break;case"file-stream-end":{u.current!==null&&(clearTimeout(u.current),u.current=null);const C=n.current;let S=r.current,w=l.current,O=null;if(C==="lines"){const D=f.current.decode(),R=o.current+D;R&&(S=[...S,R],r.current=S),o.current=""}else if(C==="content"){const D=f.current.decode();w=l.current+D,l.current=w}else{const D=c.current.reduce((j,v)=>j+v.length,0);O=new Uint8Array(D);let R=0;for(const j of c.current)O.set(j,R),R+=j.length;c.current=[]}t({status:"complete",mode:C,lines:C==="lines"?[...S]:[],content:C==="content"?w:"",buffer:C==="binary"?O:null,totalSize:a.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":u.current!==null&&(clearTimeout(u.current),u.current=null),t(C=>({...C,status:"error",error:I.error}));break}},[]),k=i.useCallback(()=>{u.current!==null&&(clearTimeout(u.current),u.current=null),r.current=[],o.current="",l.current="",c.current=[],d.current=0,a.current=0,f.current=null,t(Je)},[]);return{state:e,startStream:b,handleChunk:h,handleControl:y,reset:k}}function oo(e=50,t=20,n=80){const[r,o]=i.useState(e),l=i.useRef(null),c=i.useCallback(d=>{d.preventDefault();const a=l.current;if(!a)return;const u=a.getBoundingClientRect(),f=u.width;document.body.classList.add("resizing-panes-h");let m=null;const p=h=>{m||(m=requestAnimationFrame(()=>{m=null;const y=h.clientX-u.left,k=Math.min(n,Math.max(t,y/f*100));o(k)}))},b=()=>{m&&cancelAnimationFrame(m),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",p),document.addEventListener("mouseup",b)},[t,n]);return{leftWidthPercent:r,containerRef:l,onDividerMouseDown:c}}const en={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon"};function so(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":t in en?"image":"text"}function io(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return en[t]||"image/png"}function Ye(e){return e.split("/").pop()||e}const ao=3e3;function qe({label:e,percent:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"#565f89",fontSize:13},children:e}),t!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"#292e42",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${t}%`,backgroundColor:"#7aa2f7",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"#565f89",whiteSpace:"nowrap"},children:[t,"%"]})]})]})}function Nt({sessionId:e,onSelect:t}){const n=i.useCallback(()=>{},[]),{cwd:r,files:o,loading:l,error:c,handleNavigate:d,handleGoUp:a,handleRefresh:u}=st({sessionId:e,onClose:n,pollCwd:ao});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(at,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(lt,{loading:l,error:c,empty:o.length===0,emptyText:"No files found"}),!l&&!c&&o.map(f=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent"},onClick:()=>{f.type==="directory"?d(f.name):t(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Yt(f.name,f.type)}),s.jsx("span",{style:{flex:1,color:f.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:f.name}),f.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:it(f.size)})]},f.name))]})]})}function lo({sessionId:e,token:t,connected:n,onClose:r,onSend:o,onRequestFileStream:l,planMode:c,onPlanModeClose:d}){const[a,u]=i.useState(null),[f,m]=i.useState(null),p=ro(),[b,h]=i.useState(!1),[y,k]=i.useState(!1),[I,C]=i.useState(!1),{leftWidthPercent:S,containerRef:w,onDividerMouseDown:O}=oo(50),D=i.useRef(null),R=i.useRef(null),[j,v]=i.useState(!1),x=i.useRef("doc"),[z,A]=i.useState(null),[_,N]=i.useState(""),[F,H]=i.useState(!1),[G,J]=i.useState(!1);i.useEffect(()=>{if(!c){V.current=null;return}let P=!1;return H(!0),(async()=>{try{const K=await Te(t,e);if(P)return;if(K.files.find(Z=>Z.name==="PLAN.md")){const Z=K.cwd+"/PLAN.md";A(Z),N("")}else{try{const Z=await wr(t,e,"PLAN.md");if(P)return;if(Z.ok&&Z.path){A(Z.path),N(""),H(!1);return}}catch{}A(null),N("")}}catch{A(null)}finally{P||H(!1)}})(),()=>{P=!0}},[c,e,t]);const V=i.useRef(null);i.useEffect(()=>{!c||!z||!n||V.current===z&&_||(V.current=z,x.current="plan",p.reset(),p.startStream("content"),l==null||l(z))},[c,z,n]),i.useEffect(()=>{c&&p.state.status==="complete"&&z&&x.current==="plan"&&N(p.state.content)},[c,p.state.status,p.state.content,z]);const Y=i.useRef(null),me=i.useCallback(P=>{Y.current=P,d==null||d()},[d]);i.useEffect(()=>{!c&&Y.current&&D.current&&(D.current.fillContent(Y.current),Y.current=null)},[c]);const he=i.useCallback(()=>{!z||!n||(V.current=null,x.current="plan",N(""),p.reset(),p.startStream("content"),l==null||l(z),V.current=z)},[z,n,p,l]),ee=i.useRef(new Map),de=i.useRef(null),xe=i.useRef(null);i.useEffect(()=>(er(e,p.handleChunk,p.handleControl),()=>tr(e)),[e,p.handleChunk,p.handleControl]);const ue=i.useCallback(()=>{if(!a)return;const P=y?xe.current:de.current;P&&ee.current.set(a,P.scrollTop)},[a,y]),be=i.useCallback(P=>{const K=ee.current.get(P);K!=null&&requestAnimationFrame(()=>{const X=y?xe.current:de.current;X&&(X.scrollTop=K)})},[y]),ae=i.useCallback((P,K)=>{ue();const X=so(P);u(P),m(X),h(!1),x.current="doc",p.reset();const Z=X==="text"?"lines":X==="pdf"||X==="image"?"binary":"content";p.startStream(Z),l==null||l(P)},[ue,p,l]),fe=i.useCallback(()=>{if(!a||!f)return;x.current="doc",p.reset();const P=f==="text"?"lines":f==="pdf"||f==="image"?"binary":"content";p.startStream(P),l==null||l(a)},[a,f,p,l]),L=i.useCallback(()=>{a&&navigator.clipboard.writeText(a).then(()=>{C(!0),setTimeout(()=>C(!1),1500)}).catch(()=>{})},[a]);i.useEffect(()=>{if(!y&&!G)return;const P=K=>{if(K.key==="Escape"){if(G){J(!1);return}ue(),k(!1)}};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[y,G,ue]),i.useEffect(()=>{a&&p.state.status==="complete"&&be(a)},[y,a,be,p.state.status]);const{totalSize:E,receivedBytes:$}=p.state,B=E>0?Math.round($/E*100):0,W=i.useCallback(()=>{const P=window.getSelection(),K=P==null?void 0:P.toString();K&&navigator.clipboard.writeText(K).catch(()=>{})},[]),ne=P=>{if(!a)return s.jsx(Nt,{sessionId:e,onSelect:ae});const{status:K,lines:X,content:Z,buffer:ge}=p.state;if(K==="error")return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#f7768e",fontSize:"13px",padding:"12px",textAlign:"center"},children:p.state.error||"Stream error"});if(K==="streaming")return f==="text"?s.jsx(Et,{lines:X,totalSize:E,receivedBytes:$,streaming:!0}):s.jsx(qe,{label:"Loading...",percent:B});if(K==="complete"){if(f==="text")return s.jsx(Et,{lines:X,totalSize:E,receivedBytes:$,streaming:!1});if(f==="md")return s.jsx("div",{ref:P,style:{height:"100%",overflow:"auto"},children:s.jsx(jr,{content:Z})});if(f==="html")return s.jsx("div",{ref:P,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:Z,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})});if(f==="pdf"&&ge)return s.jsx(Pr,{data:ge,scrollRef:P});if(f==="image"&&ge){const g=new Blob([ge.buffer],{type:io(a)}),T=URL.createObjectURL(g);return s.jsx("div",{ref:P,style:{height:"100%",overflow:"auto",display:"flex",alignItems:"center",justifyContent:"center",padding:12},children:s.jsx("img",{src:T,alt:Ye(a),onLoad:()=>URL.revokeObjectURL(T),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",borderRadius:4}})})}}return K==="idle"?s.jsx(Nt,{sessionId:e,onSelect:ae}):null};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",height:"30px",flexShrink:0,backgroundColor:"#16161e",borderBottom:"1px solid #292e42"},children:[s.jsxs("div",{style:{width:`${S}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>h(P=>!P),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),a&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:L,title:I?"Copied!":`Click to copy: ${a}`,children:I?"Copied!":Ye(a)}),s.jsx("button",{className:"pane-btn",onClick:()=>{ue(),k(!0)},title:"Expand document view",children:"⛶"}),s.jsx("button",{className:"pane-btn",onClick:fe,title:"Refresh document",children:"↻"})]})]}),s.jsx("div",{style:{width:"4px",flexShrink:0}}),s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",minWidth:0},children:c?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"#bb9af7",fontWeight:600},children:"Plan"}),z&&s.jsx("span",{style:{fontSize:"10px",color:"#565f89"},children:z.split("/").pop()})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("button",{className:"pane-btn",onClick:he,title:"Refresh PLAN.md",children:"↻"}),s.jsx("button",{className:"pane-btn",onClick:()=>J(!0),title:"Expand plan view",children:"⛶"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{var K;const P=(K=R.current)==null?void 0:K.getSummary();P&&(Y.current=P),d==null||d()},title:"Close Plan mode",children:"×Plan"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>{var P;return(P=D.current)==null?void 0:P.send()},disabled:!j,title:"Send to terminal (Ctrl+Enter)",style:j?{color:"#9ece6a"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"10px",color:"#414868"},children:"Ctrl+Enter"})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:r,title:"Close Doc panel",children:"×"})]})})]}),s.jsxs("div",{ref:w,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${S}%`,flexShrink:0},onMouseUp:W,children:[ne(P=>{de.current=P}),b&&s.jsx(Mr,{sessionId:e,onSelect:ae,onClose:()=>h(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:O}),s.jsx("div",{className:"plan-editor-wrap",children:c?F?s.jsx(qe,{label:"Loading PLAN.md..."}):z&&!_&&(p.state.status==="streaming"||p.state.status==="idle")?s.jsx(qe,{label:"Loading PLAN.md...",percent:p.state.totalSize>0?Math.round(p.state.receivedBytes/p.state.totalSize*100):void 0}):z&&!G?s.jsx(zt,{ref:R,markdown:_,filePath:z,sessionId:e,onExecute:me}):z&&G?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:12},children:"Editing in expanded view"}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"#565f89",fontSize:13,fontStyle:"italic"},children:"No PLAN.md found in CWD"}),s.jsx("button",{className:"pane-btn",onClick:()=>h(!0),style:{color:"#7aa2f7"},children:"Select file"})]}):s.jsx(Nr,{ref:D,onSend:o,onContentChange:v,sessionId:e,token:t})})]}),y&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsx("span",{style:{fontSize:"14px",color:"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a?Ye(a):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{ue(),k(!1)},title:"Close expanded view (ESC)",style:{fontSize:"14px"},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},onMouseUp:W,children:ne(P=>{xe.current=P})})]}),G&&z&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsxs("span",{style:{fontSize:"14px",color:"#bb9af7"},children:["Plan: ",z.split("/").pop()]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>J(!1),title:"Close expanded view (ESC)",style:{fontSize:"14px"},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(zt,{ref:R,markdown:_,filePath:z,sessionId:e,onExecute:me,expanded:!0})})]})]})}const co=100,uo=600,Ce=typeof window<"u"?window.matchMedia(`(max-width: ${uo-1}px)`):null;function fo(){const[e,t]=i.useState(()=>(Ce==null?void 0:Ce.matches)??!1);return i.useEffect(()=>{if(!Ce)return;const n=r=>t(r.matches);return Ce.addEventListener("change",n),()=>Ce.removeEventListener("change",n)},[]),e}const po=i.memo(function({terminal:t}){const n=fo(),r=M(R=>R.splitTerminal),o=M(R=>R.token),l=M(R=>R.setTerminalPanelMode),c=i.useRef(null),d=i.useRef(null),[a,u]=i.useState(!1),[f,m]=i.useState(!1),[p,b]=i.useState(0),[h,y]=i.useState(50),k=t.panelMode!=="none",I=t.panelMode==="plan",C=i.useRef(null),S=async R=>{const j=R.target.files;if(!(!j||j.length===0||!o)){m(!0),b(0);try{await yr(o,t.id,j,v=>{b(v)})}catch(v){alert(`Upload failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{m(!1),b(0),c.current&&(c.current.value="")}}},w=i.useRef(void 0),O=i.useCallback(R=>{if(d.current){const j=R.replace(/\r?\n/g," ").trimEnd();d.current.sendInput(j),w.current=window.setTimeout(()=>{var v;return(v=d.current)==null?void 0:v.sendInput("\r")},50)}},[]);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const D=i.useCallback(R=>{R.preventDefault();const j=C.current;if(!j)return;const v=j.getBoundingClientRect(),x=v.height;document.body.classList.add("resizing-panes-v");const z=_=>{const N=(_.clientY-v.top)/x*100,F=Math.min(80,Math.max(20,N));y(100-F)},A=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",A)};document.addEventListener("mousemove",z),document.addEventListener("mouseup",A)},[]);return s.jsxs("div",{ref:C,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:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0,height:"28px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{display:"inline-block",width:"7px",height:"7px",borderRadius:"50%",backgroundColor:t.connected?"#9ece6a":"#f7768e",boxShadow:t.connected?"0 0 4px rgba(158,206,106,0.5)":"0 0 4px rgba(247,118,142,0.5)"}}),s.jsxs("span",{style:{fontSize:"14px",color:"#565f89"},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:c,type:"file",multiple:!0,style:{display:"none"},onChange:S}),s.jsx("button",{className:"pane-btn",onClick:()=>{var R;return(R=c.current)==null?void 0:R.click()},disabled:f,style:f?{color:"#e0af68"}:void 0,title:f?`Uploading ${p}%`:"Upload files","aria-label":"Upload files",children:f?`${p}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>u(R=>!R),style:a?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${t.panelMode==="chat"?" pane-btn--active":""}`,onClick:()=>l(t.id,t.panelMode==="chat"?"none":"chat"),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${t.panelMode==="plan"?" pane-btn--active":""}`,onClick:()=>l(t.id,t.panelMode==="plan"?"none":"plan"),title:"Toggle Plan annotation mode","aria-label":"Toggle Plan annotation mode",children:"Plan"}),s.jsx("button",{className:"pane-btn",onClick:()=>r(t.id,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:()=>r(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(gr,{ref:d,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(26, 27, 38, 0.85)",zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"#565f89",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})}),a&&s.jsx(kr,{sessionId:t.id,onClose:()=>u(!1)})]}),k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:D}),s.jsx("div",{style:{height:`${h}%`,minHeight:co,flexShrink:0,overflow:"hidden"},children:s.jsx(lo,{onSend:O,onClose:()=>l(t.id,"none"),sessionId:t.id,token:o||"",connected:t.connected,onRequestFileStream:R=>{var j;return(j=d.current)==null?void 0:j.requestFileStream(R)},onCancelFileStream:()=>{var R;return(R=d.current)==null?void 0:R.cancelFileStream()},planMode:I,onPlanModeClose:()=>l(t.id,"chat")})})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:t.error})]})});class tn extends i.Component{constructor(){super(...arguments);dt(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:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"#c0caf5",fontFamily:"monospace",padding:"16px"},children:[s.jsx("div",{style:{fontSize:"14px",color:"#f7768e"},children:"Pane crashed"}),s.jsx("div",{style:{fontSize:"12px",color:"#565f89",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:"#292e42",border:"1px solid #414868",color:"#c0caf5",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):s.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"#c0caf5",fontFamily:"monospace"},children:[s.jsx("div",{style:{fontSize:"18px",color:"#f7768e"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"#565f89",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, #7aa2f7 0%, #bb9af7 100%)",border:"none",color:"#1a1b26",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const mo=4,Mt=10;function ho(){const e=M(o=>o.layout),t=M(o=>o.terminalIds.length),n=M(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#1a1b26"},children:s.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed #292e42",color:"#565f89",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(nn,{node:e,canClose:r})})}const nn=i.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(xo,{terminalId:t.terminalId,canClose:n}):s.jsx(go,{node:t,canClose:n})}),xo=i.memo(function({terminalId:t,canClose:n}){const r=M(o=>o.terminalsMap[t]);return r?s.jsx(tn,{inline:!0,children:s.jsx(po,{terminal:r,canClose:n})}):null}),go=i.memo(function({node:t,canClose:n}){const r=M(u=>u.setSplitSizes),o=i.useRef(null),l=t.direction==="horizontal",c=i.useRef(t.sizes);c.current=t.sizes;const d=i.useCallback((u,f)=>{f.preventDefault();const m=l?"resizing-panes":"resizing-panes-v";document.body.classList.add(m);const p=l?f.clientX:f.clientY,b=[...c.current],h=o.current,y=l?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let k=null;const I=S=>{k||(k=requestAnimationFrame(()=>{k=null;const D=((l?S.clientX:S.clientY)-p)/y*100,R=b[u]+D,j=b[u+1]-D;if(R>=Mt&&j>=Mt){const v=[...b];v[u]=R,v[u+1]=j,r(t.id,v)}}))},C=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(m),document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",C)};document.addEventListener("mousemove",I),document.addEventListener("mouseup",C)},[l,t.id,r]),a=[];return t.children.forEach((u,f)=>{const m=u.type==="leaf"?u.terminalId:u.id;a.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(nn,{node:u,canClose:n})},m)),f<t.children.length-1&&a.push(s.jsx("div",{onMouseDown:p=>d(f,p),style:{flex:`0 0 ${mo}px`,cursor:l?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:l?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:a})});function bo({tabId:e}){const t=M(x=>x.tabs.find(z=>z.id===e)),n=M(x=>x.activeTabId),r=M(x=>x.switchTab),o=M(x=>x.closeTab),l=M(x=>x.reopenTab),c=M(x=>x.deleteTab),d=M(x=>x.renameTab),a=M(x=>t?t.terminalIds.map(z=>{const A=x.terminalsMap[z];return A?{id:z,connected:A.connected}:{id:z,connected:!1}}):[]),u=M(x=>x.killServerSession),[f,m]=i.useState(!1),[p,b]=i.useState(""),[h,y]=i.useState(!1),k=i.useRef(null);if(!t)return null;const I=n===e,C=t.status==="open",S=()=>{C&&r(e)},w=x=>{C&&(x.stopPropagation(),b(t.name),m(!0),setTimeout(()=>{var z;return(z=k.current)==null?void 0:z.focus()},0))},O=()=>{const x=p.trim();x&&d(e,x),m(!1)},D=x=>{x.stopPropagation(),l(e)},R=x=>{x.stopPropagation(),o(e)},j=async x=>{x.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},v=x=>{x.stopPropagation(),y(!h)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:S,style:{padding:"8px 12px",cursor:C?"pointer":"default",borderLeft:I?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:I?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s",opacity:C?1:.5},onMouseEnter:x=>{C&&!I&&(x.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:x=>{I||(x.currentTarget.style.backgroundColor="transparent")},children:[C&&t.terminalIds.length>0&&s.jsx("button",{onClick:v,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:h?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[f?s.jsx("input",{ref:k,value:p,onChange:x=>b(x.target.value),onBlur:O,onKeyDown:x=>{x.key==="Enter"&&O(),x.key==="Escape"&&m(!1)},style:{width:"100%",background:"#1a1b26",border:"1px solid #7aa2f7",color:"#c0caf5",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):s.jsx("div",{onDoubleClick:w,style:{color:"#c0caf5",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",qt(Math.floor(t.createdAt/1e3))]})]}),C?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:R,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:D,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:j,title:"Delete tab",children:"×"})]})]}),C&&h&&a.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:a.map(x=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)",display:"flex",alignItems:"center"},title:`Connected: ${x.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:x.id}),s.jsx("span",{style:{marginLeft:"8px",color:x.connected?"#9ece6a":"#f7768e"},children:x.connected?"●":"○"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:z=>{z.stopPropagation(),window.confirm(`Close terminal "${x.id}"?`)&&u(x.id)},style:{marginLeft:"auto",flexShrink:0},title:"Close terminal",children:"×"})]},x.id))})]})}function yo({sessionId:e,active:t,createdAt:n}){const r=M(d=>d.addTerminal),o=M(d=>d.killServerSession),l=()=>{r("horizontal",e)},c=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};return s.jsxs("div",{onClick:l,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:qt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function vo(){const e=M(a=>a.sidebarOpen),t=M(a=>a.toggleSidebar),n=M(a=>a.fetchSessions),r=M(a=>e?a.serverSessions:[]),o=M(a=>e?a.tabs:[]),l=M(a=>a.terminalIds.length),c=new Set(o.flatMap(a=>a.terminalIds)),d=r.filter(a=>!c.has(a.sessionId));return i.useEffect(()=>{if(!e)return;n();let a=setInterval(n,5e3);const u=()=>{document.hidden?a&&(clearInterval(a),a=null):(n(),a||(a=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",u),()=>{a&&clearInterval(a),document.removeEventListener("visibilitychange",u)}},[e,n]),i.useEffect(()=>{if(!e)return;const a=setTimeout(n,800);return()=>clearTimeout(a)},[l,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:e?"1px solid #292e42":"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 #292e42",flexShrink:0},children:[s.jsx("span",{style:{color:"#7aa2f7",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Sessions"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#565f89",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:"#7aa2f7",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid #292e42"},children:"TABS"}),o.length===0?s.jsx("div",{style:{color:"#565f89",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(a=>s.jsx(bo,{tabId:a.id},a.id))]}),d.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.jsx("div",{style:{padding:"8px 12px",color:"#e0af68",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid #292e42"},children:"ORPHANED SESSIONS"}),d.map(a=>s.jsx(yo,{sessionId:a.sessionId,active:a.active,createdAt:a.createdAt},a.sessionId))]})]})]})}const rn=rt.memo(()=>{const e=M(w=>w.tabs),t=M(w=>w.activeTabId),n=M(w=>w.addTab),r=M(w=>w.switchTab),o=M(w=>w.closeTab),l=M(w=>w.renameTab),[c,d]=i.useState(null),[a,u]=i.useState(""),f=i.useRef(null),m=e.filter(w=>w.status==="open");i.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const p=w=>{d(w.id),u(w.name)},b=()=>{c&&a.trim()&&l(c,a.trim()),d(null),u("")},h=()=>{d(null),u("")},y=w=>{w.key==="Enter"?b():w.key==="Escape"&&h()},k=w=>{c||r(w)},I=(w,O)=>{w.stopPropagation(),o(O)},C=(w,O)=>{w.button===1&&(w.preventDefault(),o(O))},S=m.length>1;return s.jsxs("div",{className:"tab-bar",children:[m.map(w=>{const O=w.id===t,D=c===w.id,R=w.terminalIds.length;return s.jsx("div",{className:`tab-item ${O?"tab-item--active":""}`,onClick:()=>k(w.id),onDoubleClick:()=>p(w),onMouseDown:j=>C(j,w.id),children:D?s.jsx("input",{ref:f,type:"text",value:a,onChange:j=>u(j.target.value),onBlur:b,onKeyDown:y,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[w.name," ",R>0&&`(${R})`]}),S&&s.jsx("button",{className:"tab-item__close",onClick:j=>I(j,w.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},w.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});rn.displayName="TabBar";function wo(){return localStorage.getItem("ai-cli-online-token")}function So(){const e=M(a=>a.token),t=M(a=>a.setToken),n=M(a=>a.tabs),r=M(a=>a.addTab),o=M(a=>a.toggleSidebar),l=M(a=>a.fontSize),c=M(a=>a.setFontSize),d=M(a=>a.tabsLoading);return i.useEffect(()=>{const a=wo();a&&!e&&t(a)},[]),i.useEffect(()=>{e&&!d&&n.filter(a=>a.status==="open").length===0&&r("Default")},[e,d]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"#1a1b26"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"#7aa2f7",letterSpacing:"0.5px"},children:"AI-Cli Online"})}),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:()=>c(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:"#a9b1d6",minWidth:"20px",textAlign:"center"},children:l}),s.jsx("button",{className:"header-btn",onClick:()=>c(l+1),disabled:l>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(Co,{}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Sessions Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(ho,{})}),s.jsx(vo,{})]}),s.jsx(rn,{})]}):s.jsx(Qn,{})}const ko=[1,2,3,4];function Co(){const e=M(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="#9ece6a",n=4):e<150?(t="#e0af68",n=3):e<300?(t="#ff9e64",n=2):(t="#f7768e",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[ko.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}Xe.createRoot(document.getElementById("root")).render(s.jsx(rt.StrictMode,{children:s.jsx(tn,{children:s.jsx(So,{})})}));
|
package/web/dist/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<!-- Fonts loaded locally from /fonts/ -->
|
|
8
8
|
<title>AI-Cli Online</title>
|
|
9
9
|
<link rel="preload" href="/fonts/JetBrainsMono-Regular.woff2" as="font" type="font/woff2" crossorigin />
|
|
10
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-zFa9lx6P.js"></script>
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/react-vendor-BCIvbQoU.js">
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/terminal-DnNpv9tw.js">
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/markdown-BERZKN_L.js">
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
var on=Object.defineProperty;var sn=(e,t,n)=>t in e?on(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ct=(e,t,n)=>sn(e,typeof t!="symbol"?t+"":t,n);import{r as i,a as an,g as ln,R as nt}from"./react-vendor-BCIvbQoU.js";import{D as Dt,o as Ot,L as cn,x as At}from"./terminal-DnNpv9tw.js";import{d as rt,p as $t}from"./markdown-BERZKN_L.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();var Pt={exports:{}},$e={};/**
|
|
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 dn=i,un=Symbol.for("react.element"),fn=Symbol.for("react.fragment"),pn=Object.prototype.hasOwnProperty,mn=dn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,hn={key:!0,ref:!0,__self:!0,__source:!0};function _t(e,t,n){var r,o={},l=null,c=null;n!==void 0&&(l=""+n),t.key!==void 0&&(l=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)pn.call(t,r)&&!hn.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:un,type:e,key:l,ref:c,props:o,_owner:mn.current}}$e.Fragment=fn;$e.jsx=_t;$e.jsxs=_t;Pt.exports=$e;var s=Pt.exports,qe={},dt=an;qe.createRoot=dt.createRoot,qe.hydrateRoot=dt.hydrateRoot;const xn={},ut=e=>{let t;const n=new Set,r=(f,m)=>{const p=typeof f=="function"?f(t):f;if(!Object.is(p,t)){const y=t;t=m??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(h=>h(t,y))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>u,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},u=t=e(r,o,a);return a},yn=e=>e?ut(e):ut;var Bt={exports:{}},Ft={},Ut={exports:{}},Wt={};/**
|
|
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 Ie=i;function bn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var gn=typeof Object.is=="function"?Object.is:bn,vn=Ie.useState,wn=Ie.useEffect,Sn=Ie.useLayoutEffect,kn=Ie.useDebugValue;function Cn(e,t){var n=t(),r=vn({inst:{value:n,getSnapshot:t}}),o=r[0].inst,l=r[1];return Sn(function(){o.value=n,o.getSnapshot=t,Fe(o)&&l({inst:o})},[e,n,t]),wn(function(){return Fe(o)&&l({inst:o}),e(function(){Fe(o)&&l({inst:o})})},[e]),kn(n),n}function Fe(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!gn(e,n)}catch{return!0}}function Tn(e,t){return t()}var In=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Tn:Cn;Wt.useSyncExternalStore=Ie.useSyncExternalStore!==void 0?Ie.useSyncExternalStore:In;Ut.exports=Wt;var En=Ut.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 Pe=i,jn=En;function Rn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var zn=typeof Object.is=="function"?Object.is:Rn,Nn=jn.useSyncExternalStore,Ln=Pe.useRef,Mn=Pe.useEffect,Dn=Pe.useMemo,On=Pe.useDebugValue;Ft.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var l=Ln(null);if(l.current===null){var c={hasValue:!1,value:null};l.current=c}else c=l.current;l=Dn(function(){function a(y){if(!u){if(u=!0,f=y,y=r(y),o!==void 0&&c.hasValue){var h=c.value;if(o(h,y))return m=h}return m=y}if(h=m,zn(f,y))return h;var g=r(y);return o!==void 0&&o(h,g)?(f=y,h):(f=y,m=g)}var u=!1,f,m,p=n===void 0?null:n;return[function(){return a(t())},p===null?void 0:function(){return a(p())}]},[t,n,r,o]);var d=Nn(e,l[0],l[1]);return Mn(function(){c.hasValue=!0,c.value=d},[d]),On(d),d};Bt.exports=Ft;var An=Bt.exports;const $n=ln(An),Ht={},{useDebugValue:Pn}=nt,{useSyncExternalStoreWithSelector:_n}=$n;let ft=!1;const Bn=e=>e;function Fn(e,t=Bn,n){(Ht?"production":void 0)!=="production"&&n&&!ft&&(ft=!0);const r=_n(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Pn(r),r}const pt=e=>{const t=typeof e=="function"?yn(e):e,n=(r,o)=>Fn(t,r,o);return Object.assign(n,t),n},Un=e=>e?pt(e):pt,Q="";function se(e){return{Authorization:`Bearer ${e}`}}async function Wn(e){try{const t=await fetch(`${Q}/api/settings/font-size`,{headers:se(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function Hn(e,t){try{await fetch(`${Q}/api/settings/font-size`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function Kn(e){try{const t=await fetch(`${Q}/api/settings/tabs-layout`,{headers:se(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function Vn(e,t){try{await fetch(`${Q}/api/settings/tabs-layout`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function mt(e,t){try{const n=`${Q}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const Oe="ai-cli-online-tabs",ht="ai-cli-online-layout",xt="ai-cli-online-session-names";function Ae(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let c=0;c<e.children.length;c++){const d=Ae(e.children[c],t);d!==null&&(n.push(d),r.push(e.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,d)=>c+d,0),l=r.map(c=>c/o*100);return{...e,children:n,sizes:l}}function Kt(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(l=>Kt(l,t,n,r,o))}}function Vt(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Vt(r,t,n))}}function Ue(e){return e.tabs.find(t=>t.id===e.activeTabId)}function be(e,t,n){return e.map(r=>r.id===t?n(r):r)}function oe(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(Oe,JSON.stringify(t))}catch{}Gn(t)}let Le=null,Me=null,Se=null,Re=null;function Gn(e){Re=e,Se&&clearTimeout(Se),Se=setTimeout(()=>{Se=null,Re=null;const t=M.getState().token;t&&Vn(t,e)},2e3)}function Jn(e){Le&&clearTimeout(Le),Le=setTimeout(()=>{Le=null,oe(e)},500)}function Yn(){try{const e=localStorage.getItem(Oe);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(ht);if(e){const t=JSON.parse(e);let n="Default";try{const l=localStorage.getItem(xt);if(l){const c=JSON.parse(l),d=Object.values(c)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Oe,JSON.stringify(o))}catch{}return localStorage.removeItem(ht),localStorage.removeItem(xt),o}}catch{}return null}function te(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function qn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.tabs){if(c.status!=="open"){const u=c.terminalIds.filter(f=>n.has(f));if(u.length>0){let f=c.layout;for(const m of c.terminalIds)!n.has(m)&&f&&(f=Ae(f,m));r.push({...c,terminalIds:u,layout:f})}continue}const d=c.terminalIds.filter(u=>n.has(u));if(d.length===0)continue;let a=c.layout;for(const u of c.terminalIds)!n.has(u)&&a&&(a=Ae(a,u));r.push({...c,terminalIds:d,layout:a})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(d=>d.status==="open");o=(c==null?void 0:c.id)||""}return{...e,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var t,n;const e=(n=(t=M==null?void 0:M.getState)==null?void 0:t.call(M))==null?void 0:n.token;if(e)if(Re)Se&&(clearTimeout(Se),Se=null),mt(e,Re),Re=null;else{const r=M.getState();r.tabs.length>0&&mt(e,te(r))}});function yt(e,t){const n=e.tabs.find(u=>u.terminalIds.includes(t));if(!n){const{[t]:u,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(u=>u!==t),o=n.layout?Ae(n.layout,t):null,l=be(e.tabs,n.id,u=>({...u,terminalIds:r,layout:o})),{[t]:c,...d}=e.terminalsMap,a={terminalsMap:d,tabs:l};return n.id===e.activeTabId&&(a.terminalIds=r,a.layout=o),a}const M=Un((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{var r;if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Wn(n).then(l=>{t().token===n&&e({fontSize:l})});const o=Yn();if(o&&o.tabs.length>0){const l={};for(const a of o.tabs)if(a.status==="open")for(const u of a.terminalIds)l[u]={id:u,connected:!1,sessionResumed:!1,error:null,panelMode:((r=a.panelModes)==null?void 0:r[u])||"none"};const c=o.tabs.find(a=>a.id===o.activeTabId&&a.status==="open")||o.tabs.find(a=>a.status==="open"),d=(c==null?void 0:c.id)||"";e({token:n,tabsLoading:!0,terminalsMap:l,tabs:o.tabs,activeTabId:d,nextId:o.nextId,nextSplitId:o.nextSplitId,nextTabId:o.nextTabId,terminalIds:(c==null?void 0:c.terminalIds)||[],layout:(c==null?void 0:c.layout)||null})}else e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Xn(n,o);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(Oe),e({token:n,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:n=>{const r=t(),o=`tab${r.nextTabId}`,l=`t${r.nextId}`,c={id:l,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},d={type:"leaf",terminalId:l},a={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[l],layout:d,createdAt:Date.now()};return e({tabs:[...r.tabs,a],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[l]:c},terminalIds:a.terminalIds,layout:a.layout}),oe(te(t())),o},switchTab:n=>{const o=t().tabs.find(l=>l.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),oe(te(t())))},closeTab:n=>{const r=t(),o=r.tabs.find(m=>m.id===n);if(!o||o.status!=="open"||r.tabs.filter(m=>m.status==="open").length<=1)return;const c={...r.terminalsMap};for(const m of o.terminalIds)delete c[m];const d=be(r.tabs,n,m=>({...m,status:"closed"}));let a=r.activeTabId,u=r.terminalIds,f=r.layout;if(r.activeTabId===n){const m=r.tabs.findIndex(h=>h.id===n),p=d.filter(h=>h.status==="open"),y=p.find(h=>d.findIndex(k=>k.id===h.id)>m)||p[p.length-1];y&&(a=y.id,u=y.terminalIds,f=y.layout)}e({tabs:d,activeTabId:a,terminalsMap:c,terminalIds:u,layout:f}),oe(te(t()))},reopenTab:n=>{var d;const r=t(),o=r.tabs.find(a=>a.id===n);if(!o||o.status!=="closed")return;const l={...r.terminalsMap};for(const a of o.terminalIds)l[a]={id:a,connected:!1,sessionResumed:!1,error:null,panelMode:((d=o.panelModes)==null?void 0:d[a])||"none"};const c=be(r.tabs,n,a=>({...a,status:"open"}));e({tabs:c,activeTabId:n,terminalsMap:l,terminalIds:o.terminalIds,layout:o.layout}),oe(te(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(y=>y.id===n);if(!o)return;const l=r.token;l&&await Promise.all(o.terminalIds.map(y=>fetch(`${Q}/api/sessions/${encodeURIComponent(y)}`,{method:"DELETE",headers:se(l)}).catch(()=>{})));const c=t(),d=c.tabs.find(y=>y.id===n);if(!d)return;const a={...c.terminalsMap};for(const y of d.terminalIds)delete a[y];const u=c.tabs.filter(y=>y.id!==n);let f=c.activeTabId,m=c.terminalIds,p=c.layout;if(c.activeTabId===n){const y=u.find(h=>h.status==="open");y?(f=y.id,m=y.terminalIds,p=y.layout):(f="",m=[],p=null)}e({tabs:u,activeTabId:f,terminalsMap:a,terminalIds:m,layout:p}),oe(te(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=be(t().tabs,n,l=>({...l,name:r}));e({tabs:o}),oe(te(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const l=Ue(o);if(!l){const O=`tab${o.nextTabId}`,D=r||`t${o.nextId}`;let R=o.nextId;const j=D.match(/^t(\d+)$/);j&&(R=Math.max(R,parseInt(j[1],10)+1));const v=r?R:R+1,x={id:D,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},z={type:"leaf",terminalId:D},A={id:O,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[D],layout:z,createdAt:Date.now()};return e({tabs:[...o.tabs,A],activeTabId:O,nextTabId:o.nextTabId+1,nextId:v,terminalsMap:{...o.terminalsMap,[D]:x},terminalIds:[D],layout:z}),oe(te(t())),D}const{nextId:c,nextSplitId:d,terminalsMap:a}=o,{terminalIds:u,layout:f}=l,m=r||`t${c}`;let p=c;const y=m.match(/^t(\d+)$/);y&&(p=Math.max(p,parseInt(y[1],10)+1));const h={id:m,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},g={type:"leaf",terminalId:m};let k,T=d;if(!f)k=g;else if(f.type==="leaf"){const O=n||"horizontal";k={id:`s${T}`,type:"split",direction:O,children:[f,g],sizes:[50,50]},T++}else if(f.direction===(n||"horizontal")){const D=100/(f.children.length+1),R=(100-D)/100,j=[...f.sizes.map(v=>v*R),D];k={...f,children:[...f.children,g],sizes:j}}else{const O=n||"horizontal";k={id:`s${T}`,type:"split",direction:O,children:[f,g],sizes:[50,50]},T++}const C=[...u,m],S=r?p:p+1,w=be(o.tabs,l.id,O=>({...O,terminalIds:C,layout:k}));return e({terminalsMap:{...a,[m]:h},terminalIds:C,layout:k,tabs:w,nextId:S,nextSplitId:T}),oe(te(t())),m},splitTerminal:(n,r)=>{const o=t(),l=Ue(o);if(!l||!l.layout)return"";const{nextId:c,nextSplitId:d,terminalsMap:a}=o,u=`t${c}`,f={id:u,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},m={type:"leaf",terminalId:u},p=`s${d}`,y=Kt(l.layout,n,r,m,p),h=[...l.terminalIds,u],g=c+1,k=d+1,T=be(o.tabs,l.id,C=>({...C,terminalIds:h,layout:y}));return e({terminalsMap:{...a,[u]:f},terminalIds:h,layout:y,tabs:T,nextId:g,nextSplitId:k}),oe(te(t())),u},removeTerminal:n=>{const r=yt(t(),n);r&&(e(r),oe(te(t())))},setTerminalConnected:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,error:r}}}})},setTerminalPanelMode:(n,r)=>{const o=t(),l=o.terminalsMap[n];if(!l||l.panelMode===r)return;const c={...o.terminalsMap,[n]:{...l,panelMode:r}},d=o.tabs.find(u=>u.terminalIds.includes(n));let a=o.tabs;if(d){const u={...d.panelModes,[n]:r};a=be(o.tabs,d.id,f=>({...f,panelModes:u}))}e({terminalsMap:c,tabs:a}),oe(te(t()))},setSplitSizes:(n,r)=>{const o=t(),l=Ue(o);if(!l||!l.layout)return;const c=Vt(l.layout,n,r),d=be(o.tabs,l.id,a=>({...a,layout:c}));e({layout:c,tabs:d}),Jn(te(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),Me&&clearTimeout(Me),Me=setTimeout(()=>{Me=null;const o=t().token;o&&Hn(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${Q}/api/sessions`,{headers:se(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}},killServerSession:async n=>{const r=t().token;if(!r)return;try{await fetch(`${Q}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:se(r)})}catch{}const o=yt(t(),n);o&&(e(o),oe(te(t()))),setTimeout(()=>t().fetchSessions(),500)}}));async function Xn(e,t){var o,l;const{setState:n,getState:r}=M;try{const[c,d]=await Promise.all([Kn(e),fetch(`${Q}/api/sessions`,{headers:se(e)}).then(h=>h.ok?h.json():[]).catch(()=>[])]);if(r().token!==e)return;const a=c&&((o=c.tabs)==null?void 0:o.length)>0?c:t;if(!a||a.tabs.length===0){n({tabsLoading:!1});return}const u=qn(a,d);if(!u){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:a.nextId,nextSplitId:a.nextSplitId,nextTabId:a.nextTabId,terminalIds:[],layout:null});return}const f=r().terminalsMap,m={};for(const h of u.tabs)if(h.status==="open")for(const g of h.terminalIds)m[g]=f[g]||{id:g,connected:!1,sessionResumed:!1,error:null,panelMode:((l=h.panelModes)==null?void 0:l[g])||"none"};const p=u.tabs.find(h=>h.id===u.activeTabId&&h.status==="open")||u.tabs.find(h=>h.status==="open"),y=(p==null?void 0:p.id)||"";n({tabsLoading:!1,terminalsMap:m,tabs:u.tabs,activeTabId:y,nextId:u.nextId,nextSplitId:u.nextSplitId,nextTabId:u.nextTabId,terminalIds:(p==null?void 0:p.terminalIds)||[],layout:(p==null?void 0:p.layout)||null}),oe(te(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function Zn(){const[e,t]=i.useState(""),n=M(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, #1a1b26 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"#24283b",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid #292e42"},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, #7aa2f7 0%, #bb9af7 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"#1a1b26",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"#c0caf5",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"#565f89",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:"#7aa2f7",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"#1a1b26",color:"#c0caf5",border:"1px solid #292e42",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:e.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#414868",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"#1a1b26",padding:"2px 6px",borderRadius:"4px",border:"1px solid #292e42",fontSize:"11px"},children:"server/.env"})]})})]})})}const _e=new Map;function Qn(e,t,n){_e.set(e,{onChunk:t,onControl:n})}function er(e){_e.delete(e)}function tr(e,t){var n;(n=_e.get(e))==null||n.onChunk(t)}function nr(e,t){var n;(n=_e.get(e))==null||n.onControl(t)}const rr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,De=500,or=8e3,sr=1e4,bt=4e3,ir=5e3,ar=10,lr=64*1024,cr=1,gt=2,dr=3,ur=4,fr=5,pr=new TextDecoder,mr=new TextEncoder;function vt(e,t){const n=mr.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function hr(e,t,n){const r=i.useRef(null),o=i.useRef(De),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),a=i.useRef(null),u=i.useRef(!1),f=i.useRef(n),m=i.useRef(!1),p=i.useRef(0),y=i.useRef(!0),h=i.useRef(!navigator.onLine),g=i.useRef(""),k=i.useRef(null),T=i.useRef("");f.current=n;const C=i.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),d.current&&(clearTimeout(d.current),d.current=null),l.current&&(clearTimeout(l.current),l.current=null),a.current&&(clearTimeout(a.current),a.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),S=i.useCallback(()=>{const{token:v,setTerminalError:x}=M.getState();if(!v||u.current)return;if(r.current){const L=r.current.readyState;if(L===WebSocket.OPEN||L===WebSocket.CONNECTING)return}m.current=!1;const z=`${rr}?sessionId=${encodeURIComponent(t)}`,A=new WebSocket(z);A.binaryType="arraybuffer",a.current=window.setTimeout(()=>{A.readyState===WebSocket.CONNECTING&&A.close()},ir);const P=()=>{A.readyState===WebSocket.OPEN&&(p.current=performance.now(),A.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{p.current>0&&(p.current=0,A.close())},bt))};A.onopen=()=>{a.current&&(clearTimeout(a.current),a.current=null),A.send(JSON.stringify({type:"auth",token:v})),x(t,null),o.current=De,y.current=!0},A.onclose=L=>{const{setTerminalConnected:F,setTerminalError:H,setToken:G}=M.getState();if(F(t,!1),C(),m.current)return;if(L.code===4001){u.current=!0,H(t,"Authentication failed"),G(null),localStorage.removeItem("ai-cli-online-token");return}if(L.code===4002)return;if(L.code===4005){H(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(y.current){y.current=!1,l.current=window.setTimeout(()=>S(),50);return}const J=o.current;o.current=Math.min(J*2,or);const V=Math.round(J*(.5+Math.random()));l.current=window.setTimeout(()=>{S()},V)},A.onerror=()=>{},A.onmessage=L=>{var F;try{const H=e.current;if(L.data instanceof ArrayBuffer){const J=new Uint8Array(L.data);if(J.length<1)return;const V=J[0],Y=J.subarray(1);switch(V){case cr:H==null||H.write(Y);break;case dr:H==null||H.write(Y);break;case ur:{(F=f.current)==null||F.call(f,pr.decode(Y));break}case fr:{tr(t,Y);break}}return}const G=JSON.parse(L.data);switch(G.type){case"connected":{const J=M.getState();J.setTerminalConnected(t,!0),J.setTerminalResumed(t,G.resumed);const V=e.current;V&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"resize",cols:V.cols,rows:V.rows})),T.current&&(A.send(vt(gt,T.current)),T.current=""),P(),c.current=window.setInterval(P,sr);break}case"error":M.getState().setTerminalError(t,G.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),p.current>0){const J=Math.round(performance.now()-p.current),V=M.getState();(V.terminalIds.length===0||V.terminalIds[0]===t)&&V.setLatency(J),p.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":nr(t,G);break}}catch{}},r.current=A},[t,e,C]),w=i.useCallback(v=>{const x=r.current;if(!x||x.readyState!==WebSocket.OPEN){T.current.length<lr&&(T.current+=v);return}g.current+=v,k.current||(k.current=window.setTimeout(()=>{const z=g.current;g.current="",k.current=null,z&&x.readyState===WebSocket.OPEN&&x.send(vt(gt,z))},ar))},[]),O=i.useCallback((v,x)=>{var z;((z=r.current)==null?void 0:z.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:v,rows:x}))},[]),D=i.useCallback(()=>{var v;((v=r.current)==null?void 0:v.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),R=i.useCallback(v=>{var x;((x=r.current)==null?void 0:x.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:v}))},[]),j=i.useCallback(()=>{var v;((v=r.current)==null?void 0:v.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return i.useEffect(()=>{M.getState().token&&(u.current=!1,S());const x=()=>{h.current=!1,o.current=De,y.current=!0;const P=r.current;(!P||P.readyState===WebSocket.CLOSED||P.readyState===WebSocket.CLOSING)&&S()},z=()=>{h.current=!0},A=()=>{if(document.visibilityState!=="visible")return;const P=r.current;if(!P||P.readyState!==WebSocket.OPEN){!h.current&&!m.current&&(o.current=De,y.current=!0,S());return}p.current=performance.now(),P.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{p.current>0&&(p.current=0,P.close())},bt)};return window.addEventListener("online",x),window.addEventListener("offline",z),document.addEventListener("visibilitychange",A),()=>{m.current=!0,C(),window.removeEventListener("online",x),window.removeEventListener("offline",z),document.removeEventListener("visibilitychange",A),r.current&&(r.current.close(),r.current=null)}},[S,C,t]),{sendInput:w,sendResize:O,requestScrollback:D,requestFileStream:R,cancelFileStream:j}}const Gt={background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",selectionBackground:"#33467c",black:"#15161e",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#414868",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},Jt="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",xr=i.forwardRef(function({sessionId:t},n){const r=i.useRef(null),o=i.useRef(null),l=i.useRef(null),[c,d]=i.useState(!1),[a,u]=i.useState(""),f=M(S=>S.fontSize),m=i.useCallback(S=>{u(S),d(!0)},[]),{sendInput:p,sendResize:y,requestScrollback:h,requestFileStream:g,cancelFileStream:k}=hr(o,t,m);i.useImperativeHandle(n,()=>({sendInput:p,requestFileStream:g,cancelFileStream:k}),[p,g,k]);const T=i.useRef(p),C=i.useRef(y);return T.current=p,C.current=y,i.useEffect(()=>{if(!r.current)return;let S=!1,w=null,O=null,D=null,R=null;if(S||!r.current)return;const j=new Dt({cursorBlink:!0,scrollback:1e4,fontSize:M.getState().fontSize,fontFamily:Jt,theme:Gt,allowProposedApi:!0}),v=new Ot;j.loadAddon(v),j.loadAddon(new cn((L,F)=>{window.open(F,"_blank","noopener,noreferrer")})),j.open(r.current);try{const L=new At;L.onContextLoss(()=>{L.dispose()}),j.loadAddon(L)}catch{}o.current=j,l.current=v,j.onSelectionChange(()=>{const L=j.getSelection();L&&navigator.clipboard.writeText(L).catch(()=>{})});const x=j.element,z=L=>{L.preventDefault(),navigator.clipboard.readText().then(F=>{F&&T.current(F)}).catch(()=>{})};x&&x.addEventListener("contextmenu",z);const A=()=>{try{const L=r.current;if(L&&L.clientWidth>0&&L.clientHeight>0)return v.fit(),C.current(j.cols,j.rows),!0}catch{}return!1};requestAnimationFrame(()=>A());let P=0;return w=setInterval(()=>{P++,(A()||P>=10)&&(clearInterval(w),w=null)},100),document.fonts.ready.then(()=>{if(!S)try{v.fit(),C.current(j.cols,j.rows)}catch{}}),j.onData(L=>{T.current(L)}),R=new ResizeObserver(()=>{O||(O=requestAnimationFrame(()=>{O=null;try{v.fit(),D&&clearTimeout(D),D=setTimeout(()=>{D=null,C.current(j.cols,j.rows)},50)}catch{}}))}),R.observe(r.current),()=>{S=!0,w&&clearInterval(w),O&&cancelAnimationFrame(O),D&&clearTimeout(D),R&&R.disconnect(),x&&x.removeEventListener("contextmenu",z),o.current&&(o.current.dispose(),o.current=null),l.current=null}},[t]),i.useEffect(()=>{const S=o.current,w=l.current;if(!(!S||!w)&&S.options.fontSize!==f){S.options.fontSize=f;try{w.fit()}catch{}C.current(S.cols,S.rows)}},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"#1a1b26",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:S=>{S.currentTarget.blur(),c?(d(!1),u("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:S=>{S.currentTarget.style.opacity="1"},onMouseLeave:S=>{S.currentTarget.style.opacity="0.8"},children:c?"✕":s.jsx("span",{style:{fontSize:16},children:"👁"})}),c&&s.jsx(yr,{data:a,onClose:()=>{d(!1),u("")}})]})});function yr({data:e,onClose:t}){const n=i.useRef(null),r=i.useRef(t);r.current=t;const o=M(a=>a.fontSize),l=i.useRef(null),c=i.useRef(null);i.useEffect(()=>{if(!n.current)return;const a=new Dt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:Jt,theme:Gt});l.current=a;const u=new Ot;c.current=u,a.loadAddon(u),a.open(n.current);try{const g=new At;g.onContextLoss(()=>g.dispose()),a.loadAddon(g)}catch{}a.onSelectionChange(()=>{const g=a.getSelection();g&&navigator.clipboard.writeText(g).catch(()=>{})}),a.attachCustomKeyEventHandler(g=>(g.key==="Escape"&&r.current(),!1)),a.write(e);let f=null;const m=()=>{const g=n.current;if(!g||g.clientWidth<=0||g.clientHeight<=0)return!1;try{return u.fit(),a.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!m()){let g=0;f=setInterval(()=>{g++,(m()||g>=30)&&(clearInterval(f),f=null)},50)}});let p=null;const y=new ResizeObserver(()=>{p||(p=requestAnimationFrame(()=>{p=null,m()}))});y.observe(n.current);const h=g=>{g.key==="Escape"&&r.current()};return document.addEventListener("keydown",h),()=>{f&&clearInterval(f),p&&cancelAnimationFrame(p),document.removeEventListener("keydown",h),y.disconnect(),a.dispose(),l.current=null,c.current=null}},[e]),i.useEffect(()=>{var a;if(l.current){l.current.options.fontSize=o;try{(a=c.current)==null||a.fit()}catch{}}},[o]);const d=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26"},children:[s.jsx("div",{style:{height:d,boxSizing:"border-box",padding:"0 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",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:d,left:0,right:0,bottom:0,overflow:"hidden"}})]})}async function Te(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:se(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function br(e,t,n,r){return new Promise((o,l)=>{const c=new FormData;for(const a of n)c.append("files",a);const d=new XMLHttpRequest;d.open("POST",`${Q}/api/sessions/${encodeURIComponent(t)}/upload`),d.setRequestHeader("Authorization",`Bearer ${e}`),d.upload.addEventListener("progress",a=>{a.lengthComputable&&r&&r(Math.round(a.loaded/a.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?o():l(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>l(new Error("Upload network error"))),d.addEventListener("abort",()=>l(new Error("Upload aborted"))),d.send(c)})}async function gr(e,t){const n=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:se(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function vr(e,t,n){const r=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/touch`,{method:"POST",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error("Failed to create file");return r.json()}async function wr(e,t,n){const r=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:se(e)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),l=URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l)}function ot({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=M(S=>S.token),[l,c]=i.useState(""),[d,a]=i.useState([]),[u,f]=i.useState(!0),[m,p]=i.useState(null),y=i.useRef(""),h=i.useCallback(async S=>{if(o){f(!0),p(null);try{const w=await Te(o,e,S);S||(y.current=w.cwd),c(w.cwd),a(n?n(w.files):w.files)}catch(w){p(w instanceof Error?w.message:"Failed to load files")}finally{f(!1)}}},[o,e,n]);i.useEffect(()=>{h()},[h]),i.useEffect(()=>{if(!r||!o)return;let S=!1;const w=setInterval(async()=>{if(!S)try{const O=await gr(o,e);if(S)return;if(O!==y.current){y.current=O;const D=await Te(o,e);if(S)return;c(D.cwd),a(n?n(D.files):D.files)}}catch{}},r);return()=>{S=!0,clearInterval(w)}},[r,o,e,n]);const g=i.useRef(t);g.current=t,i.useEffect(()=>{const S=w=>{w.key==="Escape"&&g.current()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[]);const k=i.useCallback(S=>{h(l+"/"+S)},[h,l]),T=i.useCallback(()=>{const S=l.replace(/\/[^/]+$/,"")||"/";h(S)},[h,l]),C=i.useCallback(()=>{h(l)},[h,l]);return{cwd:l,files:d,loading:u,error:m,setError:p,handleNavigate:k,handleGoUp:T,handleRefresh:C}}function st(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Yt(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function qt(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function it({cwd:e,onGoUp:t,onRefresh:n,onClose:r}){return s.jsxs("div",{style:{padding:"6px 12px",background:"#24283b",borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[s.jsx("button",{onClick:t,style:{background:"none",border:"1px solid #414868",color:"#7aa2f7",borderRadius:3,padding:"1px 8px",fontSize:12,cursor:"pointer",flexShrink:0},title:"Go to parent directory",children:".."}),s.jsx("span",{style:{color:"#7aa2f7",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e||"..."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[s.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Refresh",children:"↻"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Close (ESC)",children:"✕"})]})]})}function at({loading:e,error:t,empty:n,emptyText:r="Empty directory"}){return e?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):t?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:t}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function Sr({sessionId:e,onClose:t}){const n=M(h=>h.token),{cwd:r,files:o,loading:l,error:c,setError:d,handleNavigate:a,handleGoUp:u,handleRefresh:f}=ot({sessionId:e,onClose:t}),[m,p]=i.useState(null),y=async h=>{if(n){p(h);try{await wr(n,e,r+"/"+h)}catch(g){d(g instanceof Error?g.message:"Download failed")}finally{p(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(it,{cwd:r,onGoUp:u,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(at,{loading:l,error:c,empty:o.length===0,emptyText:"Empty directory"}),!l&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&a(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:g=>{g.stopPropagation(),y(h.name)},disabled:m===h.name,style:{background:"none",border:"1px solid #414868",color:m===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:m===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:m===h.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:h.type==="directory"?"#7aa2f7":"#565f89"},children:h.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:h.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:h.type==="file"?st(h.size):""})]},h.name))]})]})}let Ee=null;const kr=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"];function Cr(e){return e.initialize({startOnLoad:!1,theme:"dark",themeVariables:{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"},gantt:{titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800}}),e}function Tr(){return Ee||(Ee=(async()=>{for(const e of kr)try{const t=await import(e);return Cr(t.default)}catch{}throw Ee=null,new Error("All mermaid CDN sources failed")})(),Ee)}let Ir=0;function Xt(e,t){i.useEffect(()=>{const n=e.current;if(!n)return;const r=n.querySelectorAll("code.language-mermaid, code.language-gantt");if(r.length===0)return;let o=!1;return(async()=>{let l;try{l=await Tr()}catch{if(o)return;for(const d of r){const a=d.parentElement;if(!a||a.tagName!=="PRE")continue;a.classList.add("mermaid-error");const u=document.createElement("div");u.className="mermaid-error__msg",u.textContent="Failed to load Mermaid library",a.appendChild(u)}return}if(!o)for(const c of r){if(o)break;const d=c.parentElement;if(!d||d.tagName!=="PRE")continue;const a=c.textContent||"";if(!a.trim())continue;const u=`mermaid-${++Ir}`;try{const{svg:f}=await l.render(u,a);if(o)break;const m=document.createElement("div");m.className="mermaid-diagram",m.innerHTML=f,d.replaceWith(m)}catch{if(o)break;d.classList.add("mermaid-error");const f=document.createElement("div");f.className="mermaid-error__msg",f.textContent="Mermaid syntax error",d.appendChild(f)}}})(),()=>{o=!0}},[t])}function Er({content:e}){const t=M(o=>o.fontSize),n=i.useRef(null),r=i.useMemo(()=>{if(!e)return"";const o=rt.parse(e,{async:!1});return $t.sanitize(o,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[e]);return Xt(n,r),e?s.jsx("div",{ref:n,className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${t}px`},dangerouslySetInnerHTML:{__html:r}}):s.jsx("div",{className:"md-preview",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#414868",fontStyle:"italic",fontSize:"13px"},children:"Waiting for plan output..."})}async function jr(e,t){const n=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:se(e)});return n.ok?(await n.json()).content??"":""}async function wt(e,t,n){await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const Rr=50;function Xe(){const e=i.useRef([]),t=i.useCallback(o=>{e.current.push(o),e.current.length>Rr&&e.current.shift()},[]),n=i.useCallback(()=>e.current.pop(),[]),r=i.useCallback(()=>{e.current=[]},[]);return i.useMemo(()=>({pushUndo:t,popUndo:n,clearUndo:r}),[t,n,r])}function Ze(e,t,n){e.preventDefault();const r=e.currentTarget,o=r.selectionStart,l=r.selectionEnd,c=r.value;n==null||n(c);const d=c.slice(0,o)+" "+c.slice(l);t(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function Qe(e,t,n){const r=t();return r!==void 0?(e.preventDefault(),n(r),!0):!1}function et(e,t=10){var n;return Math.min(t,Math.max(1,(((n=e.match(/\n/g))==null?void 0:n.length)??0)+1))}const lt="chat-history",St=50;function Zt(){try{const e=localStorage.getItem(lt);return e?JSON.parse(e):[]}catch{return[]}}function zr(e){const n=Zt().filter(r=>r.text!==e);n.unshift({text:e,ts:Date.now()}),n.length>St&&(n.length=St),localStorage.setItem(lt,JSON.stringify(n))}const kt=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],Nr=i.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},l){const c=M(b=>b.fontSize),[d,a]=i.useState(""),u=i.useRef(null),f=i.useRef(void 0),m=i.useRef(!1),{pushUndo:p,popUndo:y}=Xe(),h=i.useRef(d);h.current=d;const g=i.useCallback(()=>p(h.current),[p]),[k,T]=i.useState(!1),[C,S]=i.useState(""),[w,O]=i.useState(0),[D,R]=i.useState(!1),[j,v]=i.useState([]),[x,z]=i.useState(0),[A,P]=i.useState(""),L=i.useRef(null),F=i.useMemo(()=>{if(!A)return j;const b=A.toLowerCase();return j.filter(E=>E.text.toLowerCase().includes(b))},[j,A]),[H,G]=i.useState(!1),[J,V]=i.useState(""),[Y,me]=i.useState(""),[he,ee]=i.useState(0),[de,xe]=i.useState([]),[ue,ye]=i.useState(!1),ae=i.useRef(""),fe=i.useRef(null),N=i.useMemo(()=>{if(!C)return kt;const b=C.toLowerCase();return kt.filter(E=>E.cmd.toLowerCase().includes(b)||E.desc.toLowerCase().includes(b))},[C]),I=i.useMemo(()=>{let b=de;if(J){const E=J.toLowerCase();b=b.filter(U=>U.name.toLowerCase().includes(E))}return[...b].sort((E,U)=>E.type==="directory"&&U.type!=="directory"?-1:E.type!=="directory"&&U.type==="directory"?1:E.name.localeCompare(U.name))},[de,J]);i.useEffect(()=>{let b=!1;return jr(o,r).then(E=>{!b&&E&&a(E),m.current=!0}).catch(()=>{m.current=!0}),()=>{b=!0}},[o,r]),i.useEffect(()=>{if(m.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{wt(o,r,d).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[d,o,r]),i.useEffect(()=>{var b;(b=u.current)==null||b.focus()},[]),i.useEffect(()=>{if(!H)return;let b=!1;return ye(!0),(async()=>{try{if(Y){if(!ae.current){const q=await Te(o,r);if(b)return;ae.current=q.cwd}const E=`${ae.current}/${Y.replace(/\/$/,"")}`,U=await Te(o,r,E);if(b)return;xe(U.files)}else{const E=await Te(o,r);if(b)return;ae.current=E.cwd,xe(E.files)}ye(!1)}catch{if(b)return;xe([]),ye(!1)}})(),()=>{b=!0}},[H,Y,o,r]),i.useEffect(()=>{if(!H||!fe.current)return;const b=fe.current.querySelector(".file-item--active");b==null||b.scrollIntoView({block:"nearest"})},[he,H]);const $=i.useCallback(()=>{const b=h.current.trim();b&&(zr(b),t(b),a(""),wt(o,r,"").catch(()=>{}))},[t,o,r]),B=i.useCallback(b=>{g(),a(b)},[g]);i.useImperativeHandle(l,()=>({send:$,fillContent:B}),[$,B]),i.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const W=i.useCallback(()=>{const b=Zt();T(!1),S("");const E=u.current;if(E){const U=E.selectionStart,q=d.slice(0,U),re=d.slice(U),we=q.match(/(?:^|\s)(\/history)\s*$/);if(we){const le=q.length-we[1].length;a(d.slice(0,le)+re)}}b.length!==0&&(v(b),z(0),P(""),R(!0))},[d]),ne=i.useCallback(b=>{g(),a(b.text),R(!1),requestAnimationFrame(()=>{const E=u.current;E&&(E.selectionStart=E.selectionEnd=b.text.length,E.focus())})},[g]),_=i.useCallback(b=>{const E=F[b];if(!E)return;const U=j.filter(re=>re.ts!==E.ts||re.text!==E.text);v(U),localStorage.setItem(lt,JSON.stringify(U));const q=A?U.filter(re=>re.text.toLowerCase().includes(A.toLowerCase())):U;x>=q.length&&z(Math.max(0,q.length-1))},[F,j,x,A]);i.useEffect(()=>{if(!D||!L.current)return;const b=L.current.querySelector(".history-item--active");b==null||b.scrollIntoView({block:"nearest"})},[x,D]);const K=i.useCallback(b=>{if(b==="/history"){W();return}const E=u.current;if(!E)return;g();const U=E.selectionStart,q=d.slice(0,U),re=d.slice(U),le=q.lastIndexOf(`
|
|
26
|
-
`)+1,pe=q.slice(le).match(/\/[a-zA-Z:-]*$/);if(pe){const ie=le+(pe.index??0),ke=b+" ",Be=d.slice(0,ie)+ke+re;a(Be);const rn=ie+ke.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=rn,E.focus()})}else{const ie=q+b+re;a(ie);const ke=U+b.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ke,E.focus()})}T(!1),S(""),O(0)},[d,g,W]),X=i.useCallback(b=>{const E=u.current;if(!E)return;g();const U=E.selectionStart,q=d.slice(0,U),re=d.slice(U),we=q.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!we)return;const le=q.length-we[0].length;if(b.type==="directory"){const ce="@"+Y+b.name+"/",pe=d.slice(0,le)+ce+re;a(pe);const ie=le+ce.length;me(Y+b.name+"/"),V(""),ee(0),requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ie,E.focus()})}else{const ce=b.name+" ",pe=d.slice(0,le)+ce+re;a(pe);const ie=le+ce.length;G(!1),V(""),me(""),ee(0),xe([]),ae.current="",requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ie,E.focus()})}},[d,Y,g]),Z=i.useCallback(b=>{const E=b.target.value;if(a(E),D){const ce=E.trim();ce?(P(ce),z(0)):P("");return}const U=b.target.selectionStart,q=E.slice(0,U),re=q.lastIndexOf(`
|
|
27
|
-
`),le=q.slice(re+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(le)T(!0),S(le[1]),O(0),G(!1);else{T(!1);const ce=q.match(/@([a-zA-Z0-9_.\-/]*)$/);if(ce){const pe=ce[1],ie=pe.lastIndexOf("/"),ke=ie>=0?pe.slice(0,ie+1):"",Be=ie>=0?pe.slice(ie+1):pe;V(Be),ee(0),me(ke),G(!0)}else G(!1)}},[D]),ve=i.useCallback(b=>{if(k&&N.length>0){if(b.key==="ArrowDown"){b.preventDefault(),O(E=>(E+1)%N.length);return}if(b.key==="ArrowUp"){b.preventDefault(),O(E=>(E-1+N.length)%N.length);return}if(b.key==="Enter"||b.key==="Tab"){b.preventDefault(),K(N[w].cmd);return}if(b.key==="Escape"){b.preventDefault(),T(!1);return}}if(H&&I.length>0){if(b.key==="ArrowDown"){b.preventDefault(),ee(E=>(E+1)%I.length);return}if(b.key==="ArrowUp"){b.preventDefault(),ee(E=>(E-1+I.length)%I.length);return}if(b.key==="Tab"||b.key==="Enter"){b.preventDefault(),X(I[he]);return}if(b.key==="Escape"){b.preventDefault(),G(!1);return}}if(D&&F.length>0){if(b.key==="ArrowDown"){b.preventDefault(),z(E=>(E+1)%F.length);return}if(b.key==="ArrowUp"){b.preventDefault(),z(E=>(E-1+F.length)%F.length);return}if(b.key==="Enter"){b.preventDefault(),ne(F[x]);return}if(b.key==="Delete"||b.key==="Backspace"&&(b.ctrlKey||b.metaKey)){b.preventDefault(),_(x);return}if(b.key==="Escape"){b.preventDefault(),R(!1);return}}if(b.key==="z"&&(b.ctrlKey||b.metaKey)&&!b.shiftKey){Qe(b,y,a);return}if(b.key==="Tab"){Ze(b,a,p);return}b.key==="Enter"&&(b.ctrlKey||b.metaKey)&&(b.preventDefault(),$())},[$,k,N,w,K,H,I,he,X,p,y,D,F,x,ne,_]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[k&&N.length>0&&s.jsx("div",{className:"slash-dropdown",children:N.map((b,E)=>s.jsxs("div",{className:`slash-item${E===w?" slash-item--active":""}`,onMouseDown:U=>{U.preventDefault(),K(b.cmd)},onMouseEnter:()=>O(E),children:[s.jsx("span",{className:"slash-cmd",children:b.cmd}),s.jsx("span",{className:"slash-desc",children:b.desc})]},b.cmd))}),H&&(ue||I.length>0)&&s.jsx("div",{className:"file-dropdown",ref:fe,children:ue?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):I.map((b,E)=>s.jsxs("div",{className:`file-item${E===he?" file-item--active":""}`,onMouseDown:U=>{U.preventDefault(),X(b)},onMouseEnter:()=>ee(E),children:[s.jsx("span",{className:"file-icon",children:b.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:b.name})]},b.name))}),D&&s.jsx("div",{className:"history-dropdown",ref:L,children:F.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):F.map((b,E)=>s.jsxs("div",{className:`history-item${E===x?" history-item--active":""}`,onMouseDown:U=>{U.preventDefault(),ne(b)},onMouseEnter:()=>z(E),children:[s.jsx("span",{className:"history-text",children:b.text.length>120?b.text.slice(0,120)+"...":b.text}),s.jsx("span",{className:"history-time",children:new Date(b.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:U=>{U.preventDefault(),U.stopPropagation(),_(E)},title:"Delete (Del key)",children:"×"})]},`${b.ts}-${E}`))}),s.jsx("textarea",{ref:u,className:"md-editor-textarea",value:d,onChange:Z,onKeyDown:ve,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function Lr({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:l,error:c,handleNavigate:d,handleGoUp:a,handleRefresh:u}=ot({sessionId:e,onClose:n}),f=(m,p)=>{t(r+"/"+m,p)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(it,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(at,{loading:l,error:c,empty:o.length===0,emptyText:"No files found"}),!l&&!c&&o.map(m=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent"},onClick:()=>{m.type==="directory"?d(m.name):f(m.name,m.size)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:m.type==="directory"?"#7aa2f7":"#565f89"},children:Yt(m.name,m.type)}),s.jsx("span",{style:{flex:1,color:m.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m.name}),m.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:st(m.size)})]},m.name))]})]})}const Mr="modulepreload",Dr=function(e){return"/"+e},Ct={},Or=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(a=>{if(a=Dr(a),a in Ct)return;Ct[a]=!0;const u=a.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${f}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":Mr,u||(m.as="script"),m.crossOrigin="",m.href=a,d&&m.setAttribute("nonce",d),document.head.appendChild(m),u)return new Promise((p,y)=>{m.addEventListener("load",p),m.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${a}`)))})}))}function l(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&l(d.reason);return t().catch(l)})};let tt=null,We=null;function Ar(){return We||(We=Or(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(tt=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),We}function $r({data:e,scrollRef:t}){const n=i.useRef(null),[r,o]=i.useState(null),[l,c]=i.useState(!0),d=i.useRef(0),a=u=>{n.current=u,t==null||t(u)};return i.useEffect(()=>{if(!e)return;const u=++d.current;return c(!0),o(null),(async()=>{try{if(await Ar(),!tt||u!==d.current)return;let f;if(e instanceof Uint8Array)f=e;else{const h=atob(e);f=new Uint8Array(h.length);for(let g=0;g<h.length;g++)f[g]=h.charCodeAt(g)}const m=await tt.getDocument({data:f}).promise;if(u!==d.current)return;const p=n.current;if(!p)return;for(;p.firstChild;)p.removeChild(p.firstChild);const y=p.clientWidth-24;for(let h=1;h<=m.numPages;h++){const g=await m.getPage(h);if(u!==d.current)return;const k=g.getViewport({scale:1}),T=Math.min(y/k.width,2),C=g.getViewport({scale:T}),S=document.createElement("canvas");S.width=C.width,S.height=C.height,S.style.display="block",S.style.margin="0 auto 8px",S.style.maxWidth="100%";const w=S.getContext("2d");if(w){if(await g.render({canvasContext:w,viewport:C,canvas:S}).promise,u!==d.current)return;p.appendChild(S)}}c(!1)}catch(f){if(u!==d.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{d.current++}},[e]),s.jsxs("div",{ref:a,className:"pdf-renderer",children:[l&&s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading PDF..."}),r&&s.jsxs("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:["PDF Error: ",r]})]})}const Ne=typeof window<"u"?i.useLayoutEffect:i.useEffect;function Tt(e){if(e!==void 0)switch(typeof e){case"number":return e;case"string":{if(e.endsWith("px"))return parseFloat(e);break}}}function Pr({box:e,defaultHeight:t,defaultWidth:n,disabled:r,element:o,mode:l,style:c}){const{styleHeight:d,styleWidth:a}=i.useMemo(()=>({styleHeight:Tt(c==null?void 0:c.height),styleWidth:Tt(c==null?void 0:c.width)}),[c==null?void 0:c.height,c==null?void 0:c.width]),[u,f]=i.useState({height:t,width:n}),m=r||d!==void 0||l==="only-width"||d!==void 0&&a!==void 0;return Ne(()=>{if(o===null||m)return;const p=new ResizeObserver(y=>{for(const h of y){const{contentRect:g,target:k}=h;o===k&&f(T=>T.height===g.height&&T.width===g.width?T:{height:g.height,width:g.width})}});return p.observe(o,{box:e}),()=>{p==null||p.unobserve(o)}},[e,m,o,d,a]),i.useMemo(()=>({height:d??u.height,width:a??u.width}),[u,d,a])}function _r(e){const t=i.useRef(()=>{throw new Error("Cannot call during render.")});return Ne(()=>{t.current=e},[e]),i.useCallback(n=>{var r;return(r=t.current)==null?void 0:r.call(t,n)},[t])}function He({containerElement:e,direction:t,isRtl:n,scrollOffset:r}){return r}function ge(e,t="Assertion error"){if(!e)throw Error(t)}function ze(e,t){if(e===t)return!0;if(!!e!=!!t||(ge(e!==void 0),ge(t!==void 0),Object.keys(e).length!==Object.keys(t).length))return!1;for(const n in e)if(!Object.is(t[n],e[n]))return!1;return!0}function Qt({cachedBounds:e,itemCount:t,itemSize:n}){if(t===0)return 0;if(typeof n=="number")return t*n;{const r=e.get(e.size===0?0:e.size-1);ge(r!==void 0,"Unexpected bounds cache miss");const o=(r.scrollOffset+r.size)/e.size;return t*o}}function Br({align:e,cachedBounds:t,index:n,itemCount:r,itemSize:o,containerScrollOffset:l,containerSize:c}){if(n<0||n>=r)throw RangeError(`Invalid index specified: ${n}`,{cause:`Index ${n} is not within the range of 0 - ${r-1}`});const d=Qt({cachedBounds:t,itemCount:r,itemSize:o}),a=t.get(n),u=Math.max(0,Math.min(d-c,a.scrollOffset)),f=Math.max(0,a.scrollOffset-c+a.size);switch(e==="smart"&&(l>=f&&l<=u?e="auto":e="center"),e){case"start":return u;case"end":return f;case"center":return a.scrollOffset<=c/2?0:a.scrollOffset+a.size/2>=d-c/2?d-c:a.scrollOffset+a.size/2-c/2;case"auto":default:return l>=f&&l<=u?l:l<f?f:u}}function Ke({cachedBounds:e,containerScrollOffset:t,containerSize:n,itemCount:r,overscanCount:o}){const l=r-1;let c=0,d=-1,a=0,u=-1,f=0;for(;f<l;){const m=e.get(f);if(m.scrollOffset+m.size>t)break;f++}for(c=f,a=Math.max(0,c-o);f<l;){const m=e.get(f);if(m.scrollOffset+m.size>=t+n)break;f++}return d=Math.min(l,f),u=Math.min(r-1,d+o),c<0&&(c=0,d=-1,a=0,u=-1),{startIndexVisible:c,stopIndexVisible:d,startIndexOverscan:a,stopIndexOverscan:u}}function Fr({itemCount:e,itemProps:t,itemSize:n}){const r=new Map;return{get(o){for(ge(o<e,`Invalid index ${o}`);r.size-1<o;){const c=r.size;let d;switch(typeof n){case"function":{d=n(c,t);break}case"number":{d=n;break}}if(c===0)r.set(c,{size:d,scrollOffset:0});else{const a=r.get(c-1);ge(a!==void 0,`Unexpected bounds cache miss for index ${o}`),r.set(c,{scrollOffset:a.scrollOffset+a.size,size:d})}}const l=r.get(o);return ge(l!==void 0,`Unexpected bounds cache miss for index ${o}`),l},set(o,l){r.set(o,l)},get size(){return r.size}}}function Ur({itemCount:e,itemProps:t,itemSize:n}){return i.useMemo(()=>Fr({itemCount:e,itemProps:t,itemSize:n}),[e,t,n])}function Wr({containerSize:e,itemSize:t}){let n;switch(typeof t){case"string":{ge(t.endsWith("%"),`Invalid item size: "${t}"; string values must be percentages (e.g. "100%")`),ge(e!==void 0,"Container size must be defined if a percentage item size is specified"),n=e*parseInt(t)/100;break}default:{n=t;break}}return n}function Hr({containerElement:e,containerStyle:t,defaultContainerSize:n=0,direction:r,isRtl:o=!1,itemCount:l,itemProps:c,itemSize:d,onResize:a,overscanCount:u}){const{height:f=n,width:m=n}=Pr({defaultHeight:n,defaultWidth:void 0,element:e,mode:"only-height",style:t}),p=i.useRef({height:0,width:0}),y=f,h=Wr({containerSize:y,itemSize:d});i.useLayoutEffect(()=>{if(typeof a=="function"){const x=p.current;(x.height!==f||x.width!==m)&&(a({height:f,width:m},{...x}),x.height=f,x.width=m)}},[f,a,m]);const g=Ur({itemCount:l,itemProps:c,itemSize:h}),k=i.useCallback(x=>g.get(x),[g]),[T,C]=i.useState(()=>Ke({cachedBounds:g,containerScrollOffset:0,containerSize:y,itemCount:l,overscanCount:u})),{startIndexVisible:S,startIndexOverscan:w,stopIndexVisible:O,stopIndexOverscan:D}={startIndexVisible:Math.min(l-1,T.startIndexVisible),startIndexOverscan:Math.min(l-1,T.startIndexOverscan),stopIndexVisible:Math.min(l-1,T.stopIndexVisible),stopIndexOverscan:Math.min(l-1,T.stopIndexOverscan)},R=i.useCallback(()=>Qt({cachedBounds:g,itemCount:l,itemSize:h}),[g,l,h]),j=i.useCallback(x=>{const z=He({containerElement:e,direction:r,isRtl:o,scrollOffset:x});return Ke({cachedBounds:g,containerScrollOffset:z,containerSize:y,itemCount:l,overscanCount:u})},[g,e,y,r,o,l,u]);Ne(()=>{const x=(e==null?void 0:e.scrollTop)??0;C(j(x))},[e,r,j]),Ne(()=>{if(!e)return;const x=()=>{C(z=>{const{scrollLeft:A,scrollTop:P}=e,L=He({containerElement:e,direction:r,isRtl:o,scrollOffset:P}),F=Ke({cachedBounds:g,containerScrollOffset:L,containerSize:y,itemCount:l,overscanCount:u});return ze(F,z)?z:F})};return e.addEventListener("scroll",x),()=>{e.removeEventListener("scroll",x)}},[g,e,y,r,l,u]);const v=_r(({align:x="auto",containerScrollOffset:z,index:A})=>{let P=Br({align:x,cachedBounds:g,containerScrollOffset:z,containerSize:y,index:A,itemCount:l,itemSize:h});if(e){if(P=He({containerElement:e,direction:r,isRtl:o,scrollOffset:P}),typeof e.scrollTo!="function"){const L=j(P);ze(T,L)||C(L)}return P}});return{getCellBounds:k,getEstimatedSize:R,scrollToIndex:v,startIndexOverscan:w,startIndexVisible:S,stopIndexOverscan:D,stopIndexVisible:O}}function Kr(e){return i.useMemo(()=>e,Object.values(e))}function Vr(e,t){const{ariaAttributes:n,style:r,...o}=e,{ariaAttributes:l,style:c,...d}=t;return ze(n,l)&&ze(r,c)&&ze(o,d)}function Gr(e){return e!=null&&typeof e=="object"&&"getAverageRowHeight"in e&&typeof e.getAverageRowHeight=="function"}const Jr="data-react-window-index";function Yr({children:e,className:t,defaultHeight:n=0,listRef:r,onResize:o,onRowsRendered:l,overscanCount:c=3,rowComponent:d,rowCount:a,rowHeight:u,rowProps:f,tagName:m="div",style:p,...y}){const h=Kr(f),g=i.useMemo(()=>i.memo(d,Vr),[d]),[k,T]=i.useState(null),C=Gr(u),S=i.useMemo(()=>C?P=>u.getRowHeight(P)??u.getAverageRowHeight():u,[C,u]),{getCellBounds:w,getEstimatedSize:O,scrollToIndex:D,startIndexOverscan:R,startIndexVisible:j,stopIndexOverscan:v,stopIndexVisible:x}=Hr({containerElement:k,containerStyle:p,defaultContainerSize:n,direction:"vertical",itemCount:a,itemProps:h,itemSize:S,onResize:o,overscanCount:c});i.useImperativeHandle(r,()=>({get element(){return k},scrollToRow({align:P="auto",behavior:L="auto",index:F}){const H=D({align:P,containerScrollOffset:(k==null?void 0:k.scrollTop)??0,index:F});typeof(k==null?void 0:k.scrollTo)=="function"&&k.scrollTo({behavior:L,top:H})}}),[k,D]),Ne(()=>{if(!k)return;const P=Array.from(k.children).filter((L,F)=>{if(L.hasAttribute("aria-hidden"))return!1;const H=`${R+F}`;return L.setAttribute(Jr,H),!0});if(C)return u.observeRowElements(P)},[k,C,u,R,v]),i.useEffect(()=>{R>=0&&v>=0&&l&&l({startIndex:j,stopIndex:x},{startIndex:R,stopIndex:v})},[l,R,j,v,x]);const z=i.useMemo(()=>{const P=[];if(a>0)for(let L=R;L<=v;L++){const F=w(L);P.push(i.createElement(g,{...h,ariaAttributes:{"aria-posinset":L+1,"aria-setsize":a,role:"listitem"},key:L,index:L,style:{position:"absolute",left:0,transform:`translateY(${F.scrollOffset}px)`,height:C?void 0:F.size,width:"100%"}}))}return P},[g,w,C,a,h,R,v]),A=s.jsx("div",{"aria-hidden":!0,style:{height:O(),width:"100%",zIndex:-1}});return i.createElement(m,{role:"list",...y,className:t,ref:T,style:{position:"relative",maxHeight:"100%",flexGrow:1,overflowY:"auto",...p}},z,e,A)}const qr='"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',Xr=20;function Zr({index:e,style:t,lines:n}){return s.jsx("div",{style:{...t,padding:"0 12px",color:"#a9b1d6",whiteSpace:"pre",overflow:"hidden",boxSizing:"border-box"},children:n[e]})}function It({lines:e,totalSize:t,receivedBytes:n,streaming:r}){const o=i.useRef(null),[,l]=i.useState(0),c=M(y=>y.fontSize),d=Math.round(c*1.5);i.useEffect(()=>{const y=o.current;if(!y)return;const h=new ResizeObserver(()=>l(g=>g+1));return h.observe(y),()=>h.disconnect()},[]);const a=t>0?Math.round(n/t*100):0,u=e.length.toLocaleString(),f=o.current,m=(f==null?void 0:f.clientWidth)||0,p=(f==null?void 0:f.clientHeight)||0;return s.jsxs("div",{ref:o,style:{height:"100%",width:"100%",position:"relative",fontFamily:qr,fontSize:c,lineHeight:`${d}px`},children:[p>0&&s.jsx(Yr,{rowComponent:Zr,rowCount:e.length,rowHeight:d,rowProps:{lines:e},overscanCount:Xr,style:{height:p,width:m}}),s.jsxs("div",{style:{position:"absolute",bottom:6,right:14,fontSize:10,color:"#565f89",background:"rgba(22, 22, 30, 0.85)",padding:"2px 8px",borderRadius:4,pointerEvents:"none",userSelect:"none"},children:[u," lines",r&&` (${a}%)`]})]})}const je={additions:[],deletions:[]};let Qr=0;function Et(){return`ann_${++Qr}_${Date.now()}`}function Ve(e,t){return`plan-annotations-${e}-${t}`}function eo(e){const t=rt.parser([e],{async:!1});return $t.sanitize(t,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function Ge(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++){const o=e[r].raw??"";for(const l of o)l===`
|
|
28
|
-
`&&n++}return n}function jt(e,t){const n=[];return e.additions.length>0&&(n.push("[增加批注]"),e.additions.forEach((r,o)=>{var c;const l=((c=t[r.sourceLine-1])==null?void 0:c.trim().slice(0,50))??"";n.push(`${o+1}. 在第${r.sourceLine}行 ("${l}") 之后添加: "${r.content}"`)})),e.deletions.length>0&&(n.length>0&&n.push(""),n.push("[删除标记]"),e.deletions.forEach((r,o)=>{const l=t.slice(r.startLine-1,r.endLine).join(" ").trim();n.push(`${o+1}. 删除第${r.startLine}-${r.endLine}行: "${l.slice(0,60)}${l.length>60?"...":""}"`)})),n.length===0?"":`请根据以下用户批注修改 PLAN.md:
|
|
29
|
-
|
|
30
|
-
`+n.join(`
|
|
31
|
-
`)}const Rt=i.forwardRef(function({markdown:t,filePath:n,sessionId:r,onExecute:o,onClear:l,expanded:c},d){const a=M(N=>N.fontSize),u=i.useMemo(()=>t?rt.lexer(t):[],[t]),f=i.useMemo(()=>t.split(`
|
|
32
|
-
`),[t]),m=i.useRef(new Set),[p,y]=i.useState(()=>{try{const N=localStorage.getItem(Ve(r,n)),I=N?JSON.parse(N):je,$=new Set;return I.additions.forEach(B=>$.add(B.id)),I.deletions.forEach(B=>$.add(B.id)),m.current=$,I}catch{return je}}),h=i.useRef([]),g=30,k=i.useCallback(()=>{h.current.push(JSON.parse(JSON.stringify(p))),h.current.length>g&&h.current.shift()},[p]),T=i.useRef(void 0);i.useEffect(()=>(T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{localStorage.setItem(Ve(r,n),JSON.stringify(p))},300),()=>{T.current&&clearTimeout(T.current)}),[p,r,n]),i.useEffect(()=>{try{const N=localStorage.getItem(Ve(r,n)),I=N?JSON.parse(N):je;y(I);const $=new Set;I.additions.forEach(B=>$.add(B.id)),I.deletions.forEach(B=>$.add(B.id)),m.current=$,h.current=[]}catch{y(je),m.current=new Set}},[r,n]);const[C,S]=i.useState(null),[w,O]=i.useState(""),D=i.useRef(null),[R,j]=i.useState(null),[v,x]=i.useState(""),z=i.useRef(null),[A,P]=i.useState(null),L=i.useRef(null);i.useEffect(()=>{C!=null&&requestAnimationFrame(()=>{var N;return(N=D.current)==null?void 0:N.focus()})},[C]);const F=i.useCallback(N=>{if(!w.trim()){S(null),O("");return}k();const I=Ge(u,N+1);y($=>({...$,additions:[...$.additions,{id:Et(),afterTokenIndex:N,sourceLine:I,content:w.trim()}]})),S(null),O("")},[w,k,u]),H=i.useCallback(N=>{k(),y(I=>({...I,additions:I.additions.filter($=>$.id!==N)}))},[k]),G=i.useCallback((N,I)=>{k(),y($=>({...$,additions:$.additions.map(B=>B.id===N?{...B,content:I}:B)}))},[k]),J=i.useCallback(()=>{var N;A&&(k(),y(I=>({...I,deletions:[...I.deletions,{id:Et(),tokenIndices:A.tokenIndices,startLine:A.startLine,endLine:A.endLine,selectedText:A.text.slice(0,80)}]})),P(null),(N=window.getSelection())==null||N.removeAllRanges())},[A,k]),V=i.useCallback(N=>{k(),y(I=>({...I,deletions:I.deletions.filter($=>$.id!==N)}))},[k]),Y=i.useCallback((N,I)=>{k(),y($=>({...$,deletions:$.deletions.map(B=>B.id===N?{...B,selectedText:I}:B)}))},[k]),me=i.useCallback(N=>{let I=N instanceof Element?N:N.parentElement;for(;I&&I!==L.current;){if(I.hasAttribute("data-token-index"))return I;I=I.parentElement}return null},[]),he=i.useCallback(()=>{const N=window.getSelection();if(!N||N.isCollapsed||!L.current){P(null);return}const I=N.toString().trim();if(!I){P(null);return}const $=N.getRangeAt(0);if(!L.current.contains($.commonAncestorContainer)){P(null);return}const B=me($.startContainer),W=me($.endContainer);if(!B||!W){P(null);return}const ne=parseInt(B.getAttribute("data-token-index")||"0",10),_=parseInt(W.getAttribute("data-token-index")||"0",10),K=[];for(let U=Math.min(ne,_);U<=Math.max(ne,_);U++)K.push(U);const X=Ge(u,Math.min(ne,_)),Z=Ge(u,Math.max(ne,_)+1),ve=$.getBoundingClientRect(),b=L.current,E=b.getBoundingClientRect();navigator.clipboard.writeText(I).catch(()=>{}),P({x:ve.right-E.left+b.scrollLeft+6,y:ve.top-E.top+b.scrollTop-2,tokenIndices:K,startLine:X,endLine:Z,text:I})},[u,me]),ee=i.useRef(void 0);i.useEffect(()=>{const N=()=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{const I=window.getSelection();if(!I||I.isCollapsed||!L.current){P(null);return}const $=I.anchorNode;$&&L.current.contains($)&&he()},120)};return document.addEventListener("selectionchange",N),()=>{document.removeEventListener("selectionchange",N),ee.current&&clearTimeout(ee.current)}},[he]),Xt(L,u),i.useEffect(()=>{const N=I=>{var $;if((I.ctrlKey||I.metaKey)&&I.key==="z"&&!I.shiftKey){if((($=document.activeElement)==null?void 0:$.tagName)==="TEXTAREA")return;const B=h.current.pop();B&&(I.preventDefault(),y(B))}};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[]);const de=i.useCallback(()=>({additions:p.additions.filter(N=>!m.current.has(N.id)),deletions:p.deletions.filter(N=>!m.current.has(N.id))}),[p]),xe=i.useCallback(()=>{const N=jt(de(),f);if(N){o(N);const I=new Set;p.additions.forEach($=>I.add($.id)),p.deletions.forEach($=>I.add($.id)),m.current=I}},[de,p,f,o]);i.useImperativeHandle(d,()=>({getSummary:()=>jt(de(),f)}),[de,f]);const ue=i.useCallback(()=>{k(),y(je),l==null||l()},[k,l]),ye=i.useMemo(()=>{const N=new Set;return p.deletions.forEach(I=>I.tokenIndices.forEach($=>N.add($))),N},[p.deletions]),ae=i.useMemo(()=>{const N=new Map;return p.additions.forEach(I=>{const $=N.get(I.afterTokenIndex)||[];$.push(I),N.set(I.afterTokenIndex,$)}),N},[p.additions]),fe=p.additions.length>0||p.deletions.length>0;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("button",{className:"pane-btn",onClick:xe,disabled:!fe,title:"Save annotations to editor",style:fe?{color:"#9ece6a"}:{opacity:.4},children:"Save"}),s.jsx("button",{className:"pane-btn",onClick:ue,disabled:!fe,title:"Clear all annotations",style:fe?{}:{opacity:.4},children:"Clear"}),fe&&s.jsxs("span",{style:{fontSize:10,color:"#565f89",marginLeft:4},children:["+",p.additions.length," −",p.deletions.length]})]}),s.jsxs("div",{ref:L,className:"plan-anno-content md-preview",style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${a}px`},onMouseUp:he,children:[s.jsx(zt,{index:-1,active:C===-1,additions:ae.get(-1),onOpen:()=>{S(-1),O("")},onSubmit:()=>F(-1),onRemoveAddition:H,onEditAddition:G,insertText:w,setInsertText:O,textareaRef:C===-1?D:void 0,expanded:c,alwaysShow:u.length===0,fontSize:a}),u.map((N,I)=>{const $=eo(N);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":I,className:ye.has(I)?"plan-block--deleted":void 0,dangerouslySetInnerHTML:{__html:$}}),p.deletions.filter(B=>B.tokenIndices.includes(I)&&B.tokenIndices[0]===I).map(B=>s.jsx("div",{className:"plan-deletion-card",children:R===B.id?s.jsx("textarea",{ref:z,className:"plan-annotation-textarea",value:v,onChange:W=>x(W.target.value),onKeyDown:W=>{if(W.key==="Enter"&&(W.ctrlKey||W.metaKey)){W.preventDefault();const ne=v.trim();ne?Y(B.id,ne):V(B.id),j(null)}W.key==="Escape"&&(W.preventDefault(),j(null))},onBlur:()=>{const W=v.trim();W?Y(B.id,W):V(B.id),j(null)},rows:et(v),style:{fontSize:`${a}px`,flex:1}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${a}px`,color:"#f7768e",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{j(B.id),x(B.selectedText),requestAnimationFrame(()=>{const W=z.current;W&&(W.focus(),W.selectionStart=W.selectionEnd=W.value.length)})},title:"Double-click to edit",children:B.selectedText}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{j(B.id),x(B.selectedText),requestAnimationFrame(()=>{const W=z.current;W&&(W.focus(),W.selectionStart=W.selectionEnd=W.value.length)})},style:{color:"#7aa2f7"},title:"Edit deletion annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>V(B.id),title:"Remove deletion",children:"×"})]})},B.id)),s.jsx(zt,{index:I,active:C===I,additions:ae.get(I),onOpen:()=>{S(I),O("")},onSubmit:()=>F(I),onRemoveAddition:H,onEditAddition:G,insertText:w,setInsertText:O,textareaRef:C===I?D:void 0,expanded:c,fontSize:a})]},I)}),A&&s.jsx("button",{className:"plan-delete-float",style:{top:A.y,left:A.x},onMouseDown:N=>{N.preventDefault(),J()},children:"−"})]})]})});function zt({index:e,active:t,additions:n,onOpen:r,onSubmit:o,onRemoveAddition:l,onEditAddition:c,insertText:d,setInsertText:a,textareaRef:u,expanded:f,alwaysShow:m,fontSize:p=14}){const[y,h]=i.useState(null),[g,k]=i.useState(""),T=i.useRef(null),C=Xe(),S=Xe();i.useEffect(()=>{y&&(C.clearUndo(),requestAnimationFrame(()=>{const v=T.current;v&&(v.focus(),v.selectionStart=v.selectionEnd=v.value.length)}))},[y]),i.useEffect(()=>{t&&S.clearUndo()},[t]);const w=i.useCallback(v=>{k(x=>(C.pushUndo(x),v))},[C]),O=i.useCallback(v=>{S.pushUndo(d),a(v)},[d,a,S]),D=i.useCallback(v=>{h(v.id),k(v.content)},[]),R=i.useCallback(()=>{if(!y)return;const v=g.trim();v?c(y,v):l(y),h(null),k("")},[y,g,c,l]),j=i.useCallback(()=>{h(null),k("")},[]);return s.jsxs("div",{className:`plan-insert-zone${m?" plan-insert-zone--empty":""}`,"data-zone-index":e,children:[n==null?void 0:n.map(v=>s.jsx("div",{className:"plan-annotation-card",children:y===v.id?s.jsx("textarea",{ref:T,className:"plan-annotation-textarea",value:g,onChange:x=>w(x.target.value),onKeyDown:x=>{if(x.key==="Enter"&&(x.ctrlKey||x.metaKey)){x.preventDefault(),R();return}if(x.key==="Escape"){x.preventDefault(),j();return}if(x.key==="Tab"){Ze(x,w);return}if(x.key==="z"&&(x.ctrlKey||x.metaKey)&&!x.shiftKey){Qe(x,C.popUndo,k);return}},onBlur:R,rows:et(g),style:{fontSize:`${p}px`,flex:1,...f?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${p}px`,color:"#e0af68",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>D(v),title:"Double-click to edit",children:v.content}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>D(v),style:{color:"#7aa2f7"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(v.id),children:"×"})]})},v.id)),t?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:d,onChange:v=>O(v.target.value),onKeyDown:v=>{if(v.key==="Enter"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),o();return}if(v.key==="Escape"){v.preventDefault(),o();return}if(v.key==="Tab"){Ze(v,O);return}if(v.key==="z"&&(v.ctrlKey||v.metaKey)&&!v.shiftKey){Qe(v,S.popUndo,a);return}},placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:et(d),style:{fontSize:`${p}px`,...f?{minWidth:300}:void 0}})}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}const Je={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},to=200;function no(){const[e,t]=i.useState(Je),n=i.useRef("lines"),r=i.useRef([]),o=i.useRef(""),l=i.useRef(""),c=i.useRef([]),d=i.useRef(0),a=i.useRef(0),u=i.useRef(null),f=i.useRef(null),m=i.useCallback(()=>{const T=n.current;t(C=>({...C,receivedBytes:d.current,...T==="lines"?{lines:[...r.current]}:{},...T==="content"?{content:l.current}:{}}))},[]),p=i.useCallback(()=>{u.current===null&&(u.current=window.setTimeout(()=>{u.current=null,m()},to))},[m]),y=i.useCallback(T=>{n.current=T,r.current=[],o.current="",l.current="",c.current=[],d.current=0,a.current=0,f.current=new TextDecoder,u.current!==null&&(clearTimeout(u.current),u.current=null),t({...Je,mode:T,status:"streaming"})},[]),h=i.useCallback(T=>{d.current+=T.length;const C=n.current;if(C==="lines"){const w=f.current.decode(T,{stream:!0}).split(`
|
|
33
|
-
`);w[0]=o.current+w[0],o.current=w.pop(),w.length>0&&r.current.push(...w)}else if(C==="content"){const S=f.current.decode(T,{stream:!0});l.current+=S}else c.current.push(new Uint8Array(T));p()},[p]),g=i.useCallback(T=>{switch(T.type){case"file-stream-start":a.current=T.size,t(C=>({...C,totalSize:T.size,mtime:T.mtime}));break;case"file-stream-end":{u.current!==null&&(clearTimeout(u.current),u.current=null);const C=n.current;let S=r.current,w=l.current,O=null;if(C==="lines"){const D=f.current.decode(),R=o.current+D;R&&(S=[...S,R],r.current=S),o.current=""}else if(C==="content"){const D=f.current.decode();w=l.current+D,l.current=w}else{const D=c.current.reduce((j,v)=>j+v.length,0);O=new Uint8Array(D);let R=0;for(const j of c.current)O.set(j,R),R+=j.length;c.current=[]}t({status:"complete",mode:C,lines:C==="lines"?[...S]:[],content:C==="content"?w:"",buffer:C==="binary"?O:null,totalSize:a.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":u.current!==null&&(clearTimeout(u.current),u.current=null),t(C=>({...C,status:"error",error:T.error}));break}},[]),k=i.useCallback(()=>{u.current!==null&&(clearTimeout(u.current),u.current=null),r.current=[],o.current="",l.current="",c.current=[],d.current=0,a.current=0,f.current=null,t(Je)},[]);return{state:e,startStream:y,handleChunk:h,handleControl:g,reset:k}}function ro(e=50,t=20,n=80){const[r,o]=i.useState(e),l=i.useRef(null),c=i.useCallback(d=>{d.preventDefault();const a=l.current;if(!a)return;const u=a.getBoundingClientRect(),f=u.width;document.body.classList.add("resizing-panes-h");let m=null;const p=h=>{m||(m=requestAnimationFrame(()=>{m=null;const g=h.clientX-u.left,k=Math.min(n,Math.max(t,g/f*100));o(k)}))},y=()=>{m&&cancelAnimationFrame(m),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",y)};document.addEventListener("mousemove",p),document.addEventListener("mouseup",y)},[t,n]);return{leftWidthPercent:r,containerRef:l,onDividerMouseDown:c}}function oo(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":"text"}function Nt(e){return e.split("/").pop()||e}const so=3e3;function Ye({label:e,percent:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"#565f89",fontSize:13},children:e}),t!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"#292e42",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${t}%`,backgroundColor:"#7aa2f7",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"#565f89",whiteSpace:"nowrap"},children:[t,"%"]})]})]})}function Lt({sessionId:e,onSelect:t}){const n=i.useCallback(()=>{},[]),{cwd:r,files:o,loading:l,error:c,handleNavigate:d,handleGoUp:a,handleRefresh:u}=ot({sessionId:e,onClose:n,pollCwd:so});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(it,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(at,{loading:l,error:c,empty:o.length===0,emptyText:"No files found"}),!l&&!c&&o.map(f=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent"},onClick:()=>{f.type==="directory"?d(f.name):t(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Yt(f.name,f.type)}),s.jsx("span",{style:{flex:1,color:f.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:f.name}),f.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:st(f.size)})]},f.name))]})]})}function io({sessionId:e,token:t,connected:n,onClose:r,onSend:o,onRequestFileStream:l,planMode:c,onPlanModeClose:d}){const[a,u]=i.useState(null),[f,m]=i.useState(null),p=no(),[y,h]=i.useState(!1),[g,k]=i.useState(!1),[T,C]=i.useState(!1),{leftWidthPercent:S,containerRef:w,onDividerMouseDown:O}=ro(50),D=i.useRef(null),R=i.useRef(null),[j,v]=i.useState(!1),x=i.useRef("doc"),[z,A]=i.useState(null),[P,L]=i.useState(""),[F,H]=i.useState(!1),[G,J]=i.useState(!1);i.useEffect(()=>{if(!c){V.current=null;return}let _=!1;return H(!0),(async()=>{try{const K=await Te(t,e);if(_)return;if(K.files.find(Z=>Z.name==="PLAN.md")){const Z=K.cwd+"/PLAN.md";A(Z),L("")}else{try{const Z=await vr(t,e,"PLAN.md");if(_)return;if(Z.ok&&Z.path){A(Z.path),L(""),H(!1);return}}catch{}A(null),L("")}}catch{A(null)}finally{_||H(!1)}})(),()=>{_=!0}},[c,e,t]);const V=i.useRef(null);i.useEffect(()=>{!c||!z||!n||V.current===z&&P||(V.current=z,x.current="plan",p.reset(),p.startStream("content"),l==null||l(z))},[c,z,n]),i.useEffect(()=>{c&&p.state.status==="complete"&&z&&x.current==="plan"&&L(p.state.content)},[c,p.state.status,p.state.content,z]);const Y=i.useRef(null),me=i.useCallback(_=>{Y.current=_,d==null||d()},[d]);i.useEffect(()=>{!c&&Y.current&&D.current&&(D.current.fillContent(Y.current),Y.current=null)},[c]);const he=i.useCallback(()=>{!z||!n||(V.current=null,x.current="plan",L(""),p.reset(),p.startStream("content"),l==null||l(z),V.current=z)},[z,n,p,l]),ee=i.useRef(new Map),de=i.useRef(null),xe=i.useRef(null);i.useEffect(()=>(Qn(e,p.handleChunk,p.handleControl),()=>er(e)),[e,p.handleChunk,p.handleControl]);const ue=i.useCallback(()=>{if(!a)return;const _=g?xe.current:de.current;_&&ee.current.set(a,_.scrollTop)},[a,g]),ye=i.useCallback(_=>{const K=ee.current.get(_);K!=null&&requestAnimationFrame(()=>{const X=g?xe.current:de.current;X&&(X.scrollTop=K)})},[g]),ae=i.useCallback((_,K)=>{ue();const X=oo(_);u(_),m(X),h(!1),x.current="doc",p.reset();const Z=X==="text"?"lines":X==="pdf"?"binary":"content";p.startStream(Z),l==null||l(_)},[ue,p,l]),fe=i.useCallback(()=>{if(!a||!f)return;x.current="doc",p.reset();const _=f==="text"?"lines":f==="pdf"?"binary":"content";p.startStream(_),l==null||l(a)},[a,f,p,l]),N=i.useCallback(()=>{a&&navigator.clipboard.writeText(a).then(()=>{C(!0),setTimeout(()=>C(!1),1500)}).catch(()=>{})},[a]);i.useEffect(()=>{if(!g&&!G)return;const _=K=>{if(K.key==="Escape"){if(G){J(!1);return}ue(),k(!1)}};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[g,G,ue]),i.useEffect(()=>{a&&p.state.status==="complete"&&ye(a)},[g,a,ye,p.state.status]);const{totalSize:I,receivedBytes:$}=p.state,B=I>0?Math.round($/I*100):0,W=i.useCallback(()=>{const _=window.getSelection(),K=_==null?void 0:_.toString();K&&navigator.clipboard.writeText(K).catch(()=>{})},[]),ne=_=>{if(!a)return s.jsx(Lt,{sessionId:e,onSelect:ae});const{status:K,lines:X,content:Z,buffer:ve}=p.state;if(K==="error")return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#f7768e",fontSize:"13px",padding:"12px",textAlign:"center"},children:p.state.error||"Stream error"});if(K==="streaming")return f==="text"?s.jsx(It,{lines:X,totalSize:I,receivedBytes:$,streaming:!0}):s.jsx(Ye,{label:"Loading...",percent:B});if(K==="complete"){if(f==="text")return s.jsx(It,{lines:X,totalSize:I,receivedBytes:$,streaming:!1});if(f==="md")return s.jsx("div",{ref:_,style:{height:"100%",overflow:"auto"},children:s.jsx(Er,{content:Z})});if(f==="html")return s.jsx("div",{ref:_,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:Z,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})});if(f==="pdf"&&ve)return s.jsx($r,{data:ve,scrollRef:_})}return K==="idle"?s.jsx(Lt,{sessionId:e,onSelect:ae}):null};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",height:"30px",flexShrink:0,backgroundColor:"#16161e",borderBottom:"1px solid #292e42"},children:[s.jsxs("div",{style:{width:`${S}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>h(_=>!_),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),a&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:N,title:T?"Copied!":`Click to copy: ${a}`,children:T?"Copied!":Nt(a)}),s.jsx("button",{className:"pane-btn",onClick:()=>{ue(),k(!0)},title:"Expand document view",children:"⛶"}),s.jsx("button",{className:"pane-btn",onClick:fe,title:"Refresh document",children:"↻"})]})]}),s.jsx("div",{style:{width:"4px",flexShrink:0}}),s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",minWidth:0},children:c?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"#bb9af7",fontWeight:600},children:"Plan"}),z&&s.jsx("span",{style:{fontSize:"10px",color:"#565f89"},children:z.split("/").pop()})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("button",{className:"pane-btn",onClick:he,title:"Refresh PLAN.md",children:"↻"}),s.jsx("button",{className:"pane-btn",onClick:()=>J(!0),title:"Expand plan view",children:"⛶"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{var K;const _=(K=R.current)==null?void 0:K.getSummary();_&&(Y.current=_),d==null||d()},title:"Close Plan mode",children:"×Plan"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=D.current)==null?void 0:_.send()},disabled:!j,title:"Send to terminal (Ctrl+Enter)",style:j?{color:"#9ece6a"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"10px",color:"#414868"},children:"Ctrl+Enter"})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:r,title:"Close Doc panel",children:"×"})]})})]}),s.jsxs("div",{ref:w,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${S}%`,flexShrink:0},onMouseUp:W,children:[ne(_=>{de.current=_}),y&&s.jsx(Lr,{sessionId:e,onSelect:ae,onClose:()=>h(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:O}),s.jsx("div",{className:"plan-editor-wrap",children:c?F?s.jsx(Ye,{label:"Loading PLAN.md..."}):z&&!P&&(p.state.status==="streaming"||p.state.status==="idle")?s.jsx(Ye,{label:"Loading PLAN.md...",percent:p.state.totalSize>0?Math.round(p.state.receivedBytes/p.state.totalSize*100):void 0}):z&&!G?s.jsx(Rt,{ref:R,markdown:P,filePath:z,sessionId:e,onExecute:me}):z&&G?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:12},children:"Editing in expanded view"}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"#565f89",fontSize:13,fontStyle:"italic"},children:"No PLAN.md found in CWD"}),s.jsx("button",{className:"pane-btn",onClick:()=>h(!0),style:{color:"#7aa2f7"},children:"Select file"})]}):s.jsx(Nr,{ref:D,onSend:o,onContentChange:v,sessionId:e,token:t})})]}),g&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsx("span",{style:{fontSize:"14px",color:"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a?Nt(a):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{ue(),k(!1)},title:"Close expanded view (ESC)",style:{fontSize:"14px"},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},onMouseUp:W,children:ne(_=>{xe.current=_})})]}),G&&z&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsxs("span",{style:{fontSize:"14px",color:"#bb9af7"},children:["Plan: ",z.split("/").pop()]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>J(!1),title:"Close expanded view (ESC)",style:{fontSize:"14px"},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(Rt,{ref:R,markdown:P,filePath:z,sessionId:e,onExecute:me,expanded:!0})})]})]})}const ao=100,lo=600,Ce=typeof window<"u"?window.matchMedia(`(max-width: ${lo-1}px)`):null;function co(){const[e,t]=i.useState(()=>(Ce==null?void 0:Ce.matches)??!1);return i.useEffect(()=>{if(!Ce)return;const n=r=>t(r.matches);return Ce.addEventListener("change",n),()=>Ce.removeEventListener("change",n)},[]),e}const uo=i.memo(function({terminal:t}){const n=co(),r=M(R=>R.splitTerminal),o=M(R=>R.token),l=M(R=>R.setTerminalPanelMode),c=i.useRef(null),d=i.useRef(null),[a,u]=i.useState(!1),[f,m]=i.useState(!1),[p,y]=i.useState(0),[h,g]=i.useState(50),k=t.panelMode!=="none",T=t.panelMode==="plan",C=i.useRef(null),S=async R=>{const j=R.target.files;if(!(!j||j.length===0||!o)){m(!0),y(0);try{await br(o,t.id,j,v=>{y(v)})}catch(v){alert(`Upload failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{m(!1),y(0),c.current&&(c.current.value="")}}},w=i.useRef(void 0),O=i.useCallback(R=>{if(d.current){const j=R.replace(/\r?\n/g," ").trimEnd();d.current.sendInput(j),w.current=window.setTimeout(()=>{var v;return(v=d.current)==null?void 0:v.sendInput("\r")},50)}},[]);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const D=i.useCallback(R=>{R.preventDefault();const j=C.current;if(!j)return;const v=j.getBoundingClientRect(),x=v.height;document.body.classList.add("resizing-panes-v");const z=P=>{const L=(P.clientY-v.top)/x*100,F=Math.min(80,Math.max(20,L));g(100-F)},A=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",A)};document.addEventListener("mousemove",z),document.addEventListener("mouseup",A)},[]);return s.jsxs("div",{ref:C,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:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0,height:"28px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{display:"inline-block",width:"7px",height:"7px",borderRadius:"50%",backgroundColor:t.connected?"#9ece6a":"#f7768e",boxShadow:t.connected?"0 0 4px rgba(158,206,106,0.5)":"0 0 4px rgba(247,118,142,0.5)"}}),s.jsxs("span",{style:{fontSize:"14px",color:"#565f89"},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:c,type:"file",multiple:!0,style:{display:"none"},onChange:S}),s.jsx("button",{className:"pane-btn",onClick:()=>{var R;return(R=c.current)==null?void 0:R.click()},disabled:f,style:f?{color:"#e0af68"}:void 0,title:f?`Uploading ${p}%`:"Upload files","aria-label":"Upload files",children:f?`${p}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>u(R=>!R),style:a?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${t.panelMode==="chat"?" pane-btn--active":""}`,onClick:()=>l(t.id,t.panelMode==="chat"?"none":"chat"),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${t.panelMode==="plan"?" pane-btn--active":""}`,onClick:()=>l(t.id,t.panelMode==="plan"?"none":"plan"),title:"Toggle Plan annotation mode","aria-label":"Toggle Plan annotation mode",children:"Plan"}),s.jsx("button",{className:"pane-btn",onClick:()=>r(t.id,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:()=>r(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(xr,{ref:d,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(26, 27, 38, 0.85)",zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"#565f89",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})}),a&&s.jsx(Sr,{sessionId:t.id,onClose:()=>u(!1)})]}),k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:D}),s.jsx("div",{style:{height:`${h}%`,minHeight:ao,flexShrink:0,overflow:"hidden"},children:s.jsx(io,{onSend:O,onClose:()=>l(t.id,"none"),sessionId:t.id,token:o||"",connected:t.connected,onRequestFileStream:R=>{var j;return(j=d.current)==null?void 0:j.requestFileStream(R)},onCancelFileStream:()=>{var R;return(R=d.current)==null?void 0:R.cancelFileStream()},planMode:T,onPlanModeClose:()=>l(t.id,"chat")})})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:t.error})]})});class en extends i.Component{constructor(){super(...arguments);ct(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:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"#c0caf5",fontFamily:"monospace",padding:"16px"},children:[s.jsx("div",{style:{fontSize:"14px",color:"#f7768e"},children:"Pane crashed"}),s.jsx("div",{style:{fontSize:"12px",color:"#565f89",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:"#292e42",border:"1px solid #414868",color:"#c0caf5",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):s.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"#c0caf5",fontFamily:"monospace"},children:[s.jsx("div",{style:{fontSize:"18px",color:"#f7768e"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"#565f89",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, #7aa2f7 0%, #bb9af7 100%)",border:"none",color:"#1a1b26",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const fo=4,Mt=10;function po(){const e=M(o=>o.layout),t=M(o=>o.terminalIds.length),n=M(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#1a1b26"},children:s.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed #292e42",color:"#565f89",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(tn,{node:e,canClose:r})})}const tn=i.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(mo,{terminalId:t.terminalId,canClose:n}):s.jsx(ho,{node:t,canClose:n})}),mo=i.memo(function({terminalId:t,canClose:n}){const r=M(o=>o.terminalsMap[t]);return r?s.jsx(en,{inline:!0,children:s.jsx(uo,{terminal:r,canClose:n})}):null}),ho=i.memo(function({node:t,canClose:n}){const r=M(u=>u.setSplitSizes),o=i.useRef(null),l=t.direction==="horizontal",c=i.useRef(t.sizes);c.current=t.sizes;const d=i.useCallback((u,f)=>{f.preventDefault();const m=l?"resizing-panes":"resizing-panes-v";document.body.classList.add(m);const p=l?f.clientX:f.clientY,y=[...c.current],h=o.current,g=l?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let k=null;const T=S=>{k||(k=requestAnimationFrame(()=>{k=null;const D=((l?S.clientX:S.clientY)-p)/g*100,R=y[u]+D,j=y[u+1]-D;if(R>=Mt&&j>=Mt){const v=[...y];v[u]=R,v[u+1]=j,r(t.id,v)}}))},C=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(m),document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",C)};document.addEventListener("mousemove",T),document.addEventListener("mouseup",C)},[l,t.id,r]),a=[];return t.children.forEach((u,f)=>{const m=u.type==="leaf"?u.terminalId:u.id;a.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(tn,{node:u,canClose:n})},m)),f<t.children.length-1&&a.push(s.jsx("div",{onMouseDown:p=>d(f,p),style:{flex:`0 0 ${fo}px`,cursor:l?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:l?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:a})});function xo({tabId:e}){const t=M(x=>x.tabs.find(z=>z.id===e)),n=M(x=>x.activeTabId),r=M(x=>x.switchTab),o=M(x=>x.closeTab),l=M(x=>x.reopenTab),c=M(x=>x.deleteTab),d=M(x=>x.renameTab),a=M(x=>t?t.terminalIds.map(z=>{const A=x.terminalsMap[z];return A?{id:z,connected:A.connected}:{id:z,connected:!1}}):[]),u=M(x=>x.killServerSession),[f,m]=i.useState(!1),[p,y]=i.useState(""),[h,g]=i.useState(!1),k=i.useRef(null);if(!t)return null;const T=n===e,C=t.status==="open",S=()=>{C&&r(e)},w=x=>{C&&(x.stopPropagation(),y(t.name),m(!0),setTimeout(()=>{var z;return(z=k.current)==null?void 0:z.focus()},0))},O=()=>{const x=p.trim();x&&d(e,x),m(!1)},D=x=>{x.stopPropagation(),l(e)},R=x=>{x.stopPropagation(),o(e)},j=async x=>{x.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},v=x=>{x.stopPropagation(),g(!h)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:S,style:{padding:"8px 12px",cursor:C?"pointer":"default",borderLeft:T?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:T?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s",opacity:C?1:.5},onMouseEnter:x=>{C&&!T&&(x.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:x=>{T||(x.currentTarget.style.backgroundColor="transparent")},children:[C&&t.terminalIds.length>0&&s.jsx("button",{onClick:v,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:h?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[f?s.jsx("input",{ref:k,value:p,onChange:x=>y(x.target.value),onBlur:O,onKeyDown:x=>{x.key==="Enter"&&O(),x.key==="Escape"&&m(!1)},style:{width:"100%",background:"#1a1b26",border:"1px solid #7aa2f7",color:"#c0caf5",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):s.jsx("div",{onDoubleClick:w,style:{color:"#c0caf5",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",qt(Math.floor(t.createdAt/1e3))]})]}),C?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:R,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:D,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:j,title:"Delete tab",children:"×"})]})]}),C&&h&&a.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:a.map(x=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)",display:"flex",alignItems:"center"},title:`Connected: ${x.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:x.id}),s.jsx("span",{style:{marginLeft:"8px",color:x.connected?"#9ece6a":"#f7768e"},children:x.connected?"●":"○"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:z=>{z.stopPropagation(),window.confirm(`Close terminal "${x.id}"?`)&&u(x.id)},style:{marginLeft:"auto",flexShrink:0},title:"Close terminal",children:"×"})]},x.id))})]})}function yo({sessionId:e,active:t,createdAt:n}){const r=M(d=>d.addTerminal),o=M(d=>d.killServerSession),l=()=>{r("horizontal",e)},c=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};return s.jsxs("div",{onClick:l,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:qt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function bo(){const e=M(a=>a.sidebarOpen),t=M(a=>a.toggleSidebar),n=M(a=>a.fetchSessions),r=M(a=>e?a.serverSessions:[]),o=M(a=>e?a.tabs:[]),l=M(a=>a.terminalIds.length),c=new Set(o.flatMap(a=>a.terminalIds)),d=r.filter(a=>!c.has(a.sessionId));return i.useEffect(()=>{if(!e)return;n();let a=setInterval(n,5e3);const u=()=>{document.hidden?a&&(clearInterval(a),a=null):(n(),a||(a=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",u),()=>{a&&clearInterval(a),document.removeEventListener("visibilitychange",u)}},[e,n]),i.useEffect(()=>{if(!e)return;const a=setTimeout(n,800);return()=>clearTimeout(a)},[l,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:e?"1px solid #292e42":"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 #292e42",flexShrink:0},children:[s.jsx("span",{style:{color:"#7aa2f7",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Sessions"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#565f89",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:"#7aa2f7",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid #292e42"},children:"TABS"}),o.length===0?s.jsx("div",{style:{color:"#565f89",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(a=>s.jsx(xo,{tabId:a.id},a.id))]}),d.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.jsx("div",{style:{padding:"8px 12px",color:"#e0af68",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid #292e42"},children:"ORPHANED SESSIONS"}),d.map(a=>s.jsx(yo,{sessionId:a.sessionId,active:a.active,createdAt:a.createdAt},a.sessionId))]})]})]})}const nn=nt.memo(()=>{const e=M(w=>w.tabs),t=M(w=>w.activeTabId),n=M(w=>w.addTab),r=M(w=>w.switchTab),o=M(w=>w.closeTab),l=M(w=>w.renameTab),[c,d]=i.useState(null),[a,u]=i.useState(""),f=i.useRef(null),m=e.filter(w=>w.status==="open");i.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const p=w=>{d(w.id),u(w.name)},y=()=>{c&&a.trim()&&l(c,a.trim()),d(null),u("")},h=()=>{d(null),u("")},g=w=>{w.key==="Enter"?y():w.key==="Escape"&&h()},k=w=>{c||r(w)},T=(w,O)=>{w.stopPropagation(),o(O)},C=(w,O)=>{w.button===1&&(w.preventDefault(),o(O))},S=m.length>1;return s.jsxs("div",{className:"tab-bar",children:[m.map(w=>{const O=w.id===t,D=c===w.id,R=w.terminalIds.length;return s.jsx("div",{className:`tab-item ${O?"tab-item--active":""}`,onClick:()=>k(w.id),onDoubleClick:()=>p(w),onMouseDown:j=>C(j,w.id),children:D?s.jsx("input",{ref:f,type:"text",value:a,onChange:j=>u(j.target.value),onBlur:y,onKeyDown:g,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[w.name," ",R>0&&`(${R})`]}),S&&s.jsx("button",{className:"tab-item__close",onClick:j=>T(j,w.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},w.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});nn.displayName="TabBar";function go(){return localStorage.getItem("ai-cli-online-token")}function vo(){const e=M(a=>a.token),t=M(a=>a.setToken),n=M(a=>a.tabs),r=M(a=>a.addTab),o=M(a=>a.toggleSidebar),l=M(a=>a.fontSize),c=M(a=>a.setFontSize),d=M(a=>a.tabsLoading);return i.useEffect(()=>{const a=go();a&&!e&&t(a)},[]),i.useEffect(()=>{e&&!d&&n.filter(a=>a.status==="open").length===0&&r("Default")},[e,d]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"#1a1b26"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"#7aa2f7",letterSpacing:"0.5px"},children:"AI-Cli Online"})}),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:()=>c(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:"#a9b1d6",minWidth:"20px",textAlign:"center"},children:l}),s.jsx("button",{className:"header-btn",onClick:()=>c(l+1),disabled:l>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(So,{}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Sessions Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(po,{})}),s.jsx(bo,{})]}),s.jsx(nn,{})]}):s.jsx(Zn,{})}const wo=[1,2,3,4];function So(){const e=M(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="#9ece6a",n=4):e<150?(t="#e0af68",n=3):e<300?(t="#ff9e64",n=2):(t="#f7768e",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[wo.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}qe.createRoot(document.getElementById("root")).render(s.jsx(nt.StrictMode,{children:s.jsx(en,{children:s.jsx(vo,{})})}));
|