ai-cli-online 2.2.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/install-service.sh +25 -10
- package/package.json +1 -1
- package/server/dist/index.js +2 -0
- package/server/dist/tmux.js +3 -2
- package/server/dist/websocket.js +1 -1
- package/server/package.json +1 -1
- package/shared/package.json +1 -1
- package/web/dist/assets/index-UW3BpUWL.js +38 -0
- package/web/dist/index.html +1 -2
- package/web/package.json +1 -1
- package/web/dist/assets/index-DpLQJExV.js +0 -38
package/install-service.sh
CHANGED
|
@@ -216,17 +216,29 @@ ${NGINX_SSL_BLOCK}
|
|
|
216
216
|
# 文件上传大小限制 (与 multer 100MB 限制匹配)
|
|
217
217
|
client_max_body_size 100m;
|
|
218
218
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
219
|
+
# Static files served directly by nginx (fonts, JS, CSS, images)
|
|
220
|
+
# Avoids proxy buffering issues with large files like 5MB+ fonts
|
|
221
|
+
location /assets/ {
|
|
222
|
+
alias ${PROJECT_DIR}/web/dist/assets/;
|
|
223
|
+
expires 30d;
|
|
224
|
+
add_header Cache-Control "public, immutable";
|
|
225
|
+
gzip_static on;
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
-
location /
|
|
229
|
-
|
|
228
|
+
location /fonts/ {
|
|
229
|
+
alias ${PROJECT_DIR}/web/dist/fonts/;
|
|
230
|
+
expires 30d;
|
|
231
|
+
add_header Cache-Control "public, immutable";
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
location /favicon.svg {
|
|
235
|
+
alias ${PROJECT_DIR}/web/dist/favicon.svg;
|
|
236
|
+
expires 30d;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
# API, WebSocket, and HTML via Node.js proxy
|
|
240
|
+
location / {
|
|
241
|
+
proxy_pass http://127.0.0.1:${BACKEND_PORT};
|
|
230
242
|
proxy_http_version 1.1;
|
|
231
243
|
proxy_set_header Upgrade \$http_upgrade;
|
|
232
244
|
proxy_set_header Connection "upgrade";
|
|
@@ -235,13 +247,16 @@ ${NGINX_SSL_BLOCK}
|
|
|
235
247
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
|
236
248
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
|
237
249
|
proxy_read_timeout 86400s;
|
|
238
|
-
proxy_send_timeout 86400s;
|
|
239
250
|
}
|
|
240
251
|
}
|
|
241
252
|
NGINX_EOF
|
|
242
253
|
|
|
243
254
|
echo "[nginx] 已写入 $NGINX_CONF"
|
|
244
255
|
|
|
256
|
+
# Ensure nginx worker (www-data) can traverse user home directory for static files
|
|
257
|
+
chmod o+x "$RUN_HOME"
|
|
258
|
+
echo "[nginx] 已设置 $RUN_HOME 可遍历权限 (chmod o+x)"
|
|
259
|
+
|
|
245
260
|
# 启用站点 (symlink to sites-enabled)
|
|
246
261
|
NGINX_ENABLED="/etc/nginx/sites-enabled/${SERVICE_NAME}"
|
|
247
262
|
if [[ -L "$NGINX_ENABLED" ]]; then
|
package/package.json
CHANGED
package/server/dist/index.js
CHANGED
|
@@ -462,6 +462,8 @@ async function main() {
|
|
|
462
462
|
zlibDeflateOptions: { level: 1 }, // Fastest compression to avoid CPU bottleneck
|
|
463
463
|
threshold: 128, // Only compress messages > 128 bytes
|
|
464
464
|
concurrencyLimit: 10,
|
|
465
|
+
clientNoContextTakeover: true, // Stateless compression — better proxy compatibility
|
|
466
|
+
serverNoContextTakeover: true,
|
|
465
467
|
},
|
|
466
468
|
});
|
|
467
469
|
setupWebSocket(wss, AUTH_TOKEN, DEFAULT_WORKING_DIR, safeTokenCompare, MAX_CONNECTIONS);
|
package/server/dist/tmux.js
CHANGED
|
@@ -162,8 +162,9 @@ export async function cleanupStaleSessions(ttlHours) {
|
|
|
162
162
|
}
|
|
163
163
|
/** 获取 tmux session 当前活动 pane 的工作目录 */
|
|
164
164
|
export async function getCwd(sessionName) {
|
|
165
|
+
// Use list-panes instead of display-message: display-message ignores the = exact-match prefix
|
|
165
166
|
const { stdout } = await execFile('tmux', [
|
|
166
|
-
'
|
|
167
|
+
'list-panes', '-t', `=${sessionName}`, '-F', '#{pane_current_path}',
|
|
167
168
|
], { encoding: 'utf-8' });
|
|
168
169
|
return stdout.trim();
|
|
169
170
|
}
|
|
@@ -171,7 +172,7 @@ export async function getCwd(sessionName) {
|
|
|
171
172
|
export async function getPaneCommand(sessionName) {
|
|
172
173
|
try {
|
|
173
174
|
const { stdout } = await execFile('tmux', [
|
|
174
|
-
'
|
|
175
|
+
'list-panes', '-t', `=${sessionName}`, '-F', '#{pane_current_command}',
|
|
175
176
|
], { encoding: 'utf-8' });
|
|
176
177
|
return stdout.trim();
|
|
177
178
|
}
|
package/server/dist/websocket.js
CHANGED
|
@@ -80,7 +80,7 @@ function sendBinary(ws, typePrefix, data) {
|
|
|
80
80
|
/** Server-side keepalive: ping all clients every 30s, terminate if no pong */
|
|
81
81
|
let keepAliveInterval = null;
|
|
82
82
|
function startKeepAlive(wss) {
|
|
83
|
-
const KEEPALIVE_INTERVAL =
|
|
83
|
+
const KEEPALIVE_INTERVAL = 20_000;
|
|
84
84
|
keepAliveInterval = setInterval(() => {
|
|
85
85
|
for (const ws of wss.clients) {
|
|
86
86
|
const alive = ws;
|
package/server/package.json
CHANGED
package/shared/package.json
CHANGED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
var it=Object.defineProperty;var at=(t,e,n)=>e in t?it(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Te=(t,e,n)=>at(t,typeof e!="symbol"?e+"":e,n);import{r as d,a as lt,g as ct,R as ge}from"./react-vendor-BCIvbQoU.js";import{D as Fe,o as We,x as dt}from"./terminal-CFozNkMS.js";import{d as ut,p as ft}from"./markdown-BERZKN_L.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();var Be={exports:{}},de={};/**
|
|
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 pt=d,mt=Symbol.for("react.element"),ht=Symbol.for("react.fragment"),xt=Object.prototype.hasOwnProperty,bt=pt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,yt={key:!0,ref:!0,__self:!0,__source:!0};function Ue(t,e,n){var r,o={},a=null,c=null;n!==void 0&&(a=""+n),e.key!==void 0&&(a=""+e.key),e.ref!==void 0&&(c=e.ref);for(r in e)xt.call(e,r)&&!yt.hasOwnProperty(r)&&(o[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)o[r]===void 0&&(o[r]=e[r]);return{$$typeof:mt,type:t,key:a,ref:c,props:o,_owner:bt.current}}de.Fragment=ht;de.jsx=Ue;de.jsxs=Ue;Be.exports=de;var s=Be.exports,be={},ke=lt;be.createRoot=ke.createRoot,be.hydrateRoot=ke.hydrateRoot;const gt={},Ie=t=>{let e;const n=new Set,r=(f,u)=>{const b=typeof f=="function"?f(e):f;if(!Object.is(b,e)){const m=e;e=u??(typeof b!="object"||b===null)?b:Object.assign({},e,b),n.forEach(x=>x(e,m))}},o=()=>e,l={setState:r,getState:o,getInitialState:()=>p,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},p=e=t(r,o,l);return l},wt=t=>t?Ie(t):Ie;var He={exports:{}},Ve={},Ge={exports:{}},qe={};/**
|
|
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 te=d;function vt(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var St=typeof Object.is=="function"?Object.is:vt,Tt=te.useState,kt=te.useEffect,It=te.useLayoutEffect,Ct=te.useDebugValue;function jt(t,e){var n=e(),r=Tt({inst:{value:n,getSnapshot:e}}),o=r[0].inst,a=r[1];return It(function(){o.value=n,o.getSnapshot=e,he(o)&&a({inst:o})},[t,n,e]),kt(function(){return he(o)&&a({inst:o}),t(function(){he(o)&&a({inst:o})})},[t]),Ct(n),n}function he(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!St(t,n)}catch{return!0}}function Et(t,e){return e()}var Rt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Et:jt;qe.useSyncExternalStore=te.useSyncExternalStore!==void 0?te.useSyncExternalStore:Rt;Ge.exports=qe;var Lt=Ge.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 ue=d,zt=Lt;function Mt(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var Dt=typeof Object.is=="function"?Object.is:Mt,Nt=zt.useSyncExternalStore,Ot=ue.useRef,_t=ue.useEffect,At=ue.useMemo,$t=ue.useDebugValue;Ve.useSyncExternalStoreWithSelector=function(t,e,n,r,o){var a=Ot(null);if(a.current===null){var c={hasValue:!1,value:null};a.current=c}else c=a.current;a=At(function(){function l(m){if(!p){if(p=!0,f=m,m=r(m),o!==void 0&&c.hasValue){var x=c.value;if(o(x,m))return u=x}return u=m}if(x=u,Dt(f,m))return x;var S=r(m);return o!==void 0&&o(x,S)?(f=m,x):(f=m,u=S)}var p=!1,f,u,b=n===void 0?null:n;return[function(){return l(e())},b===null?void 0:function(){return l(b())}]},[e,n,r,o]);var i=Nt(t,a[0],a[1]);return _t(function(){c.hasValue=!0,c.value=i},[i]),$t(i),i};He.exports=Ve;var Pt=He.exports;const Ft=ct(Pt),Je={},{useDebugValue:Wt}=ge,{useSyncExternalStoreWithSelector:Bt}=Ft;let Ce=!1;const Ut=t=>t;function Ht(t,e=Ut,n){(Je?"production":void 0)!=="production"&&n&&!Ce&&(Ce=!0);const r=Bt(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return Wt(r),r}const je=t=>{const e=typeof t=="function"?wt(t):t,n=(r,o)=>Ht(e,r,o);return Object.assign(n,e),n},Vt=t=>t?je(t):je,P="";function B(t){return{Authorization:`Bearer ${t}`}}async function Gt(t){try{const e=await fetch(`${P}/api/settings/font-size`,{headers:B(t)});return e.ok?(await e.json()).fontSize:14}catch{return 14}}async function qt(t,e){try{await fetch(`${P}/api/settings/font-size`,{method:"PUT",headers:{...B(t),"Content-Type":"application/json"},body:JSON.stringify({fontSize:e})})}catch{}}async function Jt(t){try{const e=await fetch(`${P}/api/settings/tabs-layout`,{headers:B(t)});return e.ok?(await e.json()).layout:null}catch{return null}}async function Kt(t,e){try{await fetch(`${P}/api/settings/tabs-layout`,{method:"PUT",headers:{...B(t),"Content-Type":"application/json"},body:JSON.stringify({layout:e})})}catch{}}function Ee(t,e){try{const n=`${P}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:t});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const ce="ai-cli-online-tabs",Re="ai-cli-online-layout",Le="ai-cli-online-session-names";function oe(t,e){if(t.type==="leaf")return t.terminalId===e?null:t;const n=[],r=[];for(let c=0;c<t.children.length;c++){const i=oe(t.children[c],e);i!==null&&(n.push(i),r.push(t.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,i)=>c+i,0),a=r.map(c=>c/o*100);return{...t,children:n,sizes:a}}function Ke(t,e,n,r,o){return t.type==="leaf"?t.terminalId===e?{id:o,type:"split",direction:n,children:[t,r],sizes:[50,50]}:t:{...t,children:t.children.map(a=>Ke(a,e,n,r,o))}}function Ye(t,e,n){return t.type==="leaf"?t:t.id===e?{...t,sizes:n}:{...t,children:t.children.map(r=>Ye(r,e,n))}}function xe(t){return t.tabs.find(e=>e.id===t.activeTabId)}function X(t,e,n){return t.map(r=>r.id===e?n(r):r)}function V(t){const e={version:2,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId,tabs:t.tabs};try{localStorage.setItem(ce,JSON.stringify(e))}catch{}Yt(e)}let se=null,ie=null,Z=null,ne=null;function Yt(t){ne=t,Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,ne=null;const e=v.getState().token;e&&Kt(e,t)},2e3)}function Xt(t){se&&clearTimeout(se),se=setTimeout(()=>{se=null,V(t)},500)}function Zt(){try{const t=localStorage.getItem(ce);if(t){const e=JSON.parse(t);if(e.version===2)return e}}catch{}try{const t=localStorage.getItem(Re);if(t){const e=JSON.parse(t);let n="Default";try{const a=localStorage.getItem(Le);if(a){const c=JSON.parse(a),i=Object.values(c)[0];i&&(n=i)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(ce,JSON.stringify(o))}catch{}return localStorage.removeItem(Re),localStorage.removeItem(Le),o}}catch{}return null}function W(t){return{tabs:t.tabs,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId}}function Qt(t,e){const n=new Set(e.map(c=>c.sessionId)),r=[];for(const c of t.tabs){if(c.status!=="open"){const p=c.terminalIds.filter(f=>n.has(f));if(p.length>0){let f=c.layout;for(const u of c.terminalIds)!n.has(u)&&f&&(f=oe(f,u));r.push({...c,terminalIds:p,layout:f})}continue}const i=c.terminalIds.filter(p=>n.has(p));if(i.length===0)continue;let l=c.layout;for(const p of c.terminalIds)!n.has(p)&&l&&(l=oe(l,p));r.push({...c,terminalIds:i,layout:l})}if(r.filter(c=>c.status==="open").length===0)return null;let o=t.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(i=>i.status==="open");o=(c==null?void 0:c.id)||""}return{...t,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var e,n;const t=(n=(e=v==null?void 0:v.getState)==null?void 0:e.call(v))==null?void 0:n.token;if(t)if(ne)Z&&(clearTimeout(Z),Z=null),Ee(t,ne),ne=null;else{const r=v.getState();r.tabs.length>0&&Ee(t,W(r))}});const v=Vt((t,e)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Gt(n).then(o=>{e().token===n&&t({fontSize:o})});const r=Zt();if(r&&r.tabs.length>0){const o={};for(const i of r.tabs)if(i.status==="open")for(const l of i.terminalIds)o[l]={id:l,connected:!1,sessionResumed:!1,error:null};const a=r.tabs.find(i=>i.id===r.activeTabId&&i.status==="open")||r.tabs.find(i=>i.status==="open"),c=(a==null?void 0:a.id)||"";t({token:n,tabsLoading:!0,terminalsMap:o,tabs:r.tabs,activeTabId:c,nextId:r.nextId,nextSplitId:r.nextSplitId,nextTabId:r.nextTabId,terminalIds:(a==null?void 0:a.terminalIds)||[],layout:(a==null?void 0:a.layout)||null})}else t({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});en(n,r);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(ce),t({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=e(),o=`tab${r.nextTabId}`,a=`t${r.nextId}`,c={id:a,connected:!1,sessionResumed:!1,error:null},i={type:"leaf",terminalId:a},l={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[a],layout:i,createdAt:Date.now()};return t({tabs:[...r.tabs,l],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[a]:c},terminalIds:l.terminalIds,layout:l.layout}),V(W(e())),o},switchTab:n=>{const o=e().tabs.find(a=>a.id===n);!o||o.status!=="open"||(t({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),V(W(e())))},closeTab:n=>{const r=e(),o=r.tabs.find(u=>u.id===n);if(!o||o.status!=="open"||r.tabs.filter(u=>u.status==="open").length<=1)return;const c={...r.terminalsMap};for(const u of o.terminalIds)delete c[u];const i=X(r.tabs,n,u=>({...u,status:"closed"}));let l=r.activeTabId,p=r.terminalIds,f=r.layout;if(r.activeTabId===n){const u=r.tabs.findIndex(x=>x.id===n),b=i.filter(x=>x.status==="open"),m=b.find(x=>i.findIndex(I=>I.id===x.id)>u)||b[b.length-1];m&&(l=m.id,p=m.terminalIds,f=m.layout)}t({tabs:i,activeTabId:l,terminalsMap:c,terminalIds:p,layout:f}),V(W(e()))},reopenTab:n=>{const r=e(),o=r.tabs.find(i=>i.id===n);if(!o||o.status!=="closed")return;const a={...r.terminalsMap};for(const i of o.terminalIds)a[i]={id:i,connected:!1,sessionResumed:!1,error:null};const c=X(r.tabs,n,i=>({...i,status:"open"}));t({tabs:c,activeTabId:n,terminalsMap:a,terminalIds:o.terminalIds,layout:o.layout}),V(W(e()))},deleteTab:async n=>{const r=e(),o=r.tabs.find(m=>m.id===n);if(!o)return;const a=r.token;a&&await Promise.all(o.terminalIds.map(m=>fetch(`${P}/api/sessions/${encodeURIComponent(m)}`,{method:"DELETE",headers:B(a)}).catch(()=>{})));const c=e(),i=c.tabs.find(m=>m.id===n);if(!i)return;const l={...c.terminalsMap};for(const m of i.terminalIds)delete l[m];const p=c.tabs.filter(m=>m.id!==n);let f=c.activeTabId,u=c.terminalIds,b=c.layout;if(c.activeTabId===n){const m=p.find(x=>x.status==="open");m?(f=m.id,u=m.terminalIds,b=m.layout):(f="",u=[],b=null)}t({tabs:p,activeTabId:f,terminalsMap:l,terminalIds:u,layout:b}),V(W(e())),setTimeout(()=>e().fetchSessions(),500)},renameTab:(n,r)=>{const o=X(e().tabs,n,a=>({...a,name:r}));t({tabs:o}),V(W(e()))},addTerminal:(n,r)=>{const o=e();if(r&&o.terminalsMap[r])return r;const a=xe(o);if(!a){const M=`tab${o.nextTabId}`,j=r||`t${o.nextId}`;let L=o.nextId;const z=j.match(/^t(\d+)$/);z&&(L=Math.max(L,parseInt(z[1],10)+1));const h=r?L:L+1,T={id:j,connected:!1,sessionResumed:!1,error:null},D={type:"leaf",terminalId:j},$={id:M,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[j],layout:D,createdAt:Date.now()};return t({tabs:[...o.tabs,$],activeTabId:M,nextTabId:o.nextTabId+1,nextId:h,terminalsMap:{...o.terminalsMap,[j]:T},terminalIds:[j],layout:D}),V(W(e())),j}const{nextId:c,nextSplitId:i,terminalsMap:l}=o,{terminalIds:p,layout:f}=a,u=r||`t${c}`;let b=c;const m=u.match(/^t(\d+)$/);m&&(b=Math.max(b,parseInt(m[1],10)+1));const x={id:u,connected:!1,sessionResumed:!1,error:null},S={type:"leaf",terminalId:u};let I,w=i;if(!f)I=S;else if(f.type==="leaf"){const M=n||"horizontal";I={id:`s${w}`,type:"split",direction:M,children:[f,S],sizes:[50,50]},w++}else if(f.direction===(n||"horizontal")){const j=100/(f.children.length+1),L=(100-j)/100,z=[...f.sizes.map(h=>h*L),j];I={...f,children:[...f.children,S],sizes:z}}else{const M=n||"horizontal";I={id:`s${w}`,type:"split",direction:M,children:[f,S],sizes:[50,50]},w++}const R=[...p,u],C=r?b:b+1,y=X(o.tabs,a.id,M=>({...M,terminalIds:R,layout:I}));return t({terminalsMap:{...l,[u]:x},terminalIds:R,layout:I,tabs:y,nextId:C,nextSplitId:w}),V(W(e())),u},splitTerminal:(n,r)=>{const o=e(),a=xe(o);if(!a||!a.layout)return"";const{nextId:c,nextSplitId:i,terminalsMap:l}=o,p=`t${c}`,f={id:p,connected:!1,sessionResumed:!1,error:null},u={type:"leaf",terminalId:p},b=`s${i}`,m=Ke(a.layout,n,r,u,b),x=[...a.terminalIds,p],S=c+1,I=i+1,w=X(o.tabs,a.id,R=>({...R,terminalIds:x,layout:m}));return t({terminalsMap:{...l,[p]:f},terminalIds:x,layout:m,tabs:w,nextId:S,nextSplitId:I}),V(W(e())),p},removeTerminal:n=>{const r=e(),o=r.tabs.find(f=>f.terminalIds.includes(n));if(!o){const{[n]:f,...u}=r.terminalsMap;t({terminalsMap:u});return}const a=o.terminalIds.filter(f=>f!==n),c=o.layout?oe(o.layout,n):null,i=X(r.tabs,o.id,f=>({...f,terminalIds:a,layout:c})),{[n]:l,...p}=r.terminalsMap;o.id===r.activeTabId?t({terminalsMap:p,terminalIds:a,layout:c,tabs:i}):t({terminalsMap:p,tabs:i}),V(W(e()))},setTerminalConnected:(n,r)=>{t(o=>{const a=o.terminalsMap[n];return!a||a.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,connected:r}}}})},setTerminalResumed:(n,r)=>{t(o=>{const a=o.terminalsMap[n];return!a||a.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,sessionResumed:r}}}})},setTerminalError:(n,r)=>{t(o=>{const a=o.terminalsMap[n];return!a||a.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,error:r}}}})},setSplitSizes:(n,r)=>{const o=e(),a=xe(o);if(!a||!a.layout)return;const c=Ye(a.layout,n,r),i=X(o.tabs,a.id,l=>({...l,layout:c}));t({layout:c,tabs:i}),Xt(W(e()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));t({fontSize:r}),ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null;const o=e().token;o&&qt(o,r)},500)},latency:null,setLatency:n=>t({latency:n}),sidebarOpen:!1,toggleSidebar:()=>t(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=e().token;if(n)try{const r=await fetch(`${P}/api/sessions`,{headers:B(n)});if(!r.ok)return;const o=await r.json();t({serverSessions:o})}catch{}},killServerSession:async n=>{const r=e().token;if(!r)return;try{await fetch(`${P}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:B(r)})}catch{}const o=e(),a=o.tabs.find(c=>c.terminalIds.includes(n));if(a){const c=a.terminalIds.filter(u=>u!==n),i=a.layout?oe(a.layout,n):null,l=X(o.tabs,a.id,u=>({...u,terminalIds:c,layout:i})),{[n]:p,...f}=o.terminalsMap;a.id===o.activeTabId?t({terminalsMap:f,terminalIds:c,layout:i,tabs:l}):t({terminalsMap:f,tabs:l}),V(W(e()))}else{const{[n]:c,...i}=o.terminalsMap;t({terminalsMap:i})}setTimeout(()=>e().fetchSessions(),500)}}));async function en(t,e){var o;const{setState:n,getState:r}=v;try{const[a,c]=await Promise.all([Jt(t),fetch(`${P}/api/sessions`,{headers:B(t)}).then(m=>m.ok?m.json():[]).catch(()=>[])]);if(r().token!==t)return;const i=a&&((o=a.tabs)==null?void 0:o.length)>0?a:e;if(!i||i.tabs.length===0){n({tabsLoading:!1});return}const l=Qt(i,c);if(!l){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:[],layout:null});return}const p=r().terminalsMap,f={};for(const m of l.tabs)if(m.status==="open")for(const x of m.terminalIds)f[x]=p[x]||{id:x,connected:!1,sessionResumed:!1,error:null};const u=l.tabs.find(m=>m.id===l.activeTabId&&m.status==="open")||l.tabs.find(m=>m.status==="open"),b=(u==null?void 0:u.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:l.tabs,activeTabId:b,nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null}),V(W(r()))}catch{r().token===t&&n({tabsLoading:!1})}}function tn(){const[t,e]=d.useState(""),n=v(o=>o.setToken),r=o=>{o.preventDefault(),t.trim()&&n(t.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:t,onChange:o=>e(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:!t.trim(),style:{width:"100%",padding:"11px",background:t.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:t.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:t.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#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"})]})})]})})}/**
|
|
26
|
+
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
|
|
27
|
+
* @license MIT
|
|
28
|
+
*
|
|
29
|
+
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
|
30
|
+
* @license MIT
|
|
31
|
+
*
|
|
32
|
+
* Originally forked from (with the author's permission):
|
|
33
|
+
* Fabrice Bellard's javascript vt100 for jslinux:
|
|
34
|
+
* http://bellard.org/jslinux/
|
|
35
|
+
* Copyright (c) 2011 Fabrice Bellard
|
|
36
|
+
*/var nn=class{constructor(t,e,n,r={}){this._terminal=t,this._regex=e,this._handler=n,this._options=r}provideLinks(t,e){let n=on.computeLink(t,this._regex,this._terminal,this._handler);e(this._addCallbacks(n))}_addCallbacks(t){return t.map(e=>(e.leave=this._options.leave,e.hover=(n,r)=>{if(this._options.hover){let{range:o}=e;this._options.hover(n,r,o)}},e))}};function rn(t){try{let e=new URL(t),n=e.password&&e.username?`${e.protocol}//${e.username}:${e.password}@${e.host}`:e.username?`${e.protocol}//${e.username}@${e.host}`:`${e.protocol}//${e.host}`;return t.toLocaleLowerCase().startsWith(n.toLocaleLowerCase())}catch{return!1}}var on=class le{static computeLink(e,n,r,o){let a=new RegExp(n.source,(n.flags||"")+"g"),[c,i]=le._getWindowedLineStrings(e-1,r),l=c.join(""),p,f=[];for(;p=a.exec(l);){let u=p[0];if(!rn(u))continue;let[b,m]=le._mapStrIdx(r,i,0,p.index),[x,S]=le._mapStrIdx(r,b,m,u.length);if(b===-1||m===-1||x===-1||S===-1)continue;let I={start:{x:m+1,y:b+1},end:{x:S,y:x+1}};f.push({range:I,text:u,activate:o})}return f}static _getWindowedLineStrings(e,n){let r,o=e,a=e,c=0,i="",l=[];if(r=n.buffer.active.getLine(e)){let p=r.translateToString(!0);if(r.isWrapped&&p[0]!==" "){for(c=0;(r=n.buffer.active.getLine(--o))&&c<2048&&(i=r.translateToString(!0),c+=i.length,l.push(i),!(!r.isWrapped||i.indexOf(" ")!==-1)););l.reverse()}for(l.push(p),c=0;(r=n.buffer.active.getLine(++a))&&r.isWrapped&&c<2048&&(i=r.translateToString(!0),c+=i.length,l.push(i),i.indexOf(" ")===-1););}return[l,o]}static _mapStrIdx(e,n,r,o){let a=e.buffer.active,c=a.getNullCell(),i=r;for(;o;){let l=a.getLine(n);if(!l)return[-1,-1];for(let p=i;p<l.length;++p){l.getCell(p,c);let f=c.getChars();if(c.getWidth()&&(o-=f.length||1,p===l.length-1&&f==="")){let u=a.getLine(n+1);u&&u.isWrapped&&(u.getCell(0,c),c.getWidth()===2&&(o+=1))}if(o<0)return[n,p]}n++,i=0}return[n,i]}},sn=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function an(t,e){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=e}}var ln=class{constructor(t=an,e={}){this._handler=t,this._options=e}activate(t){this._terminal=t;let e=this._options,n=e.urlRegex||sn;this._linkProvider=this._terminal.registerLinkProvider(new nn(this._terminal,n,this._handler,e))}dispose(){var t;(t=this._linkProvider)==null||t.dispose()}};const cn=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,ae=500,dn=8e3,un=1e4,ze=4e3,fn=5e3,pn=5,mn=64*1024,hn=1,Me=2,xn=3,bn=4,yn=new TextDecoder,gn=new TextEncoder;function De(t,e){const n=gn.encode(e),r=new Uint8Array(1+n.length);return r[0]=t,r.set(n,1),r.buffer}function wn(t,e,n){const r=d.useRef(null),o=d.useRef(ae),a=d.useRef(null),c=d.useRef(null),i=d.useRef(null),l=d.useRef(null),p=d.useRef(!1),f=d.useRef(n),u=d.useRef(!1),b=d.useRef(0),m=d.useRef(!0),x=d.useRef(!navigator.onLine),S=d.useRef(""),I=d.useRef(null),w=d.useRef("");f.current=n;const R=d.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),i.current&&(clearTimeout(i.current),i.current=null),a.current&&(clearTimeout(a.current),a.current=null),l.current&&(clearTimeout(l.current),l.current=null),I.current&&(clearTimeout(I.current),I.current=null)},[]),C=d.useCallback(()=>{const{token:L,setTerminalError:z}=v.getState();if(!L||p.current)return;if(r.current){const $=r.current.readyState;if($===WebSocket.OPEN||$===WebSocket.CONNECTING)return}u.current=!1;const h=`${cn}?sessionId=${encodeURIComponent(e)}`,T=new WebSocket(h);T.binaryType="arraybuffer",l.current=window.setTimeout(()=>{T.readyState===WebSocket.CONNECTING&&T.close()},fn);const D=()=>{T.readyState===WebSocket.OPEN&&(b.current=performance.now(),T.send(JSON.stringify({type:"ping"})),i.current=window.setTimeout(()=>{b.current>0&&(b.current=0,T.close())},ze))};T.onopen=()=>{l.current&&(clearTimeout(l.current),l.current=null),T.send(JSON.stringify({type:"auth",token:L})),z(e,null),o.current=ae,m.current=!0},T.onclose=$=>{const{setTerminalConnected:U,setTerminalError:A,setToken:E}=v.getState();if(U(e,!1),R(),u.current)return;if($.code===4001){p.current=!0,A(e,"Authentication failed"),E(null),localStorage.removeItem("ai-cli-online-token");return}if($.code===4002)return;if($.code===4005){A(e,"Connection limit reached");return}if(!navigator.onLine){x.current=!0;return}if(m.current){m.current=!1,a.current=window.setTimeout(()=>C(),50);return}const O=o.current;o.current=Math.min(O*2,dn);const N=Math.round(O*(.5+Math.random()));a.current=window.setTimeout(()=>{C()},N)},T.onerror=()=>{},T.onmessage=$=>{var U;try{const A=t.current;if($.data instanceof ArrayBuffer){const O=new Uint8Array($.data);if(O.length<1)return;const N=O[0],G=O.subarray(1);switch(N){case hn:A==null||A.write(G);break;case xn:A==null||A.write(G);break;case bn:{(U=f.current)==null||U.call(f,yn.decode(G));break}}return}const E=JSON.parse($.data);switch(E.type){case"connected":{const O=v.getState();O.setTerminalConnected(e,!0),O.setTerminalResumed(e,E.resumed);const N=t.current;N&&T.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"resize",cols:N.cols,rows:N.rows})),w.current&&(T.send(De(Me,w.current)),w.current=""),D(),c.current=window.setInterval(D,un);break}case"error":v.getState().setTerminalError(e,E.error);break;case"pong":{if(i.current&&(clearTimeout(i.current),i.current=null),b.current>0){const O=Math.round(performance.now()-b.current),N=v.getState();(N.terminalIds.length===0||N.terminalIds[0]===e)&&N.setLatency(O),b.current=0}break}}}catch{}},r.current=T},[e,t,R]),y=d.useCallback(L=>{const z=r.current;if(!z||z.readyState!==WebSocket.OPEN){w.current.length<mn&&(w.current+=L);return}S.current+=L,I.current||(I.current=window.setTimeout(()=>{const h=S.current;S.current="",I.current=null,h&&z.readyState===WebSocket.OPEN&&z.send(De(Me,h))},pn))},[]),M=d.useCallback((L,z)=>{var h;((h=r.current)==null?void 0:h.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:L,rows:z}))},[]),j=d.useCallback(()=>{var L;((L=r.current)==null?void 0:L.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]);return d.useEffect(()=>{v.getState().token&&(p.current=!1,C());const z=()=>{x.current=!1,o.current=ae,m.current=!0;const D=r.current;(!D||D.readyState===WebSocket.CLOSED||D.readyState===WebSocket.CLOSING)&&C()},h=()=>{x.current=!0},T=()=>{if(document.visibilityState!=="visible")return;const D=r.current;if(!D||D.readyState!==WebSocket.OPEN){!x.current&&!u.current&&(o.current=ae,m.current=!0,C());return}b.current=performance.now(),D.send(JSON.stringify({type:"ping"})),i.current&&clearTimeout(i.current),i.current=window.setTimeout(()=>{b.current>0&&(b.current=0,D.close())},ze)};return window.addEventListener("online",z),window.addEventListener("offline",h),document.addEventListener("visibilitychange",T),()=>{u.current=!0,R(),window.removeEventListener("online",z),window.removeEventListener("offline",h),document.removeEventListener("visibilitychange",T),r.current&&(r.current.close(),r.current=null)}},[C,R,e]),{sendInput:y,sendResize:M,requestScrollback:j}}const Xe={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"},Ze="'Maple Mono CN', 'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",vn=d.forwardRef(function({sessionId:e},n){const r=d.useRef(null),o=d.useRef(null),a=d.useRef(null),[c,i]=d.useState(!1),[l,p]=d.useState(""),f=v(w=>w.fontSize),u=d.useCallback(w=>{p(w),i(!0)},[]),{sendInput:b,sendResize:m,requestScrollback:x}=wn(o,e,u);d.useImperativeHandle(n,()=>({sendInput:b}),[b]);const S=d.useRef(b),I=d.useRef(m);return S.current=b,I.current=m,d.useEffect(()=>{if(!r.current)return;let w=!1,R=null,C=null,y=null,M=null;if(w||!r.current)return;const j=new Fe({cursorBlink:!0,scrollback:1e4,fontSize:v.getState().fontSize,fontFamily:Ze,theme:Xe,allowProposedApi:!0}),L=new We;j.loadAddon(L),j.loadAddon(new ln((T,D)=>{window.open(D,"_blank","noopener,noreferrer")})),j.open(r.current);try{const T=new dt;T.onContextLoss(()=>{T.dispose()}),j.loadAddon(T)}catch{}o.current=j,a.current=L;const z=()=>{try{const T=r.current;if(T&&T.clientWidth>0&&T.clientHeight>0)return L.fit(),I.current(j.cols,j.rows),!0}catch{}return!1};requestAnimationFrame(()=>z());let h=0;return R=setInterval(()=>{h++,(z()||h>=10)&&(clearInterval(R),R=null)},100),document.fonts.ready.then(()=>{if(!w)try{L.fit(),I.current(j.cols,j.rows)}catch{}}),j.onData(T=>{S.current(T)}),M=new ResizeObserver(()=>{C||(C=requestAnimationFrame(()=>{C=null;try{L.fit(),y&&clearTimeout(y),y=setTimeout(()=>{y=null,I.current(j.cols,j.rows)},50)}catch{}}))}),M.observe(r.current),()=>{w=!0,R&&clearInterval(R),C&&cancelAnimationFrame(C),y&&clearTimeout(y),M&&M.disconnect(),o.current&&(o.current.dispose(),o.current=null),a.current=null}},[e]),d.useEffect(()=>{const w=o.current,R=a.current;if(!(!w||!R)&&w.options.fontSize!==f){w.options.fontSize=f;try{R.fit()}catch{}I.current(w.cols,w.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",{onClick:()=>{c?(i(!1),p("")):x()},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:12,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:w=>{w.currentTarget.style.opacity="1"},onMouseLeave:w=>{w.currentTarget.style.opacity="0.8"},children:c?"✕":"↑"}),c&&s.jsx(Sn,{data:l,onClose:()=>{i(!1),p("")}})]})});function Sn({data:t,onClose:e}){const n=d.useRef(null),r=d.useRef(e);r.current=e;const o=v(i=>i.fontSize),a=d.useRef(null),c=d.useRef(null);return d.useEffect(()=>{if(!n.current)return;const i=new Fe({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:Ze,theme:Xe});a.current=i;const l=new We;c.current=l,i.loadAddon(l),i.open(n.current),requestAnimationFrame(()=>{try{l.fit()}catch{}i.write(t,()=>{i.scrollToBottom()})});let p=null;const f=new ResizeObserver(()=>{p||(p=requestAnimationFrame(()=>{p=null;try{l.fit()}catch{}}))});f.observe(n.current);const u=b=>{b.key==="Escape"&&r.current()};return document.addEventListener("keydown",u),()=>{p&&cancelAnimationFrame(p),document.removeEventListener("keydown",u),f.disconnect(),i.dispose(),a.current=null,c.current=null}},[t]),d.useEffect(()=>{var i;if(a.current){a.current.options.fontSize=o;try{(i=c.current)==null||i.fit()}catch{}}},[o]),s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column"},children:[s.jsx("div",{style:{padding:"4px 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{flex:1,overflow:"hidden"}})]})}async function re(t,e,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/files${r}`,{headers:B(t)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function Tn(t,e,n,r){return new Promise((o,a)=>{const c=new FormData;for(const l of n)c.append("files",l);const i=new XMLHttpRequest;i.open("POST",`${P}/api/sessions/${encodeURIComponent(e)}/upload`),i.setRequestHeader("Authorization",`Bearer ${t}`),i.upload.addEventListener("progress",l=>{l.lengthComputable&&r&&r(Math.round(l.loaded/l.total*100))}),i.addEventListener("load",()=>{i.status>=200&&i.status<300?o():a(new Error(`Upload failed: ${i.status}`))}),i.addEventListener("error",()=>a(new Error("Upload network error"))),i.addEventListener("abort",()=>a(new Error("Upload aborted"))),i.send(c)})}async function kn(t,e){const n=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/cwd`,{headers:B(t)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function In(t,e,n){const r=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/download?path=${encodeURIComponent(n)}`,{headers:B(t)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),a=URL.createObjectURL(o),c=document.createElement("a");c.href=a,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(a)}function we({sessionId:t,onClose:e,filter:n,pollCwd:r}){const o=v(C=>C.token),[a,c]=d.useState(""),[i,l]=d.useState([]),[p,f]=d.useState(!0),[u,b]=d.useState(null),m=d.useRef(""),x=d.useCallback(async C=>{if(o){f(!0),b(null);try{const y=await re(o,t,C);C||(m.current=y.cwd),c(y.cwd),l(n?n(y.files):y.files)}catch(y){b(y instanceof Error?y.message:"Failed to load files")}finally{f(!1)}}},[o,t,n]);d.useEffect(()=>{x()},[x]),d.useEffect(()=>{if(!r||!o)return;let C=!1;const y=setInterval(async()=>{if(!C)try{const M=await kn(o,t);if(C)return;if(M!==m.current){m.current=M;const j=await re(o,t);if(C)return;c(j.cwd),l(n?n(j.files):j.files)}}catch{}},r);return()=>{C=!0,clearInterval(y)}},[r,o,t,n]);const S=d.useRef(e);S.current=e,d.useEffect(()=>{const C=y=>{y.key==="Escape"&&S.current()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[]);const I=d.useCallback(C=>{x(a+"/"+C)},[x,a]),w=d.useCallback(()=>{const C=a.replace(/\/[^/]+$/,"")||"/";x(C)},[x,a]),R=d.useCallback(()=>{x(a)},[x,a]);return{cwd:a,files:i,loading:p,error:u,setError:b,handleNavigate:I,handleGoUp:w,handleRefresh:R}}function Cn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function Qe(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function ve({cwd:t,onGoUp:e,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:e,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:t||"..."})]}),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 Se({loading:t,error:e,empty:n,emptyText:r="Empty directory"}){return t?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):e?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:e}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function jn({sessionId:t,onClose:e}){const n=v(x=>x.token),{cwd:r,files:o,loading:a,error:c,setError:i,handleNavigate:l,handleGoUp:p,handleRefresh:f}=we({sessionId:t,onClose:e}),[u,b]=d.useState(null),m=async x=>{if(n){b(x);try{await In(n,t,r+"/"+x)}catch(S){i(S instanceof Error?S.message:"Download failed")}finally{b(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(ve,{cwd:r,onGoUp:p,onRefresh:f,onClose:e}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Se,{loading:a,error:c,empty:o.length===0,emptyText:"Empty directory"}),!a&&!c&&o.map(x=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:x.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:S=>{S.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:S=>{S.currentTarget.style.backgroundColor="transparent"},onClick:()=>{x.type==="directory"&&l(x.name)},children:[x.type==="file"?s.jsx("button",{onClick:S=>{S.stopPropagation(),m(x.name)},disabled:u===x.name,style:{background:"none",border:"1px solid #414868",color:u===x.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:u===x.name?"wait":"pointer",flexShrink:0,marginRight:6},children:u===x.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:x.type==="directory"?"#7aa2f7":"#565f89"},children:x.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:x.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:x.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:x.type==="file"?Cn(x.size):""})]},x.name))]})]})}function En({content:t}){const e=v(r=>r.fontSize),n=d.useMemo(()=>{if(!t)return"";const r=ut.parse(t,{async:!1});return ft.sanitize(r,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[t]);return t?s.jsx("div",{className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${e}px`},dangerouslySetInnerHTML:{__html:n}}):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 Rn(t,e){const n=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/draft`,{headers:B(t)});return n.ok?(await n.json()).content??"":""}async function Ne(t,e,n){await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/draft`,{method:"PUT",headers:{...B(t),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const Oe=[{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"}],Ln=d.forwardRef(function({onSend:e,onContentChange:n,sessionId:r,token:o},a){const c=v(g=>g.fontSize),[i,l]=d.useState(""),p=d.useRef(null),f=d.useRef(),u=d.useRef(!1),[b,m]=d.useState(!1),[x,S]=d.useState(""),[I,w]=d.useState(0),[R,C]=d.useState(!1),[y,M]=d.useState(""),[j,L]=d.useState(""),[z,h]=d.useState(0),[T,D]=d.useState([]),[$,U]=d.useState(!1),A=d.useRef(""),E=d.useRef(null),O=d.useMemo(()=>{if(!x)return Oe;const g=x.toLowerCase();return Oe.filter(k=>k.cmd.toLowerCase().includes(g)||k.desc.toLowerCase().includes(g))},[x]),N=d.useMemo(()=>{let g=T;if(y){const k=y.toLowerCase();g=g.filter(_=>_.name.toLowerCase().includes(k))}return[...g].sort((k,_)=>k.type==="directory"&&_.type!=="directory"?-1:k.type!=="directory"&&_.type==="directory"?1:k.name.localeCompare(_.name))},[T,y]);d.useEffect(()=>{let g=!1;return Rn(o,r).then(k=>{!g&&k&&l(k),u.current=!0}).catch(()=>{u.current=!0}),()=>{g=!0}},[o,r]),d.useEffect(()=>{if(u.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{Ne(o,r,i).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[i,o,r]),d.useEffect(()=>{var g;(g=p.current)==null||g.focus()},[]),d.useEffect(()=>{if(!R)return;let g=!1;return U(!0),(async()=>{try{if(j){if(!A.current){const F=await re(o,r);if(g)return;A.current=F.cwd}const k=`${A.current}/${j.replace(/\/$/,"")}`,_=await re(o,r,k);if(g)return;D(_.files)}else{const k=await re(o,r);if(g)return;A.current=k.cwd,D(k.files)}U(!1)}catch{if(g)return;D([]),U(!1)}})(),()=>{g=!0}},[R,j,o,r]),d.useEffect(()=>{if(!R||!E.current)return;const g=E.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[z,R]);const G=d.useCallback(()=>{const g=i.trim();g&&(e(g),l(""),Ne(o,r,"").catch(()=>{}))},[i,e,o,r]);d.useImperativeHandle(a,()=>({send:G}),[G]),d.useEffect(()=>{n==null||n(i.trim().length>0)},[i,n]);const fe=d.useCallback(g=>{const k=p.current;if(!k)return;const _=k.selectionStart,F=i.slice(0,_),K=i.slice(_),J=F.lastIndexOf(`
|
|
37
|
+
`)+1,q=F.slice(J).match(/\/[a-zA-Z-]*$/);if(q){const H=J+(q.index??0),ee=g+" ",me=i.slice(0,H)+ee+K;l(me);const st=H+ee.length;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=st,k.focus()})}else{const H=F+g+K;l(H);const ee=_+g.length;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=ee,k.focus()})}m(!1),S(""),w(0)},[i]),pe=d.useCallback(g=>{const k=p.current;if(!k)return;const _=k.selectionStart,F=i.slice(0,_),K=i.slice(_),Q=F.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!Q)return;const J=F.length-Q[0].length;if(g.type==="directory"){const Y="@"+j+g.name+"/",q=i.slice(0,J)+Y+K;l(q);const H=J+Y.length;L(j+g.name+"/"),M(""),h(0),requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=H,k.focus()})}else{const Y=g.name+" ",q=i.slice(0,J)+Y+K;l(q);const H=J+Y.length;C(!1),M(""),L(""),h(0),D([]),A.current="",requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=H,k.focus()})}},[i,j]),rt=d.useCallback(g=>{const k=g.target.value;l(k);const _=g.target.selectionStart,F=k.slice(0,_),K=F.lastIndexOf(`
|
|
38
|
+
`),J=F.slice(K+1).match(/^\/([a-zA-Z-]*)$/);if(J)m(!0),S(J[1]),w(0),C(!1);else{m(!1);const Y=F.match(/@([a-zA-Z0-9_.\-/]*)$/);if(Y){const q=Y[1],H=q.lastIndexOf("/"),ee=H>=0?q.slice(0,H+1):"",me=H>=0?q.slice(H+1):q;M(me),h(0),L(ee),C(!0)}else C(!1)}},[]),ot=d.useCallback(g=>{if(b&&O.length>0){if(g.key==="ArrowDown"){g.preventDefault(),w(k=>(k+1)%O.length);return}if(g.key==="ArrowUp"){g.preventDefault(),w(k=>(k-1+O.length)%O.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),fe(O[I].cmd);return}if(g.key==="Escape"){g.preventDefault(),m(!1);return}}if(R&&N.length>0){if(g.key==="ArrowDown"){g.preventDefault(),h(k=>(k+1)%N.length);return}if(g.key==="ArrowUp"){g.preventDefault(),h(k=>(k-1+N.length)%N.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),pe(N[z]);return}if(g.key==="Escape"){g.preventDefault(),C(!1);return}}if(g.key==="Tab"){g.preventDefault();const k=p.current;if(k){const _=k.selectionStart,F=k.selectionEnd,K=i.slice(0,_)+" "+i.slice(F);l(K);const Q=_+2;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=Q})}return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),G())},[G,b,O,I,fe,i,R,N,z,pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[b&&O.length>0&&s.jsx("div",{className:"slash-dropdown",children:O.map((g,k)=>s.jsxs("div",{className:`slash-item${k===I?" slash-item--active":""}`,onMouseDown:_=>{_.preventDefault(),fe(g.cmd)},onMouseEnter:()=>w(k),children:[s.jsx("span",{className:"slash-cmd",children:g.cmd}),s.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),R&&($||N.length>0)&&s.jsx("div",{className:"file-dropdown",ref:E,children:$?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):N.map((g,k)=>s.jsxs("div",{className:`file-item${k===z?" file-item--active":""}`,onMouseDown:_=>{_.preventDefault(),pe(g)},onMouseEnter:()=>h(k),children:[s.jsx("span",{className:"file-icon",children:g.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:g.name})]},g.name))}),s.jsx("textarea",{ref:p,className:"md-editor-textarea",value:i,onChange:rt,onKeyDown:ot,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function zn(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function Mn({sessionId:t,onSelect:e,onClose:n}){const{cwd:r,files:o,loading:a,error:c,handleNavigate:i,handleGoUp:l,handleRefresh:p}=we({sessionId:t,onClose:n}),f=u=>{e(r+"/"+u)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(ve,{cwd:r,onGoUp:l,onRefresh:p,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Se,{loading:a,error:c,empty:o.length===0,emptyText:"No files found"}),!a&&!c&&o.map(u=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="transparent"},onClick:()=>{u.type==="directory"?i(u.name):f(u.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:u.type==="directory"?"#7aa2f7":"#565f89"},children:zn(u.name,u.type)}),s.jsx("span",{style:{flex:1,color:u.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:u.name}),u.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:u.name.slice(u.name.lastIndexOf(".")).toLowerCase()})]},u.name))]})]})}const Dn="modulepreload",Nn=function(t){return"/"+t},_e={},On=function(e,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),i=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(l=>{if(l=Nn(l),l in _e)return;_e[l]=!0;const p=l.endsWith(".css"),f=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${f}`))return;const u=document.createElement("link");if(u.rel=p?"stylesheet":Dn,p||(u.as="script"),u.crossOrigin="",u.href=l,i&&u.setAttribute("nonce",i),document.head.appendChild(u),p)return new Promise((b,m)=>{u.addEventListener("load",b),u.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}function a(c){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=c,window.dispatchEvent(i),!i.defaultPrevented)throw c}return o.then(c=>{for(const i of c||[])i.status==="rejected"&&a(i.reason);return e().catch(a)})};let ye=null;const _n=On(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(t=>(ye=t,t.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),t));function An({data:t,scrollRef:e}){const n=d.useRef(null),[r,o]=d.useState(null),[a,c]=d.useState(!0),i=d.useRef(0),l=p=>{n.current=p,e==null||e(p)};return d.useEffect(()=>{if(!t)return;const p=++i.current;return c(!0),o(null),(async()=>{try{if(await _n,!ye||p!==i.current)return;const f=atob(t),u=new Uint8Array(f.length);for(let S=0;S<f.length;S++)u[S]=f.charCodeAt(S);const b=await ye.getDocument({data:u}).promise;if(p!==i.current)return;const m=n.current;if(!m)return;for(;m.firstChild;)m.removeChild(m.firstChild);const x=m.clientWidth-24;for(let S=1;S<=b.numPages;S++){const I=await b.getPage(S);if(p!==i.current)return;const w=I.getViewport({scale:1}),R=Math.min(x/w.width,2),C=I.getViewport({scale:R}),y=document.createElement("canvas");y.width=C.width,y.height=C.height,y.style.display="block",y.style.margin="0 auto 8px",y.style.maxWidth="100%";const M=y.getContext("2d");if(M){if(await I.render({canvasContext:M,viewport:C,canvas:y}).promise,p!==i.current)return;m.appendChild(y)}}c(!1)}catch(f){if(p!==i.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{i.current++}},[t]),s.jsxs("div",{ref:l,className:"pdf-renderer",children:[a&&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]})]})}async function Ae(t,e,n,r){const o=new URLSearchParams({path:n});r&&o.set("since",String(r));const a=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/file-content?${o}`,{headers:B(t)});if(a.status===304)return null;if(!a.ok)throw new Error("Failed to fetch file content");return a.json()}function $n(t=50,e=20,n=80){const[r,o]=d.useState(t),a=d.useRef(null),c=d.useCallback(i=>{i.preventDefault();const l=a.current;if(!l)return;const p=l.getBoundingClientRect(),f=p.width;document.body.classList.add("resizing-panes-h");let u=null;const b=x=>{u||(u=requestAnimationFrame(()=>{u=null;const S=x.clientX-p.left,I=Math.min(n,Math.max(e,S/f*100));o(I)}))},m=()=>{u&&cancelAnimationFrame(u),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",m)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",m)},[e,n]);return{leftWidthPercent:r,containerRef:a,onDividerMouseDown:c}}const Pn=3e3;function Fn(t){const e=t.slice(t.lastIndexOf(".")).toLowerCase();return e===".md"?"md":e===".html"||e===".htm"?"html":e===".pdf"?"pdf":"text"}function $e(t){return t.split("/").pop()||t}function Wn(t){if(t.type==="directory")return"📁";const e=t.name.slice(t.name.lastIndexOf(".")).toLowerCase();return e===".pdf"?"📕":e===".html"||e===".htm"?"🌐":e===".md"?"📝":"📄"}const Bn=3e3;function Un({sessionId:t,onSelect:e}){const n=d.useCallback(()=>{},[]),{cwd:r,files:o,loading:a,error:c,handleNavigate:i,handleGoUp:l,handleRefresh:p}=we({sessionId:t,onClose:n,pollCwd:Bn});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(ve,{cwd:r,onGoUp:l,onRefresh:p,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Se,{loading:a,error:c,empty:o.length===0,emptyText:"No files found"}),!a&&!c&&o.map(f=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:u=>{u.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent"},onClick:()=>{f.type==="directory"?i(f.name):e(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Wn(f)}),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",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:f.name.slice(f.name.lastIndexOf(".")).toLowerCase()})]},f.name))]})]})}function Hn({sessionId:t,token:e,onClose:n,onSend:r}){const[o,a]=d.useState(null),[c,i]=d.useState(""),[l,p]=d.useState(null),f=d.useRef(0),[u,b]=d.useState(!1),[m,x]=d.useState(!1),[S,I]=d.useState(!1),{leftWidthPercent:w,containerRef:R,onDividerMouseDown:C}=$n(50),y=d.useRef(null),[M,j]=d.useState(!1),L=d.useRef(new Map),z=d.useRef(null),h=d.useRef(null),T=d.useCallback(()=>{if(!o)return;const E=m?h.current:z.current;E&&L.current.set(o,E.scrollTop)},[o,m]),D=d.useCallback(E=>{const O=L.current.get(E);O!=null&&requestAnimationFrame(()=>{const N=m?h.current:z.current;N&&(N.scrollTop=O)})},[m]),$=d.useCallback(E=>{T();const O=Fn(E);a(E),p(O),i(""),f.current=0,b(!1),Ae(e,t,E).then(N=>{N&&(i(N.content),f.current=N.mtime,requestAnimationFrame(()=>D(E)))}).catch(()=>{})},[e,t,T,D]);d.useEffect(()=>{if(!o)return;let E=!1;const N=setInterval(async()=>{if(!E)try{const G=await Ae(e,t,o,f.current);if(E)return;G&&(i(G.content),f.current=G.mtime)}catch{}},Pn);return()=>{E=!0,clearInterval(N)}},[e,t,o]);const U=d.useCallback(()=>{o&&navigator.clipboard.writeText(o).then(()=>{I(!0),setTimeout(()=>I(!1),1500)}).catch(()=>{})},[o]);d.useEffect(()=>{if(!m)return;const E=O=>{O.key==="Escape"&&(T(),x(!1))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[m,T]),d.useEffect(()=>{o&&D(o)},[m,o,D]);const A=E=>o?!c&&l!=="pdf"?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:"13px"},children:"Loading..."}):l==="md"?s.jsx("div",{ref:E,style:{height:"100%",overflow:"auto"},children:s.jsx(En,{content:c})}):l==="html"?s.jsx("div",{ref:E,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:c,sandbox:"allow-same-origin",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})}):l==="pdf"?s.jsx(An,{data:c,scrollRef:E}):s.jsx("div",{ref:E,style:{height:"100%",overflow:"auto"},children:s.jsx("pre",{style:{margin:0,padding:"12px",fontFamily:'"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',fontSize:"13px",color:"#a9b1d6",whiteSpace:"pre-wrap",wordBreak:"break-all",lineHeight:1.5},children:c})}):s.jsx(Un,{sessionId:t,onSelect:$});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:"28px",flexShrink:0,backgroundColor:"#16161e",borderBottom:"1px solid #292e42"},children:[s.jsxs("div",{style:{width:`${w}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>b(E=>!E),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),o&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:U,title:S?"Copied!":`Click to copy: ${o}`,children:S?"Copied!":$e(o)}),s.jsx("button",{className:"pane-btn",onClick:()=>{T(),x(!0)},title:"Expand document view",style:{fontSize:"12px"},children:"⛶"})]})]}),s.jsx("div",{style:{width:"4px",flexShrink:0}}),s.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>{var E;return(E=y.current)==null?void 0:E.send()},disabled:!M,title:"Send to terminal (Ctrl+Enter)",style:M?{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:n,title:"Close Doc panel",children:"×"})]})]}),s.jsxs("div",{ref:R,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${w}%`,flexShrink:0},children:[A(E=>{z.current=E}),u&&s.jsx(Mn,{sessionId:t,onSelect:$,onClose:()=>b(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:C}),s.jsx("div",{className:"plan-editor-wrap",children:s.jsx(Ln,{ref:y,onSend:r,onContentChange:j,sessionId:t,token:e})})]}),m&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsx("span",{style:{fontSize:"12px",color:"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o?$e(o):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{T(),x(!1)},title:"Close expanded view (ESC)",children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:A(E=>{h.current=E})})]})]})}const Vn=100,Gn=600;function qn(){return d.useSyncExternalStore(t=>(window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)),()=>window.innerWidth)}const Jn=d.memo(function({terminal:e,canClose:n}){const o=qn()<Gn,a=v(h=>h.killServerSession),c=v(h=>h.splitTerminal),i=v(h=>h.token),l=d.useRef(null),p=d.useRef(null),[f,u]=d.useState(!1),[b,m]=d.useState(!1),[x,S]=d.useState(0),[I,w]=d.useState(!1),[R,C]=d.useState(50),y=d.useRef(null),M=async h=>{const T=h.target.files;if(!(!T||T.length===0||!i)){m(!0),S(0);try{await Tn(i,e.id,T,D=>{S(D)})}catch(D){alert(`Upload failed: ${D instanceof Error?D.message:"Unknown error"}`)}finally{m(!1),S(0),l.current&&(l.current.value="")}}},j=d.useRef(),L=d.useCallback(h=>{if(p.current){const T=h.replace(/\r?\n/g," ").trimEnd();p.current.sendInput(T),j.current=window.setTimeout(()=>{var D;return(D=p.current)==null?void 0:D.sendInput("\r")},50)}},[]);d.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]);const z=d.useCallback(h=>{h.preventDefault();const T=y.current;if(!T)return;const D=T.getBoundingClientRect(),$=D.height;document.body.classList.add("resizing-panes-v");const U=E=>{const O=(E.clientY-D.top)/$*100,N=Math.min(80,Math.max(20,O));C(100-N)},A=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",A)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",A)},[]);return s.jsxs("div",{ref:y,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"2px 8px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0,height:"24px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"#9ece6a":"#f7768e"}}),s.jsxs("span",{style:{fontSize:"11px",color:"#565f89"},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:l,type:"file",multiple:!0,style:{display:"none"},onChange:M}),s.jsx("button",{className:"pane-btn",onClick:()=>{var h;return(h=l.current)==null?void 0:h.click()},disabled:b,style:b?{color:"#e0af68"}:void 0,title:b?`Uploading ${x}%`:"Upload files","aria-label":"Upload files",children:b?`${x}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>u(h=>!h),style:f?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${I?" pane-btn--active":""}`,onClick:()=>w(h=>!h),title:"Toggle Document browser","aria-label":"Toggle Document browser",children:"Doc"}),s.jsx("button",{className:"pane-btn",onClick:()=>c(e.id,o?"vertical":"horizontal"),title:o?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>c(e.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"}),n&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>a(e.id),title:"Close terminal","aria-label":"Close terminal",children:"×"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(vn,{ref:p,sessionId:e.id}),!e.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..."})}),f&&s.jsx(jn,{sessionId:e.id,onClose:()=>u(!1)})]}),I&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:z}),s.jsx("div",{style:{height:`${R}%`,minHeight:Vn,flexShrink:0,overflow:"hidden"},children:s.jsx(Hn,{onSend:L,onClose:()=>w(!1),sessionId:e.id,token:i||""})})]}),e.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:e.error})]})});class et extends d.Component{constructor(){super(...arguments);Te(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 Kn=4,Pe=10;function Yn(){const t=v(o=>o.layout),e=v(o=>o.terminalIds.length),n=v(o=>o.addTerminal);if(!t)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=e>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(tt,{node:t,canClose:r})})}const tt=d.memo(function({node:e,canClose:n}){return e.type==="leaf"?s.jsx(Xn,{terminalId:e.terminalId,canClose:n}):s.jsx(Zn,{node:e,canClose:n})}),Xn=d.memo(function({terminalId:e,canClose:n}){const r=v(o=>o.terminalsMap[e]);return r?s.jsx(et,{inline:!0,children:s.jsx(Jn,{terminal:r,canClose:n})}):null}),Zn=d.memo(function({node:e,canClose:n}){const r=v(p=>p.setSplitSizes),o=d.useRef(null),a=e.direction==="horizontal",c=d.useRef(e.sizes);c.current=e.sizes;const i=d.useCallback((p,f)=>{f.preventDefault();const u=a?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const b=a?f.clientX:f.clientY,m=[...c.current],x=o.current,S=a?(x==null?void 0:x.clientWidth)||1:(x==null?void 0:x.clientHeight)||1;let I=null;const w=C=>{I||(I=requestAnimationFrame(()=>{I=null;const j=((a?C.clientX:C.clientY)-b)/S*100,L=m[p]+j,z=m[p+1]-j;if(L>=Pe&&z>=Pe){const h=[...m];h[p]=L,h[p+1]=z,r(e.id,h)}}))},R=()=>{I&&cancelAnimationFrame(I),document.body.classList.remove(u),document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",R)};document.addEventListener("mousemove",w),document.addEventListener("mouseup",R)},[a,e.id,r]),l=[];return e.children.forEach((p,f)=>{const u=p.type==="leaf"?p.terminalId:p.id;l.push(s.jsx("div",{style:{flex:`${e.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(tt,{node:p,canClose:n})},u)),f<e.children.length-1&&l.push(s.jsx("div",{onMouseDown:b=>i(f,b),style:{flex:`0 0 ${Kn}px`,cursor:a?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="#292e42"}},`divider-${e.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:a?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:l})});function Qn({tabId:t}){const e=v(h=>h.tabs.find(T=>T.id===t)),n=v(h=>h.activeTabId),r=v(h=>h.switchTab),o=v(h=>h.closeTab),a=v(h=>h.reopenTab),c=v(h=>h.deleteTab),i=v(h=>h.renameTab),l=v(h=>e?e.terminalIds.map(T=>{const D=h.terminalsMap[T];return D?{id:T,connected:D.connected}:{id:T,connected:!1}}):[]),[p,f]=d.useState(!1),[u,b]=d.useState(""),[m,x]=d.useState(!1),S=d.useRef(null);if(!e)return null;const I=n===t,w=e.status==="open",R=()=>{w&&r(t)},C=h=>{w&&(h.stopPropagation(),b(e.name),f(!0),setTimeout(()=>{var T;return(T=S.current)==null?void 0:T.focus()},0))},y=()=>{const h=u.trim();h&&i(t,h),f(!1)},M=h=>{h.stopPropagation(),a(t)},j=h=>{h.stopPropagation(),o(t)},L=async h=>{h.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await c(t)},z=h=>{h.stopPropagation(),x(!m)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:R,style:{padding:"8px 12px",cursor:w?"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:w?1:.5},onMouseEnter:h=>{w&&!I&&(h.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:h=>{I||(h.currentTarget.style.backgroundColor="transparent")},children:[w&&e.terminalIds.length>0&&s.jsx("button",{onClick:z,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:m?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[p?s.jsx("input",{ref:S,value:u,onChange:h=>b(h.target.value),onBlur:y,onKeyDown:h=>{h.key==="Enter"&&y(),h.key==="Escape"&&f(!1)},style:{width:"100%",background:"#1a1b26",border:"1px solid #7aa2f7",color:"#c0caf5",borderRadius:"3px",padding:"1px 4px",fontSize:"13px",outline:"none"}}):s.jsx("div",{onDoubleClick:C,style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:w?"Double-click to rename":e.name,children:e.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",Qe(Math.floor(e.createdAt/1e3))]})]}),w?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:j,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:M,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:L,title:"Delete tab",children:"×"})]})]}),w&&m&&l.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:l.map(h=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)"},title:`Connected: ${h.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:h.id}),s.jsx("span",{style:{marginLeft:"8px",color:h.connected?"#9ece6a":"#f7768e"},children:h.connected?"●":"○"})]},h.id))})]})}function er({sessionId:t,active:e,createdAt:n}){const r=v(i=>i.addTerminal),o=v(i=>i.killServerSession),a=()=>{r("horizontal",t)},c=i=>{i.stopPropagation(),window.confirm(`Delete orphaned session "${t}"? This will kill the tmux session.`)&&o(t)};return s.jsxs("div",{onClick:a,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s"},onMouseEnter:i=>{i.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:Qe(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function tr(){const t=v(l=>l.sidebarOpen),e=v(l=>l.toggleSidebar),n=v(l=>l.serverSessions),r=v(l=>l.fetchSessions),o=v(l=>l.tabs),a=v(l=>l.terminalIds),c=new Set(o.flatMap(l=>l.terminalIds)),i=n.filter(l=>!c.has(l.sessionId));return d.useEffect(()=>{if(!t)return;r();let l=setInterval(r,5e3);const p=()=>{document.hidden?l&&(clearInterval(l),l=null):(r(),l||(l=setInterval(r,5e3)))};return document.addEventListener("visibilitychange",p),()=>{l&&clearInterval(l),document.removeEventListener("visibilitychange",p)}},[t,r]),d.useEffect(()=>{if(!t)return;const l=setTimeout(r,800);return()=>clearTimeout(l)},[a.length,t,r]),s.jsxs("div",{className:"session-sidebar",style:{width:t?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:t?"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:e,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:"13px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(l=>s.jsx(Qn,{tabId:l.id},l.id))]}),i.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"}),i.map(l=>s.jsx(er,{sessionId:l.sessionId,active:l.active,createdAt:l.createdAt},l.sessionId))]})]})]})}const nt=ge.memo(()=>{const t=v(y=>y.tabs),e=v(y=>y.activeTabId),n=v(y=>y.addTab),r=v(y=>y.switchTab),o=v(y=>y.closeTab),a=v(y=>y.renameTab),[c,i]=d.useState(null),[l,p]=d.useState(""),f=d.useRef(null),u=t.filter(y=>y.status==="open");d.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const b=y=>{i(y.id),p(y.name)},m=()=>{c&&l.trim()&&a(c,l.trim()),i(null),p("")},x=()=>{i(null),p("")},S=y=>{y.key==="Enter"?m():y.key==="Escape"&&x()},I=y=>{c||r(y)},w=(y,M)=>{y.stopPropagation(),o(M)},R=(y,M)=>{y.button===1&&(y.preventDefault(),o(M))},C=u.length>1;return s.jsxs("div",{className:"tab-bar",children:[u.map(y=>{const M=y.id===e,j=c===y.id,L=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${M?"tab-item--active":""}`,onClick:()=>I(y.id),onDoubleClick:()=>b(y),onMouseDown:z=>R(z,y.id),children:j?s.jsx("input",{ref:f,type:"text",value:l,onChange:z=>p(z.target.value),onBlur:m,onKeyDown:S,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",L>0&&`(${L})`]}),C&&s.jsx("button",{className:"tab-item__close",onClick:z=>w(z,y.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},y.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});nt.displayName="TabBar";function nr(){return localStorage.getItem("ai-cli-online-token")}function rr(){const t=v(l=>l.token),e=v(l=>l.setToken),n=v(l=>l.tabs),r=v(l=>l.addTab),o=v(l=>l.toggleSidebar),a=v(l=>l.fontSize),c=v(l=>l.setFontSize),i=v(l=>l.tabsLoading);return d.useEffect(()=>{const l=nr();l&&!t&&e(l)},[]),d.useEffect(()=>{t&&!i&&n.filter(l=>l.status==="open").length===0&&r("Default")},[t,i]),t?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(a-1),disabled:a<=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:a}),s.jsx("button",{className:"header-btn",onClick:()=>c(a+1),disabled:a>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(sr,{}),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?")&&e(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Yn,{})}),s.jsx(tr,{})]}),s.jsx(nt,{})]}):s.jsx(tn,{})}const or=[1,2,3,4];function sr(){const t=v(r=>r.latency);if(t===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let e,n;return t<50?(e="#9ece6a",n=4):t<150?(e="#e0af68",n=3):t<300?(e="#ff9e64",n=2):(e="#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: ${t}ms`,children:[or.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?e:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[t,"ms"]})]})}be.createRoot(document.getElementById("root")).render(s.jsx(ge.StrictMode,{children:s.jsx(et,{children:s.jsx(rr,{})})}));
|
package/web/dist/index.html
CHANGED
|
@@ -6,9 +6,8 @@
|
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<!-- Fonts loaded locally from /fonts/ -->
|
|
8
8
|
<title>AI-Cli Online</title>
|
|
9
|
-
<link rel="preload" href="/fonts/MapleMono-CN-Regular.woff2" as="font" type="font/woff2" crossorigin />
|
|
10
9
|
<link rel="preload" href="/fonts/JetBrainsMono-Regular.woff2" as="font" type="font/woff2" crossorigin />
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-UW3BpUWL.js"></script>
|
|
12
11
|
<link rel="modulepreload" crossorigin href="/assets/react-vendor-BCIvbQoU.js">
|
|
13
12
|
<link rel="modulepreload" crossorigin href="/assets/terminal-CFozNkMS.js">
|
|
14
13
|
<link rel="modulepreload" crossorigin href="/assets/markdown-BERZKN_L.js">
|
package/web/package.json
CHANGED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
var st=Object.defineProperty;var it=(t,e,n)=>e in t?st(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Se=(t,e,n)=>it(t,typeof e!="symbol"?e+"":e,n);import{r as d,a as at,g as lt,R as ye}from"./react-vendor-BCIvbQoU.js";import{D as Pe,o as Fe,x as ct}from"./terminal-CFozNkMS.js";import{d as dt,p as ut}from"./markdown-BERZKN_L.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();var Be={exports:{}},ce={};/**
|
|
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 ft=d,pt=Symbol.for("react.element"),mt=Symbol.for("react.fragment"),ht=Object.prototype.hasOwnProperty,xt=ft.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,bt={key:!0,ref:!0,__self:!0,__source:!0};function We(t,e,n){var r,o={},a=null,c=null;n!==void 0&&(a=""+n),e.key!==void 0&&(a=""+e.key),e.ref!==void 0&&(c=e.ref);for(r in e)ht.call(e,r)&&!bt.hasOwnProperty(r)&&(o[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)o[r]===void 0&&(o[r]=e[r]);return{$$typeof:pt,type:t,key:a,ref:c,props:o,_owner:xt.current}}ce.Fragment=mt;ce.jsx=We;ce.jsxs=We;Be.exports=ce;var s=Be.exports,xe={},Te=at;xe.createRoot=Te.createRoot,xe.hydrateRoot=Te.hydrateRoot;const yt={},ke=t=>{let e;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(e):u;if(!Object.is(m,e)){const h=e;e=f??(typeof m!="object"||m===null)?m:Object.assign({},e,m),n.forEach(x=>x(e,h))}},o=()=>e,l={setState:r,getState:o,getInitialState:()=>p,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{n.clear()}},p=e=t(r,o,l);return l},gt=t=>t?ke(t):ke;var Ue={exports:{}},He={},Ve={exports:{}},Ge={};/**
|
|
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 te=d;function wt(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var vt=typeof Object.is=="function"?Object.is:wt,St=te.useState,Tt=te.useEffect,kt=te.useLayoutEffect,It=te.useDebugValue;function Ct(t,e){var n=e(),r=St({inst:{value:n,getSnapshot:e}}),o=r[0].inst,a=r[1];return kt(function(){o.value=n,o.getSnapshot=e,me(o)&&a({inst:o})},[t,n,e]),Tt(function(){return me(o)&&a({inst:o}),t(function(){me(o)&&a({inst:o})})},[t]),It(n),n}function me(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!vt(t,n)}catch{return!0}}function jt(t,e){return e()}var Et=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?jt:Ct;Ge.useSyncExternalStore=te.useSyncExternalStore!==void 0?te.useSyncExternalStore:Et;Ve.exports=Ge;var Rt=Ve.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 de=d,Lt=Rt;function zt(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var Dt=typeof Object.is=="function"?Object.is:zt,Mt=Lt.useSyncExternalStore,Nt=de.useRef,_t=de.useEffect,At=de.useMemo,Ot=de.useDebugValue;He.useSyncExternalStoreWithSelector=function(t,e,n,r,o){var a=Nt(null);if(a.current===null){var c={hasValue:!1,value:null};a.current=c}else c=a.current;a=At(function(){function l(h){if(!p){if(p=!0,u=h,h=r(h),o!==void 0&&c.hasValue){var x=c.value;if(o(x,h))return f=x}return f=h}if(x=f,Dt(u,h))return x;var w=r(h);return o!==void 0&&o(x,w)?(u=h,x):(u=h,f=w)}var p=!1,u,f,m=n===void 0?null:n;return[function(){return l(e())},m===null?void 0:function(){return l(m())}]},[e,n,r,o]);var i=Mt(t,a[0],a[1]);return _t(function(){c.hasValue=!0,c.value=i},[i]),Ot(i),i};Ue.exports=He;var $t=Ue.exports;const Pt=lt($t),qe={},{useDebugValue:Ft}=ye,{useSyncExternalStoreWithSelector:Bt}=Pt;let Ie=!1;const Wt=t=>t;function Ut(t,e=Wt,n){(qe?"production":void 0)!=="production"&&n&&!Ie&&(Ie=!0);const r=Bt(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return Ft(r),r}const Ce=t=>{const e=typeof t=="function"?gt(t):t,n=(r,o)=>Ut(e,r,o);return Object.assign(n,e),n},Ht=t=>t?Ce(t):Ce,P="";function U(t){return{Authorization:`Bearer ${t}`}}async function Vt(t){try{const e=await fetch(`${P}/api/settings/font-size`,{headers:U(t)});return e.ok?(await e.json()).fontSize:14}catch{return 14}}async function Gt(t,e){try{await fetch(`${P}/api/settings/font-size`,{method:"PUT",headers:{...U(t),"Content-Type":"application/json"},body:JSON.stringify({fontSize:e})})}catch{}}async function qt(t){try{const e=await fetch(`${P}/api/settings/tabs-layout`,{headers:U(t)});return e.ok?(await e.json()).layout:null}catch{return null}}async function Jt(t,e){try{await fetch(`${P}/api/settings/tabs-layout`,{method:"PUT",headers:{...U(t),"Content-Type":"application/json"},body:JSON.stringify({layout:e})})}catch{}}function je(t,e){try{const n=`${P}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:t});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const le="ai-cli-online-tabs",Ee="ai-cli-online-layout",Re="ai-cli-online-session-names";function oe(t,e){if(t.type==="leaf")return t.terminalId===e?null:t;const n=[],r=[];for(let c=0;c<t.children.length;c++){const i=oe(t.children[c],e);i!==null&&(n.push(i),r.push(t.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,i)=>c+i,0),a=r.map(c=>c/o*100);return{...t,children:n,sizes:a}}function Je(t,e,n,r,o){return t.type==="leaf"?t.terminalId===e?{id:o,type:"split",direction:n,children:[t,r],sizes:[50,50]}:t:{...t,children:t.children.map(a=>Je(a,e,n,r,o))}}function Ke(t,e,n){return t.type==="leaf"?t:t.id===e?{...t,sizes:n}:{...t,children:t.children.map(r=>Ke(r,e,n))}}function he(t){return t.tabs.find(e=>e.id===t.activeTabId)}function X(t,e,n){return t.map(r=>r.id===e?n(r):r)}function V(t){const e={version:2,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId,tabs:t.tabs};try{localStorage.setItem(le,JSON.stringify(e))}catch{}Kt(e)}let se=null,ie=null,Z=null,ne=null;function Kt(t){ne=t,Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,ne=null;const e=v.getState().token;e&&Jt(e,t)},2e3)}function Yt(t){se&&clearTimeout(se),se=setTimeout(()=>{se=null,V(t)},500)}function Xt(){try{const t=localStorage.getItem(le);if(t){const e=JSON.parse(t);if(e.version===2)return e}}catch{}try{const t=localStorage.getItem(Ee);if(t){const e=JSON.parse(t);let n="Default";try{const a=localStorage.getItem(Re);if(a){const c=JSON.parse(a),i=Object.values(c)[0];i&&(n=i)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(le,JSON.stringify(o))}catch{}return localStorage.removeItem(Ee),localStorage.removeItem(Re),o}}catch{}return null}function W(t){return{tabs:t.tabs,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId}}function Zt(t,e){const n=new Set(e.map(c=>c.sessionId)),r=[];for(const c of t.tabs){if(c.status!=="open"){const p=c.terminalIds.filter(u=>n.has(u));if(p.length>0){let u=c.layout;for(const f of c.terminalIds)!n.has(f)&&u&&(u=oe(u,f));r.push({...c,terminalIds:p,layout:u})}continue}const i=c.terminalIds.filter(p=>n.has(p));if(i.length===0)continue;let l=c.layout;for(const p of c.terminalIds)!n.has(p)&&l&&(l=oe(l,p));r.push({...c,terminalIds:i,layout:l})}if(r.filter(c=>c.status==="open").length===0)return null;let o=t.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(i=>i.status==="open");o=(c==null?void 0:c.id)||""}return{...t,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var e,n;const t=(n=(e=v==null?void 0:v.getState)==null?void 0:e.call(v))==null?void 0:n.token;if(t)if(ne)Z&&(clearTimeout(Z),Z=null),je(t,ne),ne=null;else{const r=v.getState();r.tabs.length>0&&je(t,W(r))}});const v=Ht((t,e)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Vt(n).then(o=>{e().token===n&&t({fontSize:o})});const r=Xt();if(r&&r.tabs.length>0){const o={};for(const i of r.tabs)if(i.status==="open")for(const l of i.terminalIds)o[l]={id:l,connected:!1,sessionResumed:!1,error:null};const a=r.tabs.find(i=>i.id===r.activeTabId&&i.status==="open")||r.tabs.find(i=>i.status==="open"),c=(a==null?void 0:a.id)||"";t({token:n,tabsLoading:!0,terminalsMap:o,tabs:r.tabs,activeTabId:c,nextId:r.nextId,nextSplitId:r.nextSplitId,nextTabId:r.nextTabId,terminalIds:(a==null?void 0:a.terminalIds)||[],layout:(a==null?void 0:a.layout)||null})}else t({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Qt(n,r);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(le),t({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=e(),o=`tab${r.nextTabId}`,a=`t${r.nextId}`,c={id:a,connected:!1,sessionResumed:!1,error:null},i={type:"leaf",terminalId:a},l={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[a],layout:i,createdAt:Date.now()};return t({tabs:[...r.tabs,l],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[a]:c},terminalIds:l.terminalIds,layout:l.layout}),V(W(e())),o},switchTab:n=>{const o=e().tabs.find(a=>a.id===n);!o||o.status!=="open"||(t({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),V(W(e())))},closeTab:n=>{const r=e(),o=r.tabs.find(f=>f.id===n);if(!o||o.status!=="open"||r.tabs.filter(f=>f.status==="open").length<=1)return;const c={...r.terminalsMap};for(const f of o.terminalIds)delete c[f];const i=X(r.tabs,n,f=>({...f,status:"closed"}));let l=r.activeTabId,p=r.terminalIds,u=r.layout;if(r.activeTabId===n){const f=r.tabs.findIndex(x=>x.id===n),m=i.filter(x=>x.status==="open"),h=m.find(x=>i.findIndex(k=>k.id===x.id)>f)||m[m.length-1];h&&(l=h.id,p=h.terminalIds,u=h.layout)}t({tabs:i,activeTabId:l,terminalsMap:c,terminalIds:p,layout:u}),V(W(e()))},reopenTab:n=>{const r=e(),o=r.tabs.find(i=>i.id===n);if(!o||o.status!=="closed")return;const a={...r.terminalsMap};for(const i of o.terminalIds)a[i]={id:i,connected:!1,sessionResumed:!1,error:null};const c=X(r.tabs,n,i=>({...i,status:"open"}));t({tabs:c,activeTabId:n,terminalsMap:a,terminalIds:o.terminalIds,layout:o.layout}),V(W(e()))},deleteTab:async n=>{const r=e(),o=r.tabs.find(h=>h.id===n);if(!o)return;const a=r.token;a&&await Promise.all(o.terminalIds.map(h=>fetch(`${P}/api/sessions/${encodeURIComponent(h)}`,{method:"DELETE",headers:U(a)}).catch(()=>{})));const c=e(),i=c.tabs.find(h=>h.id===n);if(!i)return;const l={...c.terminalsMap};for(const h of i.terminalIds)delete l[h];const p=c.tabs.filter(h=>h.id!==n);let u=c.activeTabId,f=c.terminalIds,m=c.layout;if(c.activeTabId===n){const h=p.find(x=>x.status==="open");h?(u=h.id,f=h.terminalIds,m=h.layout):(u="",f=[],m=null)}t({tabs:p,activeTabId:u,terminalsMap:l,terminalIds:f,layout:m}),V(W(e())),setTimeout(()=>e().fetchSessions(),500)},renameTab:(n,r)=>{const o=X(e().tabs,n,a=>({...a,name:r}));t({tabs:o}),V(W(e()))},addTerminal:(n,r)=>{const o=e();if(r&&o.terminalsMap[r])return r;const a=he(o);if(!a){const I=`tab${o.nextTabId}`,R=r||`t${o.nextId}`;let z=o.nextId;const E=R.match(/^t(\d+)$/);E&&(z=Math.max(z,parseInt(E[1],10)+1));const b=r?z:z+1,L={id:R,connected:!1,sessionResumed:!1,error:null},D={type:"leaf",terminalId:R},O={id:I,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[R],layout:D,createdAt:Date.now()};return t({tabs:[...o.tabs,O],activeTabId:I,nextTabId:o.nextTabId+1,nextId:b,terminalsMap:{...o.terminalsMap,[R]:L},terminalIds:[R],layout:D}),V(W(e())),R}const{nextId:c,nextSplitId:i,terminalsMap:l}=o,{terminalIds:p,layout:u}=a,f=r||`t${c}`;let m=c;const h=f.match(/^t(\d+)$/);h&&(m=Math.max(m,parseInt(h[1],10)+1));const x={id:f,connected:!1,sessionResumed:!1,error:null},w={type:"leaf",terminalId:f};let k,S=i;if(!u)k=w;else if(u.type==="leaf"){const I=n||"horizontal";k={id:`s${S}`,type:"split",direction:I,children:[u,w],sizes:[50,50]},S++}else if(u.direction===(n||"horizontal")){const R=100/(u.children.length+1),z=(100-R)/100,E=[...u.sizes.map(b=>b*z),R];k={...u,children:[...u.children,w],sizes:E}}else{const I=n||"horizontal";k={id:`s${S}`,type:"split",direction:I,children:[u,w],sizes:[50,50]},S++}const M=[...p,f],j=r?m:m+1,y=X(o.tabs,a.id,I=>({...I,terminalIds:M,layout:k}));return t({terminalsMap:{...l,[f]:x},terminalIds:M,layout:k,tabs:y,nextId:j,nextSplitId:S}),V(W(e())),f},splitTerminal:(n,r)=>{const o=e(),a=he(o);if(!a||!a.layout)return"";const{nextId:c,nextSplitId:i,terminalsMap:l}=o,p=`t${c}`,u={id:p,connected:!1,sessionResumed:!1,error:null},f={type:"leaf",terminalId:p},m=`s${i}`,h=Je(a.layout,n,r,f,m),x=[...a.terminalIds,p],w=c+1,k=i+1,S=X(o.tabs,a.id,M=>({...M,terminalIds:x,layout:h}));return t({terminalsMap:{...l,[p]:u},terminalIds:x,layout:h,tabs:S,nextId:w,nextSplitId:k}),V(W(e())),p},removeTerminal:n=>{const r=e(),o=r.tabs.find(u=>u.terminalIds.includes(n));if(!o){const{[n]:u,...f}=r.terminalsMap;t({terminalsMap:f});return}const a=o.terminalIds.filter(u=>u!==n),c=o.layout?oe(o.layout,n):null,i=X(r.tabs,o.id,u=>({...u,terminalIds:a,layout:c})),{[n]:l,...p}=r.terminalsMap;o.id===r.activeTabId?t({terminalsMap:p,terminalIds:a,layout:c,tabs:i}):t({terminalsMap:p,tabs:i}),V(W(e()))},setTerminalConnected:(n,r)=>{t(o=>{const a=o.terminalsMap[n];return!a||a.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,connected:r}}}})},setTerminalResumed:(n,r)=>{t(o=>{const a=o.terminalsMap[n];return!a||a.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,sessionResumed:r}}}})},setTerminalError:(n,r)=>{t(o=>{const a=o.terminalsMap[n];return!a||a.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,error:r}}}})},setSplitSizes:(n,r)=>{const o=e(),a=he(o);if(!a||!a.layout)return;const c=Ke(a.layout,n,r),i=X(o.tabs,a.id,l=>({...l,layout:c}));t({layout:c,tabs:i}),Yt(W(e()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));t({fontSize:r}),ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null;const o=e().token;o&&Gt(o,r)},500)},latency:null,setLatency:n=>t({latency:n}),sidebarOpen:!1,toggleSidebar:()=>t(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=e().token;if(n)try{const r=await fetch(`${P}/api/sessions`,{headers:U(n)});if(!r.ok)return;const o=await r.json();t({serverSessions:o})}catch{}},killServerSession:async n=>{const r=e().token;if(!r)return;try{await fetch(`${P}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:U(r)})}catch{}const o=e(),a=o.tabs.find(c=>c.terminalIds.includes(n));if(a){const c=a.terminalIds.filter(f=>f!==n),i=a.layout?oe(a.layout,n):null,l=X(o.tabs,a.id,f=>({...f,terminalIds:c,layout:i})),{[n]:p,...u}=o.terminalsMap;a.id===o.activeTabId?t({terminalsMap:u,terminalIds:c,layout:i,tabs:l}):t({terminalsMap:u,tabs:l}),V(W(e()))}else{const{[n]:c,...i}=o.terminalsMap;t({terminalsMap:i})}setTimeout(()=>e().fetchSessions(),500)}}));async function Qt(t,e){var o;const{setState:n,getState:r}=v;try{const[a,c]=await Promise.all([qt(t),fetch(`${P}/api/sessions`,{headers:U(t)}).then(m=>m.ok?m.json():[]).catch(()=>[])]);if(r().token!==t)return;const i=a&&((o=a.tabs)==null?void 0:o.length)>0?a:e;if(!i||i.tabs.length===0){n({tabsLoading:!1});return}const l=Zt(i,c);if(!l){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:[],layout:null});return}const p={};for(const m of l.tabs)if(m.status==="open")for(const h of m.terminalIds)p[h]={id:h,connected:!1,sessionResumed:!1,error:null};const u=l.tabs.find(m=>m.id===l.activeTabId&&m.status==="open")||l.tabs.find(m=>m.status==="open"),f=(u==null?void 0:u.id)||"";n({tabsLoading:!1,terminalsMap:p,tabs:l.tabs,activeTabId:f,nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null}),V(W(r()))}catch{r().token===t&&n({tabsLoading:!1})}}function en(){const[t,e]=d.useState(""),n=v(o=>o.setToken),r=o=>{o.preventDefault(),t.trim()&&n(t.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:t,onChange:o=>e(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:!t.trim(),style:{width:"100%",padding:"11px",background:t.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:t.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:t.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#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"})]})})]})})}/**
|
|
26
|
-
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
|
|
27
|
-
* @license MIT
|
|
28
|
-
*
|
|
29
|
-
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
|
30
|
-
* @license MIT
|
|
31
|
-
*
|
|
32
|
-
* Originally forked from (with the author's permission):
|
|
33
|
-
* Fabrice Bellard's javascript vt100 for jslinux:
|
|
34
|
-
* http://bellard.org/jslinux/
|
|
35
|
-
* Copyright (c) 2011 Fabrice Bellard
|
|
36
|
-
*/var tn=class{constructor(t,e,n,r={}){this._terminal=t,this._regex=e,this._handler=n,this._options=r}provideLinks(t,e){let n=rn.computeLink(t,this._regex,this._terminal,this._handler);e(this._addCallbacks(n))}_addCallbacks(t){return t.map(e=>(e.leave=this._options.leave,e.hover=(n,r)=>{if(this._options.hover){let{range:o}=e;this._options.hover(n,r,o)}},e))}};function nn(t){try{let e=new URL(t),n=e.password&&e.username?`${e.protocol}//${e.username}:${e.password}@${e.host}`:e.username?`${e.protocol}//${e.username}@${e.host}`:`${e.protocol}//${e.host}`;return t.toLocaleLowerCase().startsWith(n.toLocaleLowerCase())}catch{return!1}}var rn=class ae{static computeLink(e,n,r,o){let a=new RegExp(n.source,(n.flags||"")+"g"),[c,i]=ae._getWindowedLineStrings(e-1,r),l=c.join(""),p,u=[];for(;p=a.exec(l);){let f=p[0];if(!nn(f))continue;let[m,h]=ae._mapStrIdx(r,i,0,p.index),[x,w]=ae._mapStrIdx(r,m,h,f.length);if(m===-1||h===-1||x===-1||w===-1)continue;let k={start:{x:h+1,y:m+1},end:{x:w,y:x+1}};u.push({range:k,text:f,activate:o})}return u}static _getWindowedLineStrings(e,n){let r,o=e,a=e,c=0,i="",l=[];if(r=n.buffer.active.getLine(e)){let p=r.translateToString(!0);if(r.isWrapped&&p[0]!==" "){for(c=0;(r=n.buffer.active.getLine(--o))&&c<2048&&(i=r.translateToString(!0),c+=i.length,l.push(i),!(!r.isWrapped||i.indexOf(" ")!==-1)););l.reverse()}for(l.push(p),c=0;(r=n.buffer.active.getLine(++a))&&r.isWrapped&&c<2048&&(i=r.translateToString(!0),c+=i.length,l.push(i),i.indexOf(" ")===-1););}return[l,o]}static _mapStrIdx(e,n,r,o){let a=e.buffer.active,c=a.getNullCell(),i=r;for(;o;){let l=a.getLine(n);if(!l)return[-1,-1];for(let p=i;p<l.length;++p){l.getCell(p,c);let u=c.getChars();if(c.getWidth()&&(o-=u.length||1,p===l.length-1&&u==="")){let f=a.getLine(n+1);f&&f.isWrapped&&(f.getCell(0,c),c.getWidth()===2&&(o+=1))}if(o<0)return[n,p]}n++,i=0}return[n,i]}},on=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function sn(t,e){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=e}}var an=class{constructor(t=sn,e={}){this._handler=t,this._options=e}activate(t){this._terminal=t;let e=this._options,n=e.urlRegex||on;this._linkProvider=this._terminal.registerLinkProvider(new tn(this._terminal,n,this._handler,e))}dispose(){var t;(t=this._linkProvider)==null||t.dispose()}};const ln=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,Le=500,cn=15e3,dn=15e3,un=5e3,fn=1e4,pn=5,mn=64*1024,hn=1,ze=2,xn=3,bn=4,yn=new TextDecoder,gn=new TextEncoder;function De(t,e){const n=gn.encode(e),r=new Uint8Array(1+n.length);return r[0]=t,r.set(n,1),r.buffer}function wn(t,e,n){const r=d.useRef(null),o=d.useRef(Le),a=d.useRef(null),c=d.useRef(null),i=d.useRef(null),l=d.useRef(null),p=d.useRef(!1),u=d.useRef(n),f=d.useRef(!1),m=d.useRef(0),h=d.useRef(""),x=d.useRef(null),w=d.useRef("");u.current=n;const k=d.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),i.current&&(clearTimeout(i.current),i.current=null),a.current&&(clearTimeout(a.current),a.current=null),l.current&&(clearTimeout(l.current),l.current=null),x.current&&(clearTimeout(x.current),x.current=null)},[]),S=d.useCallback(()=>{const{token:I,setTerminalError:R}=v.getState();if(!I||p.current)return;if(r.current){const L=r.current.readyState;if(L===WebSocket.OPEN||L===WebSocket.CONNECTING)return}f.current=!1;const z=`${ln}?sessionId=${encodeURIComponent(e)}`,E=new WebSocket(z);E.binaryType="arraybuffer",l.current=window.setTimeout(()=>{E.readyState===WebSocket.CONNECTING&&E.close()},fn);const b=()=>{E.readyState===WebSocket.OPEN&&(m.current=performance.now(),E.send(JSON.stringify({type:"ping"})),i.current=window.setTimeout(()=>{m.current>0&&(m.current=0,E.close())},un))};E.onopen=()=>{l.current&&(clearTimeout(l.current),l.current=null),E.send(JSON.stringify({type:"auth",token:I})),R(e,null),o.current=Le},E.onclose=L=>{const{setTerminalConnected:D,setTerminalError:O,setToken:F}=v.getState();if(D(e,!1),k(),f.current)return;if(L.code===4001){p.current=!0,O(e,"Authentication failed"),F(null),localStorage.removeItem("ai-cli-online-token");return}if(L.code===4002)return;if(L.code===4005){O(e,"Connection limit reached");return}const N=o.current;o.current=Math.min(N*2,cn);const C=Math.round(N*(.5+Math.random()));a.current=window.setTimeout(()=>{S()},C)},E.onerror=()=>{},E.onmessage=L=>{var D;try{const O=t.current;if(L.data instanceof ArrayBuffer){const N=new Uint8Array(L.data);if(N.length<1)return;const C=N[0],A=N.subarray(1);switch(C){case hn:O==null||O.write(A);break;case xn:O==null||O.write(A);break;case bn:{(D=u.current)==null||D.call(u,yn.decode(A));break}}return}const F=JSON.parse(L.data);switch(F.type){case"connected":{const N=v.getState();N.setTerminalConnected(e,!0),N.setTerminalResumed(e,F.resumed);const C=t.current;C&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"resize",cols:C.cols,rows:C.rows})),w.current&&(E.send(De(ze,w.current)),w.current=""),b(),c.current=window.setInterval(b,dn);break}case"error":v.getState().setTerminalError(e,F.error);break;case"pong":{if(i.current&&(clearTimeout(i.current),i.current=null),m.current>0){const N=Math.round(performance.now()-m.current),C=v.getState();(C.terminalIds.length===0||C.terminalIds[0]===e)&&C.setLatency(N),m.current=0}break}}}catch{}},r.current=E},[e,t,k]),M=d.useCallback(I=>{const R=r.current;if(!R||R.readyState!==WebSocket.OPEN){w.current.length<mn&&(w.current+=I);return}h.current+=I,x.current||(x.current=window.setTimeout(()=>{const z=h.current;h.current="",x.current=null,z&&R.readyState===WebSocket.OPEN&&R.send(De(ze,z))},pn))},[]),j=d.useCallback((I,R)=>{var z;((z=r.current)==null?void 0:z.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:I,rows:R}))},[]),y=d.useCallback(()=>{var I;((I=r.current)==null?void 0:I.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]);return d.useEffect(()=>(v.getState().token&&(p.current=!1,S()),()=>{f.current=!0,k(),r.current&&(r.current.close(),r.current=null)}),[S,k]),{sendInput:M,sendResize:j,requestScrollback:y}}const Ye={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"},Xe="'Maple Mono CN', 'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",vn=d.forwardRef(function({sessionId:e},n){const r=d.useRef(null),o=d.useRef(null),a=d.useRef(null),[c,i]=d.useState(!1),[l,p]=d.useState(""),u=v(S=>S.fontSize),f=d.useCallback(S=>{p(S),i(!0)},[]),{sendInput:m,sendResize:h,requestScrollback:x}=wn(o,e,f);d.useImperativeHandle(n,()=>({sendInput:m}),[m]);const w=d.useRef(m),k=d.useRef(h);return w.current=m,k.current=h,d.useEffect(()=>{if(!r.current)return;let S=!1,M=null,j=null,y=null,I=null;const R=()=>{if(S||!r.current)return;const z=new Pe({cursorBlink:!0,scrollback:1e4,fontSize:v.getState().fontSize,fontFamily:Xe,theme:Ye,allowProposedApi:!0}),E=new Fe;z.loadAddon(E),z.loadAddon(new an((D,O)=>{window.open(O,"_blank","noopener,noreferrer")})),z.open(r.current);try{const D=new ct;D.onContextLoss(()=>{D.dispose()}),z.loadAddon(D)}catch{}o.current=z,a.current=E;const b=()=>{try{const D=r.current;if(D&&D.clientWidth>0&&D.clientHeight>0)return E.fit(),k.current(z.cols,z.rows),!0}catch{}return!1};requestAnimationFrame(()=>b());let L=0;M=setInterval(()=>{L++,(b()||L>=10)&&(clearInterval(M),M=null)},100),z.onData(D=>{w.current(D)}),I=new ResizeObserver(()=>{j||(j=requestAnimationFrame(()=>{j=null;try{E.fit(),y&&clearTimeout(y),y=setTimeout(()=>{y=null,k.current(z.cols,z.rows)},50)}catch{}}))}),I.observe(r.current)};return document.fonts.ready.then(R),()=>{S=!0,M&&clearInterval(M),j&&cancelAnimationFrame(j),y&&clearTimeout(y),I&&I.disconnect(),o.current&&(o.current.dispose(),o.current=null),a.current=null}},[e]),d.useEffect(()=>{const S=o.current,M=a.current;if(!(!S||!M)&&S.options.fontSize!==u){S.options.fontSize=u;try{M.fit()}catch{}k.current(S.cols,S.rows)}},[u]),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",{onClick:()=>{c?(i(!1),p("")):x()},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:12,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:S=>{S.currentTarget.style.opacity="1"},onMouseLeave:S=>{S.currentTarget.style.opacity="0.8"},children:c?"✕":"↑"}),c&&s.jsx(Sn,{data:l,onClose:()=>{i(!1),p("")}})]})});function Sn({data:t,onClose:e}){const n=d.useRef(null),r=d.useRef(e);r.current=e;const o=v(i=>i.fontSize),a=d.useRef(null),c=d.useRef(null);return d.useEffect(()=>{if(!n.current)return;const i=new Pe({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:Xe,theme:Ye});a.current=i;const l=new Fe;c.current=l,i.loadAddon(l),i.open(n.current),requestAnimationFrame(()=>{try{l.fit()}catch{}i.write(t,()=>{i.scrollToBottom()})});let p=null;const u=new ResizeObserver(()=>{p||(p=requestAnimationFrame(()=>{p=null;try{l.fit()}catch{}}))});u.observe(n.current);const f=m=>{m.key==="Escape"&&r.current()};return document.addEventListener("keydown",f),()=>{p&&cancelAnimationFrame(p),document.removeEventListener("keydown",f),u.disconnect(),i.dispose(),a.current=null,c.current=null}},[t]),d.useEffect(()=>{var i;if(a.current){a.current.options.fontSize=o;try{(i=c.current)==null||i.fit()}catch{}}},[o]),s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column"},children:[s.jsx("div",{style:{padding:"4px 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{flex:1,overflow:"hidden"}})]})}async function re(t,e,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/files${r}`,{headers:U(t)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function Tn(t,e,n,r){return new Promise((o,a)=>{const c=new FormData;for(const l of n)c.append("files",l);const i=new XMLHttpRequest;i.open("POST",`${P}/api/sessions/${encodeURIComponent(e)}/upload`),i.setRequestHeader("Authorization",`Bearer ${t}`),i.upload.addEventListener("progress",l=>{l.lengthComputable&&r&&r(Math.round(l.loaded/l.total*100))}),i.addEventListener("load",()=>{i.status>=200&&i.status<300?o():a(new Error(`Upload failed: ${i.status}`))}),i.addEventListener("error",()=>a(new Error("Upload network error"))),i.addEventListener("abort",()=>a(new Error("Upload aborted"))),i.send(c)})}async function kn(t,e){const n=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/cwd`,{headers:U(t)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function In(t,e,n){const r=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/download?path=${encodeURIComponent(n)}`,{headers:U(t)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),a=URL.createObjectURL(o),c=document.createElement("a");c.href=a,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(a)}function ge({sessionId:t,onClose:e,filter:n,pollCwd:r}){const o=v(j=>j.token),[a,c]=d.useState(""),[i,l]=d.useState([]),[p,u]=d.useState(!0),[f,m]=d.useState(null),h=d.useRef(""),x=d.useCallback(async j=>{if(o){u(!0),m(null);try{const y=await re(o,t,j);j||(h.current=y.cwd),c(y.cwd),l(n?n(y.files):y.files)}catch(y){m(y instanceof Error?y.message:"Failed to load files")}finally{u(!1)}}},[o,t,n]);d.useEffect(()=>{x()},[x]),d.useEffect(()=>{if(!r||!o)return;let j=!1;const y=setInterval(async()=>{if(!j)try{const I=await kn(o,t);if(j)return;if(I!==h.current){h.current=I;const R=await re(o,t);if(j)return;c(R.cwd),l(n?n(R.files):R.files)}}catch{}},r);return()=>{j=!0,clearInterval(y)}},[r,o,t,n]);const w=d.useRef(e);w.current=e,d.useEffect(()=>{const j=y=>{y.key==="Escape"&&w.current()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[]);const k=d.useCallback(j=>{x(a+"/"+j)},[x,a]),S=d.useCallback(()=>{const j=a.replace(/\/[^/]+$/,"")||"/";x(j)},[x,a]),M=d.useCallback(()=>{x(a)},[x,a]);return{cwd:a,files:i,loading:p,error:f,setError:m,handleNavigate:k,handleGoUp:S,handleRefresh:M}}function Cn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function Ze(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function we({cwd:t,onGoUp:e,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:e,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:t||"..."})]}),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 ve({loading:t,error:e,empty:n,emptyText:r="Empty directory"}){return t?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):e?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:e}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function jn({sessionId:t,onClose:e}){const n=v(x=>x.token),{cwd:r,files:o,loading:a,error:c,setError:i,handleNavigate:l,handleGoUp:p,handleRefresh:u}=ge({sessionId:t,onClose:e}),[f,m]=d.useState(null),h=async x=>{if(n){m(x);try{await In(n,t,r+"/"+x)}catch(w){i(w instanceof Error?w.message:"Download failed")}finally{m(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(we,{cwd:r,onGoUp:p,onRefresh:u,onClose:e}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(ve,{loading:a,error:c,empty:o.length===0,emptyText:"Empty directory"}),!a&&!c&&o.map(x=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:x.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="transparent"},onClick:()=>{x.type==="directory"&&l(x.name)},children:[x.type==="file"?s.jsx("button",{onClick:w=>{w.stopPropagation(),h(x.name)},disabled:f===x.name,style:{background:"none",border:"1px solid #414868",color:f===x.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:f===x.name?"wait":"pointer",flexShrink:0,marginRight:6},children:f===x.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:x.type==="directory"?"#7aa2f7":"#565f89"},children:x.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:x.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:x.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:x.type==="file"?Cn(x.size):""})]},x.name))]})]})}function En({content:t}){const e=v(r=>r.fontSize),n=d.useMemo(()=>{if(!t)return"";const r=dt.parse(t,{async:!1});return ut.sanitize(r,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[t]);return t?s.jsx("div",{className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${e}px`},dangerouslySetInnerHTML:{__html:n}}):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 Rn(t,e){const n=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/draft`,{headers:U(t)});return n.ok?(await n.json()).content??"":""}async function Me(t,e,n){await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/draft`,{method:"PUT",headers:{...U(t),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const Ne=[{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"}],Ln=d.forwardRef(function({onSend:e,onContentChange:n,sessionId:r,token:o},a){const c=v(g=>g.fontSize),[i,l]=d.useState(""),p=d.useRef(null),u=d.useRef(),f=d.useRef(!1),[m,h]=d.useState(!1),[x,w]=d.useState(""),[k,S]=d.useState(0),[M,j]=d.useState(!1),[y,I]=d.useState(""),[R,z]=d.useState(""),[E,b]=d.useState(0),[L,D]=d.useState([]),[O,F]=d.useState(!1),N=d.useRef(""),C=d.useRef(null),A=d.useMemo(()=>{if(!x)return Ne;const g=x.toLowerCase();return Ne.filter(T=>T.cmd.toLowerCase().includes(g)||T.desc.toLowerCase().includes(g))},[x]),$=d.useMemo(()=>{let g=L;if(y){const T=y.toLowerCase();g=g.filter(_=>_.name.toLowerCase().includes(T))}return[...g].sort((T,_)=>T.type==="directory"&&_.type!=="directory"?-1:T.type!=="directory"&&_.type==="directory"?1:T.name.localeCompare(_.name))},[L,y]);d.useEffect(()=>{let g=!1;return Rn(o,r).then(T=>{!g&&T&&l(T),f.current=!0}).catch(()=>{f.current=!0}),()=>{g=!0}},[o,r]),d.useEffect(()=>{if(f.current)return u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Me(o,r,i).catch(()=>{})},500),()=>{u.current&&clearTimeout(u.current)}},[i,o,r]),d.useEffect(()=>{var g;(g=p.current)==null||g.focus()},[]),d.useEffect(()=>{if(!M)return;let g=!1;return F(!0),(async()=>{try{if(R){if(!N.current){const B=await re(o,r);if(g)return;N.current=B.cwd}const T=`${N.current}/${R.replace(/\/$/,"")}`,_=await re(o,r,T);if(g)return;D(_.files)}else{const T=await re(o,r);if(g)return;N.current=T.cwd,D(T.files)}F(!1)}catch{if(g)return;D([]),F(!1)}})(),()=>{g=!0}},[M,R,o,r]),d.useEffect(()=>{if(!M||!C.current)return;const g=C.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[E,M]);const Y=d.useCallback(()=>{const g=i.trim();g&&(e(g),l(""),Me(o,r,"").catch(()=>{}))},[i,e,o,r]);d.useImperativeHandle(a,()=>({send:Y}),[Y]),d.useEffect(()=>{n==null||n(i.trim().length>0)},[i,n]);const ue=d.useCallback(g=>{const T=p.current;if(!T)return;const _=T.selectionStart,B=i.slice(0,_),J=i.slice(_),q=B.lastIndexOf(`
|
|
37
|
-
`)+1,G=B.slice(q).match(/\/[a-zA-Z-]*$/);if(G){const H=q+(G.index??0),ee=g+" ",pe=i.slice(0,H)+ee+J;l(pe);const ot=H+ee.length;requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=ot,T.focus()})}else{const H=B+g+J;l(H);const ee=_+g.length;requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=ee,T.focus()})}h(!1),w(""),S(0)},[i]),fe=d.useCallback(g=>{const T=p.current;if(!T)return;const _=T.selectionStart,B=i.slice(0,_),J=i.slice(_),Q=B.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!Q)return;const q=B.length-Q[0].length;if(g.type==="directory"){const K="@"+R+g.name+"/",G=i.slice(0,q)+K+J;l(G);const H=q+K.length;z(R+g.name+"/"),I(""),b(0),requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=H,T.focus()})}else{const K=g.name+" ",G=i.slice(0,q)+K+J;l(G);const H=q+K.length;j(!1),I(""),z(""),b(0),D([]),N.current="",requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=H,T.focus()})}},[i,R]),nt=d.useCallback(g=>{const T=g.target.value;l(T);const _=g.target.selectionStart,B=T.slice(0,_),J=B.lastIndexOf(`
|
|
38
|
-
`),q=B.slice(J+1).match(/^\/([a-zA-Z-]*)$/);if(q)h(!0),w(q[1]),S(0),j(!1);else{h(!1);const K=B.match(/@([a-zA-Z0-9_.\-/]*)$/);if(K){const G=K[1],H=G.lastIndexOf("/"),ee=H>=0?G.slice(0,H+1):"",pe=H>=0?G.slice(H+1):G;I(pe),b(0),z(ee),j(!0)}else j(!1)}},[]),rt=d.useCallback(g=>{if(m&&A.length>0){if(g.key==="ArrowDown"){g.preventDefault(),S(T=>(T+1)%A.length);return}if(g.key==="ArrowUp"){g.preventDefault(),S(T=>(T-1+A.length)%A.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),ue(A[k].cmd);return}if(g.key==="Escape"){g.preventDefault(),h(!1);return}}if(M&&$.length>0){if(g.key==="ArrowDown"){g.preventDefault(),b(T=>(T+1)%$.length);return}if(g.key==="ArrowUp"){g.preventDefault(),b(T=>(T-1+$.length)%$.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),fe($[E]);return}if(g.key==="Escape"){g.preventDefault(),j(!1);return}}if(g.key==="Tab"){g.preventDefault();const T=p.current;if(T){const _=T.selectionStart,B=T.selectionEnd,J=i.slice(0,_)+" "+i.slice(B);l(J);const Q=_+2;requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=Q})}return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),Y())},[Y,m,A,k,ue,i,M,$,E,fe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[m&&A.length>0&&s.jsx("div",{className:"slash-dropdown",children:A.map((g,T)=>s.jsxs("div",{className:`slash-item${T===k?" slash-item--active":""}`,onMouseDown:_=>{_.preventDefault(),ue(g.cmd)},onMouseEnter:()=>S(T),children:[s.jsx("span",{className:"slash-cmd",children:g.cmd}),s.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),M&&(O||$.length>0)&&s.jsx("div",{className:"file-dropdown",ref:C,children:O?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):$.map((g,T)=>s.jsxs("div",{className:`file-item${T===E?" file-item--active":""}`,onMouseDown:_=>{_.preventDefault(),fe(g)},onMouseEnter:()=>b(T),children:[s.jsx("span",{className:"file-icon",children:g.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:g.name})]},g.name))}),s.jsx("textarea",{ref:p,className:"md-editor-textarea",value:i,onChange:nt,onKeyDown:rt,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function zn(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function Dn({sessionId:t,onSelect:e,onClose:n}){const{cwd:r,files:o,loading:a,error:c,handleNavigate:i,handleGoUp:l,handleRefresh:p}=ge({sessionId:t,onClose:n}),u=f=>{e(r+"/"+f)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(we,{cwd:r,onGoUp:l,onRefresh:p,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(ve,{loading:a,error:c,empty:o.length===0,emptyText:"No files found"}),!a&&!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"?i(f.name):u(f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:zn(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",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:f.name.slice(f.name.lastIndexOf(".")).toLowerCase()})]},f.name))]})]})}const Mn="modulepreload",Nn=function(t){return"/"+t},_e={},_n=function(e,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),i=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(l=>{if(l=Nn(l),l in _e)return;_e[l]=!0;const p=l.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Mn,p||(f.as="script"),f.crossOrigin="",f.href=l,i&&f.setAttribute("nonce",i),document.head.appendChild(f),p)return new Promise((m,h)=>{f.addEventListener("load",m),f.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${l}`)))})}))}function a(c){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=c,window.dispatchEvent(i),!i.defaultPrevented)throw c}return o.then(c=>{for(const i of c||[])i.status==="rejected"&&a(i.reason);return e().catch(a)})};let be=null;const An=_n(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(t=>(be=t,t.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),t));function On({data:t,scrollRef:e}){const n=d.useRef(null),[r,o]=d.useState(null),[a,c]=d.useState(!0),i=d.useRef(0),l=p=>{n.current=p,e==null||e(p)};return d.useEffect(()=>{if(!t)return;const p=++i.current;return c(!0),o(null),(async()=>{try{if(await An,!be||p!==i.current)return;const u=atob(t),f=new Uint8Array(u.length);for(let w=0;w<u.length;w++)f[w]=u.charCodeAt(w);const m=await be.getDocument({data:f}).promise;if(p!==i.current)return;const h=n.current;if(!h)return;for(;h.firstChild;)h.removeChild(h.firstChild);const x=h.clientWidth-24;for(let w=1;w<=m.numPages;w++){const k=await m.getPage(w);if(p!==i.current)return;const S=k.getViewport({scale:1}),M=Math.min(x/S.width,2),j=k.getViewport({scale:M}),y=document.createElement("canvas");y.width=j.width,y.height=j.height,y.style.display="block",y.style.margin="0 auto 8px",y.style.maxWidth="100%";const I=y.getContext("2d");if(I){if(await k.render({canvasContext:I,viewport:j,canvas:y}).promise,p!==i.current)return;h.appendChild(y)}}c(!1)}catch(u){if(p!==i.current)return;o(u instanceof Error?u.message:"Failed to render PDF"),c(!1)}})(),()=>{i.current++}},[t]),s.jsxs("div",{ref:l,className:"pdf-renderer",children:[a&&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]})]})}async function Ae(t,e,n,r){const o=new URLSearchParams({path:n});r&&o.set("since",String(r));const a=await fetch(`${P}/api/sessions/${encodeURIComponent(e)}/file-content?${o}`,{headers:U(t)});if(a.status===304)return null;if(!a.ok)throw new Error("Failed to fetch file content");return a.json()}function $n(t=50,e=20,n=80){const[r,o]=d.useState(t),a=d.useRef(null),c=d.useCallback(i=>{i.preventDefault();const l=a.current;if(!l)return;const p=l.getBoundingClientRect(),u=p.width;document.body.classList.add("resizing-panes-h");let f=null;const m=x=>{f||(f=requestAnimationFrame(()=>{f=null;const w=x.clientX-p.left,k=Math.min(n,Math.max(e,w/u*100));o(k)}))},h=()=>{f&&cancelAnimationFrame(f),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",h)};document.addEventListener("mousemove",m),document.addEventListener("mouseup",h)},[e,n]);return{leftWidthPercent:r,containerRef:a,onDividerMouseDown:c}}const Pn=3e3;function Fn(t){const e=t.slice(t.lastIndexOf(".")).toLowerCase();return e===".md"?"md":e===".html"||e===".htm"?"html":e===".pdf"?"pdf":"text"}function Oe(t){return t.split("/").pop()||t}function Bn(t){if(t.type==="directory")return"📁";const e=t.name.slice(t.name.lastIndexOf(".")).toLowerCase();return e===".pdf"?"📕":e===".html"||e===".htm"?"🌐":e===".md"?"📝":"📄"}const Wn=3e3;function Un({sessionId:t,onSelect:e}){const n=d.useCallback(()=>{},[]),{cwd:r,files:o,loading:a,error:c,handleNavigate:i,handleGoUp:l,handleRefresh:p}=ge({sessionId:t,onClose:n,pollCwd:Wn});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(we,{cwd:r,onGoUp:l,onRefresh:p,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(ve,{loading:a,error:c,empty:o.length===0,emptyText:"No files found"}),!a&&!c&&o.map(u=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="transparent"},onClick:()=>{u.type==="directory"?i(u.name):e(r+"/"+u.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:u.type==="directory"?"#7aa2f7":"#565f89"},children:Bn(u)}),s.jsx("span",{style:{flex:1,color:u.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:u.name}),u.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:u.name.slice(u.name.lastIndexOf(".")).toLowerCase()})]},u.name))]})]})}function Hn({sessionId:t,token:e,onClose:n,onSend:r}){const[o,a]=d.useState(null),[c,i]=d.useState(""),[l,p]=d.useState(null),u=d.useRef(0),[f,m]=d.useState(!1),[h,x]=d.useState(!1),[w,k]=d.useState(!1),{leftWidthPercent:S,containerRef:M,onDividerMouseDown:j}=$n(50),y=d.useRef(null),[I,R]=d.useState(!1),z=d.useRef(new Map),E=d.useRef(null),b=d.useRef(null),L=d.useCallback(()=>{if(!o)return;const C=h?b.current:E.current;C&&z.current.set(o,C.scrollTop)},[o,h]),D=d.useCallback(C=>{const A=z.current.get(C);A!=null&&requestAnimationFrame(()=>{const $=h?b.current:E.current;$&&($.scrollTop=A)})},[h]),O=d.useCallback(C=>{L();const A=Fn(C);a(C),p(A),i(""),u.current=0,m(!1),Ae(e,t,C).then($=>{$&&(i($.content),u.current=$.mtime,requestAnimationFrame(()=>D(C)))}).catch(()=>{})},[e,t,L,D]);d.useEffect(()=>{if(!o)return;let C=!1;const $=setInterval(async()=>{if(!C)try{const Y=await Ae(e,t,o,u.current);if(C)return;Y&&(i(Y.content),u.current=Y.mtime)}catch{}},Pn);return()=>{C=!0,clearInterval($)}},[e,t,o]);const F=d.useCallback(()=>{o&&navigator.clipboard.writeText(o).then(()=>{k(!0),setTimeout(()=>k(!1),1500)}).catch(()=>{})},[o]);d.useEffect(()=>{if(!h)return;const C=A=>{A.key==="Escape"&&(L(),x(!1))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[h,L]),d.useEffect(()=>{o&&D(o)},[h,o,D]);const N=C=>o?!c&&l!=="pdf"?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:"13px"},children:"Loading..."}):l==="md"?s.jsx("div",{ref:C,style:{height:"100%",overflow:"auto"},children:s.jsx(En,{content:c})}):l==="html"?s.jsx("div",{ref:C,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:c,sandbox:"allow-same-origin",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})}):l==="pdf"?s.jsx(On,{data:c,scrollRef:C}):s.jsx("div",{ref:C,style:{height:"100%",overflow:"auto"},children:s.jsx("pre",{style:{margin:0,padding:"12px",fontFamily:'"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',fontSize:"13px",color:"#a9b1d6",whiteSpace:"pre-wrap",wordBreak:"break-all",lineHeight:1.5},children:c})}):s.jsx(Un,{sessionId:t,onSelect:O});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:"28px",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:()=>m(C=>!C),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),o&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:F,title:w?"Copied!":`Click to copy: ${o}`,children:w?"Copied!":Oe(o)}),s.jsx("button",{className:"pane-btn",onClick:()=>{L(),x(!0)},title:"Expand document view",style:{fontSize:"12px"},children:"⛶"})]})]}),s.jsx("div",{style:{width:"4px",flexShrink:0}}),s.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>{var C;return(C=y.current)==null?void 0:C.send()},disabled:!I,title:"Send to terminal (Ctrl+Enter)",style:I?{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:n,title:"Close Doc panel",children:"×"})]})]}),s.jsxs("div",{ref:M,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${S}%`,flexShrink:0},children:[N(C=>{E.current=C}),f&&s.jsx(Dn,{sessionId:t,onSelect:O,onClose:()=>m(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:j}),s.jsx("div",{className:"plan-editor-wrap",children:s.jsx(Ln,{ref:y,onSend:r,onContentChange:R,sessionId:t,token:e})})]}),h&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsx("span",{style:{fontSize:"12px",color:"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o?Oe(o):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{L(),x(!1)},title:"Close expanded view (ESC)",children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:N(C=>{b.current=C})})]})]})}const Vn=100,Gn=600;function qn(){return d.useSyncExternalStore(t=>(window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)),()=>window.innerWidth)}const Jn=d.memo(function({terminal:e,canClose:n}){const o=qn()<Gn,a=v(b=>b.killServerSession),c=v(b=>b.splitTerminal),i=v(b=>b.token),l=d.useRef(null),p=d.useRef(null),[u,f]=d.useState(!1),[m,h]=d.useState(!1),[x,w]=d.useState(0),[k,S]=d.useState(!1),[M,j]=d.useState(50),y=d.useRef(null),I=async b=>{const L=b.target.files;if(!(!L||L.length===0||!i)){h(!0),w(0);try{await Tn(i,e.id,L,D=>{w(D)})}catch(D){alert(`Upload failed: ${D instanceof Error?D.message:"Unknown error"}`)}finally{h(!1),w(0),l.current&&(l.current.value="")}}},R=d.useRef(),z=d.useCallback(b=>{if(p.current){const L=b.replace(/\r?\n/g," ").trimEnd();p.current.sendInput(L),R.current=window.setTimeout(()=>{var D;return(D=p.current)==null?void 0:D.sendInput("\r")},50)}},[]);d.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]);const E=d.useCallback(b=>{b.preventDefault();const L=y.current;if(!L)return;const D=L.getBoundingClientRect(),O=D.height;document.body.classList.add("resizing-panes-v");const F=C=>{const A=(C.clientY-D.top)/O*100,$=Math.min(80,Math.max(20,A));j(100-$)},N=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",N)};document.addEventListener("mousemove",F),document.addEventListener("mouseup",N)},[]);return s.jsxs("div",{ref:y,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"2px 8px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0,height:"24px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"#9ece6a":"#f7768e"}}),s.jsxs("span",{style:{fontSize:"11px",color:"#565f89"},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:l,type:"file",multiple:!0,style:{display:"none"},onChange:I}),s.jsx("button",{className:"pane-btn",onClick:()=>{var b;return(b=l.current)==null?void 0:b.click()},disabled:m,style:m?{color:"#e0af68"}:void 0,title:m?`Uploading ${x}%`:"Upload files","aria-label":"Upload files",children:m?`${x}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>f(b=>!b),style:u?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${k?" pane-btn--active":""}`,onClick:()=>S(b=>!b),title:"Toggle Document browser","aria-label":"Toggle Document browser",children:"Doc"}),s.jsx("button",{className:"pane-btn",onClick:()=>c(e.id,o?"vertical":"horizontal"),title:o?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>c(e.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"}),n&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>a(e.id),title:"Close terminal","aria-label":"Close terminal",children:"×"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(vn,{ref:p,sessionId:e.id}),!e.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..."})}),u&&s.jsx(jn,{sessionId:e.id,onClose:()=>f(!1)})]}),k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:E}),s.jsx("div",{style:{height:`${M}%`,minHeight:Vn,flexShrink:0,overflow:"hidden"},children:s.jsx(Hn,{onSend:z,onClose:()=>S(!1),sessionId:e.id,token:i||""})})]}),e.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:e.error})]})});class Qe extends d.Component{constructor(){super(...arguments);Se(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 Kn=4,$e=10;function Yn(){const t=v(o=>o.layout),e=v(o=>o.terminalIds.length),n=v(o=>o.addTerminal);if(!t)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=e>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(et,{node:t,canClose:r})})}const et=d.memo(function({node:e,canClose:n}){return e.type==="leaf"?s.jsx(Xn,{terminalId:e.terminalId,canClose:n}):s.jsx(Zn,{node:e,canClose:n})}),Xn=d.memo(function({terminalId:e,canClose:n}){const r=v(o=>o.terminalsMap[e]);return r?s.jsx(Qe,{inline:!0,children:s.jsx(Jn,{terminal:r,canClose:n})}):null}),Zn=d.memo(function({node:e,canClose:n}){const r=v(p=>p.setSplitSizes),o=d.useRef(null),a=e.direction==="horizontal",c=d.useRef(e.sizes);c.current=e.sizes;const i=d.useCallback((p,u)=>{u.preventDefault();const f=a?"resizing-panes":"resizing-panes-v";document.body.classList.add(f);const m=a?u.clientX:u.clientY,h=[...c.current],x=o.current,w=a?(x==null?void 0:x.clientWidth)||1:(x==null?void 0:x.clientHeight)||1;let k=null;const S=j=>{k||(k=requestAnimationFrame(()=>{k=null;const R=((a?j.clientX:j.clientY)-m)/w*100,z=h[p]+R,E=h[p+1]-R;if(z>=$e&&E>=$e){const b=[...h];b[p]=z,b[p+1]=E,r(e.id,b)}}))},M=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(f),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",M)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",M)},[a,e.id,r]),l=[];return e.children.forEach((p,u)=>{const f=p.type==="leaf"?p.terminalId:p.id;l.push(s.jsx("div",{style:{flex:`${e.sizes[u]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(et,{node:p,canClose:n})},f)),u<e.children.length-1&&l.push(s.jsx("div",{onMouseDown:m=>i(u,m),style:{flex:`0 0 ${Kn}px`,cursor:a?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="#292e42"}},`divider-${e.id}-${u}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:a?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:l})});function Qn({tabId:t}){const e=v(b=>b.tabs.find(L=>L.id===t)),n=v(b=>b.activeTabId),r=v(b=>b.switchTab),o=v(b=>b.closeTab),a=v(b=>b.reopenTab),c=v(b=>b.deleteTab),i=v(b=>b.renameTab),l=v(b=>e?e.terminalIds.map(L=>{const D=b.terminalsMap[L];return D?{id:L,connected:D.connected}:{id:L,connected:!1}}):[]),[p,u]=d.useState(!1),[f,m]=d.useState(""),[h,x]=d.useState(!1),w=d.useRef(null);if(!e)return null;const k=n===t,S=e.status==="open",M=()=>{S&&r(t)},j=b=>{S&&(b.stopPropagation(),m(e.name),u(!0),setTimeout(()=>{var L;return(L=w.current)==null?void 0:L.focus()},0))},y=()=>{const b=f.trim();b&&i(t,b),u(!1)},I=b=>{b.stopPropagation(),a(t)},R=b=>{b.stopPropagation(),o(t)},z=async b=>{b.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await c(t)},E=b=>{b.stopPropagation(),x(!h)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:M,style:{padding:"8px 12px",cursor:S?"pointer":"default",borderLeft:k?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:k?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s",opacity:S?1:.5},onMouseEnter:b=>{S&&!k&&(b.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:b=>{k||(b.currentTarget.style.backgroundColor="transparent")},children:[S&&e.terminalIds.length>0&&s.jsx("button",{onClick:E,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:[p?s.jsx("input",{ref:w,value:f,onChange:b=>m(b.target.value),onBlur:y,onKeyDown:b=>{b.key==="Enter"&&y(),b.key==="Escape"&&u(!1)},style:{width:"100%",background:"#1a1b26",border:"1px solid #7aa2f7",color:"#c0caf5",borderRadius:"3px",padding:"1px 4px",fontSize:"13px",outline:"none"}}):s.jsx("div",{onDoubleClick:j,style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:S?"Double-click to rename":e.name,children:e.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",Ze(Math.floor(e.createdAt/1e3))]})]}),S?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:I,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:z,title:"Delete tab",children:"×"})]})]}),S&&h&&l.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:l.map(b=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)"},title:`Connected: ${b.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:b.id}),s.jsx("span",{style:{marginLeft:"8px",color:b.connected?"#9ece6a":"#f7768e"},children:b.connected?"●":"○"})]},b.id))})]})}function er({sessionId:t,active:e,createdAt:n}){const r=v(i=>i.addTerminal),o=v(i=>i.killServerSession),a=()=>{r("horizontal",t)},c=i=>{i.stopPropagation(),window.confirm(`Delete orphaned session "${t}"? This will kill the tmux session.`)&&o(t)};return s.jsxs("div",{onClick:a,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s"},onMouseEnter:i=>{i.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:Ze(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function tr(){const t=v(l=>l.sidebarOpen),e=v(l=>l.toggleSidebar),n=v(l=>l.serverSessions),r=v(l=>l.fetchSessions),o=v(l=>l.tabs),a=v(l=>l.terminalIds),c=new Set(o.flatMap(l=>l.terminalIds)),i=n.filter(l=>!c.has(l.sessionId));return d.useEffect(()=>{if(!t)return;r();let l=setInterval(r,5e3);const p=()=>{document.hidden?l&&(clearInterval(l),l=null):(r(),l||(l=setInterval(r,5e3)))};return document.addEventListener("visibilitychange",p),()=>{l&&clearInterval(l),document.removeEventListener("visibilitychange",p)}},[t,r]),d.useEffect(()=>{if(!t)return;const l=setTimeout(r,800);return()=>clearTimeout(l)},[a.length,t,r]),s.jsxs("div",{className:"session-sidebar",style:{width:t?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:t?"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:e,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:"13px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(l=>s.jsx(Qn,{tabId:l.id},l.id))]}),i.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"}),i.map(l=>s.jsx(er,{sessionId:l.sessionId,active:l.active,createdAt:l.createdAt},l.sessionId))]})]})]})}const tt=ye.memo(()=>{const t=v(y=>y.tabs),e=v(y=>y.activeTabId),n=v(y=>y.addTab),r=v(y=>y.switchTab),o=v(y=>y.closeTab),a=v(y=>y.renameTab),[c,i]=d.useState(null),[l,p]=d.useState(""),u=d.useRef(null),f=t.filter(y=>y.status==="open");d.useEffect(()=>{c&&u.current&&(u.current.focus(),u.current.select())},[c]);const m=y=>{i(y.id),p(y.name)},h=()=>{c&&l.trim()&&a(c,l.trim()),i(null),p("")},x=()=>{i(null),p("")},w=y=>{y.key==="Enter"?h():y.key==="Escape"&&x()},k=y=>{c||r(y)},S=(y,I)=>{y.stopPropagation(),o(I)},M=(y,I)=>{y.button===1&&(y.preventDefault(),o(I))},j=f.length>1;return s.jsxs("div",{className:"tab-bar",children:[f.map(y=>{const I=y.id===e,R=c===y.id,z=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${I?"tab-item--active":""}`,onClick:()=>k(y.id),onDoubleClick:()=>m(y),onMouseDown:E=>M(E,y.id),children:R?s.jsx("input",{ref:u,type:"text",value:l,onChange:E=>p(E.target.value),onBlur:h,onKeyDown:w,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",z>0&&`(${z})`]}),j&&s.jsx("button",{className:"tab-item__close",onClick:E=>S(E,y.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},y.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});tt.displayName="TabBar";function nr(){return localStorage.getItem("ai-cli-online-token")}function rr(){const t=v(l=>l.token),e=v(l=>l.setToken),n=v(l=>l.tabs),r=v(l=>l.addTab),o=v(l=>l.toggleSidebar),a=v(l=>l.fontSize),c=v(l=>l.setFontSize),i=v(l=>l.tabsLoading);return d.useEffect(()=>{const l=nr();l&&!t&&e(l)},[]),d.useEffect(()=>{t&&!i&&n.filter(l=>l.status==="open").length===0&&r("Default")},[t,i]),t?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(a-1),disabled:a<=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:a}),s.jsx("button",{className:"header-btn",onClick:()=>c(a+1),disabled:a>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(sr,{}),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?")&&e(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Yn,{})}),s.jsx(tr,{})]}),s.jsx(tt,{})]}):s.jsx(en,{})}const or=[1,2,3,4];function sr(){const t=v(r=>r.latency);if(t===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let e,n;return t<50?(e="#9ece6a",n=4):t<150?(e="#e0af68",n=3):t<300?(e="#ff9e64",n=2):(e="#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: ${t}ms`,children:[or.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?e:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[t,"ms"]})]})}xe.createRoot(document.getElementById("root")).render(s.jsx(ye.StrictMode,{children:s.jsx(Qe,{children:s.jsx(rr,{})})}));
|