ai-cli-online 2.2.4 → 2.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/README.zh-CN.md +3 -1
- package/package.json +1 -1
- package/server/dist/files.js +18 -15
- package/server/dist/tmux.js +4 -3
- package/server/package.json +1 -1
- package/shared/package.json +1 -1
- package/web/dist/assets/index-C2U1eAjl.js +27 -0
- package/web/dist/index.html +1 -1
- package/web/package.json +1 -1
- package/web/dist/assets/index-PKDRHNHV.js +0 -27
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@ Ideal for **unstable networks** where SSH drops frequently, or as a **local stat
|
|
|
20
20
|
- **Session Persistence** — tmux keeps processes alive through disconnects; reconnect and resume instantly
|
|
21
21
|
- **Multi-Tab** — independent terminal groups with layout persistence across browser refreshes
|
|
22
22
|
- **Split Panes** — horizontal / vertical splits, arbitrarily nested
|
|
23
|
-
- **Document Browser** — view Markdown, HTML, and PDF files alongside your terminal
|
|
23
|
+
- **Document Browser** — view Markdown, HTML, and PDF files alongside your terminal; file picker shows file sizes
|
|
24
24
|
- **Editor Panel** — multi-line editing with server-side draft persistence (SQLite)
|
|
25
25
|
- **File Transfer** — upload files to CWD, browse and download via REST API
|
|
26
26
|
- **Scroll History** — capture-pane scrollback viewer with ANSI color preservation
|
|
@@ -50,7 +50,7 @@ Ideal for **unstable networks** where SSH drops frequently, or as a **local stat
|
|
|
50
50
|
| **Transport** | Binary frames (ultra-low latency) | JSON WebSocket |
|
|
51
51
|
| **Deployment** | Single-node Node.js | Single-node + Tailscale Serve/Funnel |
|
|
52
52
|
| **Tech Stack** | React + Express + node-pty | Lit + Express + Pi Agent |
|
|
53
|
-
| **Package Size** | ~
|
|
53
|
+
| **Package Size** | ~950 KB | ~300 MB+ |
|
|
54
54
|
| **Install** | `npx ai-cli-online` | `npm i -g openclaw && openclaw onboard` |
|
|
55
55
|
|
|
56
56
|
## Quick Start
|
|
@@ -118,6 +118,8 @@ Browser (xterm.js + WebGL) <-- WebSocket binary/JSON --> Express (node-pty) <-->
|
|
|
118
118
|
- **WebSocket compression** — `perMessageDeflate` (level 1, threshold 128 B), 50-70% bandwidth reduction
|
|
119
119
|
- **WebGL renderer** — 3-10x rendering throughput vs canvas
|
|
120
120
|
- **Parallel initialization** — PTY creation, tmux config, and resize run concurrently
|
|
121
|
+
- **PDF lazy loading** — pdfjs-dist (445 KB) only loaded when a user opens a PDF file
|
|
122
|
+
- **Smart re-render** — matchMedia threshold hook, conditional Zustand selectors, batched stat calls
|
|
121
123
|
|
|
122
124
|
## Project Structure
|
|
123
125
|
|
package/README.zh-CN.md
CHANGED
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
| **传输协议** | 二进制帧(超低延迟) | JSON WebSocket |
|
|
51
51
|
| **部署** | 单机 Node.js | 单机 + Tailscale Serve/Funnel |
|
|
52
52
|
| **技术栈** | React + Express + node-pty | Lit + Express + Pi Agent |
|
|
53
|
-
| **包大小** | ~
|
|
53
|
+
| **包大小** | ~950 KB | ~300 MB+ |
|
|
54
54
|
| **安装** | `npx ai-cli-online` | `npm i -g openclaw && openclaw onboard` |
|
|
55
55
|
|
|
56
56
|
## 快速开始
|
|
@@ -118,6 +118,8 @@ TRUST_PROXY=1 # nginx 反代时设为 1
|
|
|
118
118
|
- **WebSocket 压缩** — `perMessageDeflate`(level 1,threshold 128 B),带宽减少 50-70%
|
|
119
119
|
- **WebGL 渲染器** — 渲染吞吐量提升 3-10 倍
|
|
120
120
|
- **并行初始化** — PTY 创建、tmux 配置、resize 并行执行
|
|
121
|
+
- **PDF 懒加载** — pdfjs-dist (445 KB) 仅在用户打开 PDF 文件时加载
|
|
122
|
+
- **智能重渲染** — matchMedia 阈值 hook、条件 Zustand selector、分批 stat 调用
|
|
121
123
|
|
|
122
124
|
## 项目结构
|
|
123
125
|
|
package/package.json
CHANGED
package/server/dist/files.js
CHANGED
|
@@ -6,22 +6,25 @@ const MAX_DIR_ENTRIES = 1000;
|
|
|
6
6
|
/** List files in a directory, directories first, then alphabetical */
|
|
7
7
|
export async function listFiles(dirPath) {
|
|
8
8
|
const entries = await readdir(dirPath, { withFileTypes: true });
|
|
9
|
-
//
|
|
10
|
-
const
|
|
11
|
-
const fullPath = join(dirPath, entry.name);
|
|
12
|
-
const s = await stat(fullPath);
|
|
13
|
-
return {
|
|
14
|
-
name: entry.name,
|
|
15
|
-
type: (entry.isDirectory() ? 'directory' : 'file'),
|
|
16
|
-
size: s.size,
|
|
17
|
-
modifiedAt: s.mtime.toISOString(),
|
|
18
|
-
};
|
|
19
|
-
}));
|
|
9
|
+
// Batched parallel stat to avoid excessive concurrent syscalls on large directories
|
|
10
|
+
const BATCH_SIZE = 50;
|
|
20
11
|
const results = [];
|
|
21
|
-
for (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
12
|
+
for (let i = 0; i < entries.length; i += BATCH_SIZE) {
|
|
13
|
+
const batch = entries.slice(i, i + BATCH_SIZE);
|
|
14
|
+
const settled = await Promise.allSettled(batch.map(async (entry) => {
|
|
15
|
+
const fullPath = join(dirPath, entry.name);
|
|
16
|
+
const s = await stat(fullPath);
|
|
17
|
+
return {
|
|
18
|
+
name: entry.name,
|
|
19
|
+
type: (entry.isDirectory() ? 'directory' : 'file'),
|
|
20
|
+
size: s.size,
|
|
21
|
+
modifiedAt: s.mtime.toISOString(),
|
|
22
|
+
};
|
|
23
|
+
}));
|
|
24
|
+
for (const result of settled) {
|
|
25
|
+
if (result.status === 'fulfilled')
|
|
26
|
+
results.push(result.value);
|
|
27
|
+
}
|
|
25
28
|
}
|
|
26
29
|
// Directories first, then alphabetical
|
|
27
30
|
results.sort((a, b) => {
|
package/server/dist/tmux.js
CHANGED
|
@@ -62,7 +62,7 @@ export async function captureScrollback(name) {
|
|
|
62
62
|
try {
|
|
63
63
|
const { stdout } = await execFile('tmux', [
|
|
64
64
|
'capture-pane',
|
|
65
|
-
'-t', `=${name}
|
|
65
|
+
'-t', `=${name}:`,
|
|
66
66
|
'-p',
|
|
67
67
|
'-e',
|
|
68
68
|
'-S', '-10000',
|
|
@@ -137,10 +137,10 @@ export async function cleanupStaleSessions(ttlHours) {
|
|
|
137
137
|
'-F',
|
|
138
138
|
'#{session_name}:#{session_created}:#{session_attached}',
|
|
139
139
|
], { encoding: 'utf-8' });
|
|
140
|
+
const staleNames = [];
|
|
140
141
|
for (const line of stdout.trim().split('\n')) {
|
|
141
142
|
if (!line)
|
|
142
143
|
continue;
|
|
143
|
-
// Use lastIndexOf to safely parse (consistent with listSessions)
|
|
144
144
|
const lastColon = line.lastIndexOf(':');
|
|
145
145
|
if (lastColon === -1)
|
|
146
146
|
continue;
|
|
@@ -157,9 +157,10 @@ export async function cleanupStaleSessions(ttlHours) {
|
|
|
157
157
|
continue;
|
|
158
158
|
if (created < cutoff) {
|
|
159
159
|
console.log(`[tmux] Cleaning up stale session: ${name} (created ${new Date(created * 1000).toISOString()})`);
|
|
160
|
-
|
|
160
|
+
staleNames.push(name);
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
|
+
await Promise.all(staleNames.map((name) => killSession(name)));
|
|
163
164
|
}
|
|
164
165
|
catch {
|
|
165
166
|
// No tmux server or no sessions
|
package/server/package.json
CHANGED
package/shared/package.json
CHANGED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
var ct=Object.defineProperty;var dt=(e,t,n)=>t in e?ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ke=(e,t,n)=>dt(e,typeof t!="symbol"?t+"":t,n);import{r as d,a as ut,g as ft,R as we}from"./react-vendor-BCIvbQoU.js";import{D as Ue,o as We,L as pt,x as He}from"./terminal-DnNpv9tw.js";import{d as mt,p as ht}from"./markdown-BERZKN_L.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const 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 Ve={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 xt=d,bt=Symbol.for("react.element"),yt=Symbol.for("react.fragment"),gt=Object.prototype.hasOwnProperty,wt=xt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,vt={key:!0,ref:!0,__self:!0,__source:!0};function Ge(e,t,n){var r,o={},a=null,c=null;n!==void 0&&(a=""+n),t.key!==void 0&&(a=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)gt.call(t,r)&&!vt.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:bt,type:e,key:a,ref:c,props:o,_owner:wt.current}}de.Fragment=yt;de.jsx=Ge;de.jsxs=Ge;Ve.exports=de;var s=Ve.exports,ye={},Ie=ut;ye.createRoot=Ie.createRoot,ye.hydrateRoot=Ie.hydrateRoot;const St={},Ce=e=>{let t;const n=new Set,r=(f,u)=>{const x=typeof f=="function"?f(t):f;if(!Object.is(x,t)){const p=t;t=u??(typeof x!="object"||x===null)?x:Object.assign({},t,x),n.forEach(h=>h(t,p))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>m,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},m=t=e(r,o,i);return i},Tt=e=>e?Ce(e):Ce;var qe={exports:{}},Ke={},Je={exports:{}},Ye={};/**
|
|
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 ne=d;function kt(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var It=typeof Object.is=="function"?Object.is:kt,Ct=ne.useState,jt=ne.useEffect,Et=ne.useLayoutEffect,Rt=ne.useDebugValue;function zt(e,t){var n=t(),r=Ct({inst:{value:n,getSnapshot:t}}),o=r[0].inst,a=r[1];return Et(function(){o.value=n,o.getSnapshot=t,he(o)&&a({inst:o})},[e,n,t]),jt(function(){return he(o)&&a({inst:o}),e(function(){he(o)&&a({inst:o})})},[e]),Rt(n),n}function he(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!It(e,n)}catch{return!0}}function Lt(e,t){return t()}var Dt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lt:zt;Ye.useSyncExternalStore=ne.useSyncExternalStore!==void 0?ne.useSyncExternalStore:Dt;Je.exports=Ye;var Nt=Je.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,Mt=Nt;function At(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ot=typeof Object.is=="function"?Object.is:At,$t=Mt.useSyncExternalStore,Pt=ue.useRef,_t=ue.useEffect,Ft=ue.useMemo,Bt=ue.useDebugValue;Ke.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var a=Pt(null);if(a.current===null){var c={hasValue:!1,value:null};a.current=c}else c=a.current;a=Ft(function(){function i(p){if(!m){if(m=!0,f=p,p=r(p),o!==void 0&&c.hasValue){var h=c.value;if(o(h,p))return u=h}return u=p}if(h=u,Ot(f,p))return h;var w=r(p);return o!==void 0&&o(h,w)?(f=p,h):(f=p,u=w)}var m=!1,f,u,x=n===void 0?null:n;return[function(){return i(t())},x===null?void 0:function(){return i(x())}]},[t,n,r,o]);var l=$t(e,a[0],a[1]);return _t(function(){c.hasValue=!0,c.value=l},[l]),Bt(l),l};qe.exports=Ke;var Ut=qe.exports;const Wt=ft(Ut),Xe={},{useDebugValue:Ht}=we,{useSyncExternalStoreWithSelector:Vt}=Wt;let je=!1;const Gt=e=>e;function qt(e,t=Gt,n){(Xe?"production":void 0)!=="production"&&n&&!je&&(je=!0);const r=Vt(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Ht(r),r}const Ee=e=>{const t=typeof e=="function"?Tt(e):e,n=(r,o)=>qt(t,r,o);return Object.assign(n,t),n},Kt=e=>e?Ee(e):Ee,_="";function U(e){return{Authorization:`Bearer ${e}`}}async function Jt(e){try{const t=await fetch(`${_}/api/settings/font-size`,{headers:U(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function Yt(e,t){try{await fetch(`${_}/api/settings/font-size`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function Xt(e){try{const t=await fetch(`${_}/api/settings/tabs-layout`,{headers:U(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function Zt(e,t){try{await fetch(`${_}/api/settings/tabs-layout`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function Re(e,t){try{const n=`${_}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const le="ai-cli-online-tabs",ze="ai-cli-online-layout",Le="ai-cli-online-session-names";function ce(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let c=0;c<e.children.length;c++){const l=ce(e.children[c],t);l!==null&&(n.push(l),r.push(e.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,l)=>c+l,0),a=r.map(c=>c/o*100);return{...e,children:n,sizes:a}}function Ze(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(a=>Ze(a,t,n,r,o))}}function Qe(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Qe(r,t,n))}}function xe(e){return e.tabs.find(t=>t.id===e.activeTabId)}function X(e,t,n){return e.map(r=>r.id===t?n(r):r)}function V(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(le,JSON.stringify(t))}catch{}Qt(t)}let se=null,ie=null,Z=null,re=null;function Qt(e){re=e,Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,re=null;const t=T.getState().token;t&&Zt(t,e)},2e3)}function en(e){se&&clearTimeout(se),se=setTimeout(()=>{se=null,V(e)},500)}function tn(){try{const e=localStorage.getItem(le);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(ze);if(e){const t=JSON.parse(e);let n="Default";try{const a=localStorage.getItem(Le);if(a){const c=JSON.parse(a),l=Object.values(c)[0];l&&(n=l)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(le,JSON.stringify(o))}catch{}return localStorage.removeItem(ze),localStorage.removeItem(Le),o}}catch{}return null}function B(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function nn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.tabs){if(c.status!=="open"){const m=c.terminalIds.filter(f=>n.has(f));if(m.length>0){let f=c.layout;for(const u of c.terminalIds)!n.has(u)&&f&&(f=ce(f,u));r.push({...c,terminalIds:m,layout:f})}continue}const l=c.terminalIds.filter(m=>n.has(m));if(l.length===0)continue;let i=c.layout;for(const m of c.terminalIds)!n.has(m)&&i&&(i=ce(i,m));r.push({...c,terminalIds:l,layout:i})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(l=>l.status==="open");o=(c==null?void 0:c.id)||""}return{...e,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var t,n;const e=(n=(t=T==null?void 0:T.getState)==null?void 0:t.call(T))==null?void 0:n.token;if(e)if(re)Z&&(clearTimeout(Z),Z=null),Re(e,re),re=null;else{const r=T.getState();r.tabs.length>0&&Re(e,B(r))}});function De(e,t){const n=e.tabs.find(m=>m.terminalIds.includes(t));if(!n){const{[t]:m,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(m=>m!==t),o=n.layout?ce(n.layout,t):null,a=X(e.tabs,n.id,m=>({...m,terminalIds:r,layout:o})),{[t]:c,...l}=e.terminalsMap,i={terminalsMap:l,tabs:a};return n.id===e.activeTabId&&(i.terminalIds=r,i.layout=o),i}const T=Kt((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Jt(n).then(o=>{t().token===n&&e({fontSize:o})});const r=tn();if(r&&r.tabs.length>0){const o={};for(const l of r.tabs)if(l.status==="open")for(const i of l.terminalIds)o[i]={id:i,connected:!1,sessionResumed:!1,error:null};const a=r.tabs.find(l=>l.id===r.activeTabId&&l.status==="open")||r.tabs.find(l=>l.status==="open"),c=(a==null?void 0:a.id)||"";e({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 e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});rn(n,r);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(le),e({token:n,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:n=>{const r=t(),o=`tab${r.nextTabId}`,a=`t${r.nextId}`,c={id:a,connected:!1,sessionResumed:!1,error:null},l={type:"leaf",terminalId:a},i={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[a],layout:l,createdAt:Date.now()};return e({tabs:[...r.tabs,i],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[a]:c},terminalIds:i.terminalIds,layout:i.layout}),V(B(t())),o},switchTab:n=>{const o=t().tabs.find(a=>a.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),V(B(t())))},closeTab:n=>{const r=t(),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 l=X(r.tabs,n,u=>({...u,status:"closed"}));let i=r.activeTabId,m=r.terminalIds,f=r.layout;if(r.activeTabId===n){const u=r.tabs.findIndex(h=>h.id===n),x=l.filter(h=>h.status==="open"),p=x.find(h=>l.findIndex(C=>C.id===h.id)>u)||x[x.length-1];p&&(i=p.id,m=p.terminalIds,f=p.layout)}e({tabs:l,activeTabId:i,terminalsMap:c,terminalIds:m,layout:f}),V(B(t()))},reopenTab:n=>{const r=t(),o=r.tabs.find(l=>l.id===n);if(!o||o.status!=="closed")return;const a={...r.terminalsMap};for(const l of o.terminalIds)a[l]={id:l,connected:!1,sessionResumed:!1,error:null};const c=X(r.tabs,n,l=>({...l,status:"open"}));e({tabs:c,activeTabId:n,terminalsMap:a,terminalIds:o.terminalIds,layout:o.layout}),V(B(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(p=>p.id===n);if(!o)return;const a=r.token;a&&await Promise.all(o.terminalIds.map(p=>fetch(`${_}/api/sessions/${encodeURIComponent(p)}`,{method:"DELETE",headers:U(a)}).catch(()=>{})));const c=t(),l=c.tabs.find(p=>p.id===n);if(!l)return;const i={...c.terminalsMap};for(const p of l.terminalIds)delete i[p];const m=c.tabs.filter(p=>p.id!==n);let f=c.activeTabId,u=c.terminalIds,x=c.layout;if(c.activeTabId===n){const p=m.find(h=>h.status==="open");p?(f=p.id,u=p.terminalIds,x=p.layout):(f="",u=[],x=null)}e({tabs:m,activeTabId:f,terminalsMap:i,terminalIds:u,layout:x}),V(B(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=X(t().tabs,n,a=>({...a,name:r}));e({tabs:o}),V(B(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const a=xe(o);if(!a){const R=`tab${o.nextTabId}`,E=r||`t${o.nextId}`;let D=o.nextId;const k=E.match(/^t(\d+)$/);k&&(D=Math.max(D,parseInt(k[1],10)+1));const b=r?D:D+1,S={id:E,connected:!1,sessionResumed:!1,error:null},N={type:"leaf",terminalId:E},$={id:R,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[E],layout:N,createdAt:Date.now()};return e({tabs:[...o.tabs,$],activeTabId:R,nextTabId:o.nextTabId+1,nextId:b,terminalsMap:{...o.terminalsMap,[E]:S},terminalIds:[E],layout:N}),V(B(t())),E}const{nextId:c,nextSplitId:l,terminalsMap:i}=o,{terminalIds:m,layout:f}=a,u=r||`t${c}`;let x=c;const p=u.match(/^t(\d+)$/);p&&(x=Math.max(x,parseInt(p[1],10)+1));const h={id:u,connected:!1,sessionResumed:!1,error:null},w={type:"leaf",terminalId:u};let C,v=l;if(!f)C=w;else if(f.type==="leaf"){const R=n||"horizontal";C={id:`s${v}`,type:"split",direction:R,children:[f,w],sizes:[50,50]},v++}else if(f.direction===(n||"horizontal")){const E=100/(f.children.length+1),D=(100-E)/100,k=[...f.sizes.map(b=>b*D),E];C={...f,children:[...f.children,w],sizes:k}}else{const R=n||"horizontal";C={id:`s${v}`,type:"split",direction:R,children:[f,w],sizes:[50,50]},v++}const L=[...m,u],j=r?x:x+1,y=X(o.tabs,a.id,R=>({...R,terminalIds:L,layout:C}));return e({terminalsMap:{...i,[u]:h},terminalIds:L,layout:C,tabs:y,nextId:j,nextSplitId:v}),V(B(t())),u},splitTerminal:(n,r)=>{const o=t(),a=xe(o);if(!a||!a.layout)return"";const{nextId:c,nextSplitId:l,terminalsMap:i}=o,m=`t${c}`,f={id:m,connected:!1,sessionResumed:!1,error:null},u={type:"leaf",terminalId:m},x=`s${l}`,p=Ze(a.layout,n,r,u,x),h=[...a.terminalIds,m],w=c+1,C=l+1,v=X(o.tabs,a.id,L=>({...L,terminalIds:h,layout:p}));return e({terminalsMap:{...i,[m]:f},terminalIds:h,layout:p,tabs:v,nextId:w,nextSplitId:C}),V(B(t())),m},removeTerminal:n=>{const r=De(t(),n);r&&(e(r),V(B(t())))},setTerminalConnected:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,error:r}}}})},setSplitSizes:(n,r)=>{const o=t(),a=xe(o);if(!a||!a.layout)return;const c=Qe(a.layout,n,r),l=X(o.tabs,a.id,i=>({...i,layout:c}));e({layout:c,tabs:l}),en(B(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null;const o=t().token;o&&Yt(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${_}/api/sessions`,{headers:U(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}},killServerSession:async n=>{const r=t().token;if(!r)return;try{await fetch(`${_}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:U(r)})}catch{}const o=De(t(),n);o&&(e(o),V(B(t()))),setTimeout(()=>t().fetchSessions(),500)}}));async function rn(e,t){var o;const{setState:n,getState:r}=T;try{const[a,c]=await Promise.all([Xt(e),fetch(`${_}/api/sessions`,{headers:U(e)}).then(p=>p.ok?p.json():[]).catch(()=>[])]);if(r().token!==e)return;const l=a&&((o=a.tabs)==null?void 0:o.length)>0?a:t;if(!l||l.tabs.length===0){n({tabsLoading:!1});return}const i=nn(l,c);if(!i){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:[],layout:null});return}const m=r().terminalsMap,f={};for(const p of i.tabs)if(p.status==="open")for(const h of p.terminalIds)f[h]=m[h]||{id:h,connected:!1,sessionResumed:!1,error:null};const u=i.tabs.find(p=>p.id===i.activeTabId&&p.status==="open")||i.tabs.find(p=>p.status==="open"),x=(u==null?void 0:u.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:i.tabs,activeTabId:x,nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null}),V(B(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function on(){const[e,t]=d.useState(""),n=T(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, #1a1b26 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"#24283b",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid #292e42"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, #7aa2f7 0%, #bb9af7 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"#1a1b26",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"#c0caf5",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"#565f89",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"#7aa2f7",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"#1a1b26",color:"#c0caf5",border:"1px solid #292e42",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:e.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#414868",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"#1a1b26",padding:"2px 6px",borderRadius:"4px",border:"1px solid #292e42",fontSize:"11px"},children:"server/.env"})]})})]})})}const sn=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,ae=500,an=8e3,ln=1e4,Ne=4e3,cn=5e3,dn=5,un=64*1024,fn=1,Me=2,pn=3,mn=4,hn=new TextDecoder,xn=new TextEncoder;function Ae(e,t){const n=xn.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function bn(e,t,n){const r=d.useRef(null),o=d.useRef(ae),a=d.useRef(null),c=d.useRef(null),l=d.useRef(null),i=d.useRef(null),m=d.useRef(!1),f=d.useRef(n),u=d.useRef(!1),x=d.useRef(0),p=d.useRef(!0),h=d.useRef(!navigator.onLine),w=d.useRef(""),C=d.useRef(null),v=d.useRef("");f.current=n;const L=d.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),a.current&&(clearTimeout(a.current),a.current=null),i.current&&(clearTimeout(i.current),i.current=null),C.current&&(clearTimeout(C.current),C.current=null)},[]),j=d.useCallback(()=>{const{token:D,setTerminalError:k}=T.getState();if(!D||m.current)return;if(r.current){const $=r.current.readyState;if($===WebSocket.OPEN||$===WebSocket.CONNECTING)return}u.current=!1;const b=`${sn}?sessionId=${encodeURIComponent(t)}`,S=new WebSocket(b);S.binaryType="arraybuffer",i.current=window.setTimeout(()=>{S.readyState===WebSocket.CONNECTING&&S.close()},cn);const N=()=>{S.readyState===WebSocket.OPEN&&(x.current=performance.now(),S.send(JSON.stringify({type:"ping"})),l.current=window.setTimeout(()=>{x.current>0&&(x.current=0,S.close())},Ne))};S.onopen=()=>{i.current&&(clearTimeout(i.current),i.current=null),S.send(JSON.stringify({type:"auth",token:D})),k(t,null),o.current=ae,p.current=!0},S.onclose=$=>{const{setTerminalConnected:W,setTerminalError:P,setToken:z}=T.getState();if(W(t,!1),L(),u.current)return;if($.code===4001){m.current=!0,P(t,"Authentication failed"),z(null),localStorage.removeItem("ai-cli-online-token");return}if($.code===4002)return;if($.code===4005){P(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(p.current){p.current=!1,a.current=window.setTimeout(()=>j(),50);return}const M=o.current;o.current=Math.min(M*2,an);const A=Math.round(M*(.5+Math.random()));a.current=window.setTimeout(()=>{j()},A)},S.onerror=()=>{},S.onmessage=$=>{var W;try{const P=e.current;if($.data instanceof ArrayBuffer){const M=new Uint8Array($.data);if(M.length<1)return;const A=M[0],G=M.subarray(1);switch(A){case fn:P==null||P.write(G);break;case pn:P==null||P.write(G);break;case mn:{(W=f.current)==null||W.call(f,hn.decode(G));break}}return}const z=JSON.parse($.data);switch(z.type){case"connected":{const M=T.getState();M.setTerminalConnected(t,!0),M.setTerminalResumed(t,z.resumed);const A=e.current;A&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:A.cols,rows:A.rows})),v.current&&(S.send(Ae(Me,v.current)),v.current=""),N(),c.current=window.setInterval(N,ln);break}case"error":T.getState().setTerminalError(t,z.error);break;case"pong":{if(l.current&&(clearTimeout(l.current),l.current=null),x.current>0){const M=Math.round(performance.now()-x.current),A=T.getState();(A.terminalIds.length===0||A.terminalIds[0]===t)&&A.setLatency(M),x.current=0}break}}}catch{}},r.current=S},[t,e,L]),y=d.useCallback(D=>{const k=r.current;if(!k||k.readyState!==WebSocket.OPEN){v.current.length<un&&(v.current+=D);return}w.current+=D,C.current||(C.current=window.setTimeout(()=>{const b=w.current;w.current="",C.current=null,b&&k.readyState===WebSocket.OPEN&&k.send(Ae(Me,b))},dn))},[]),R=d.useCallback((D,k)=>{var b;((b=r.current)==null?void 0:b.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:D,rows:k}))},[]),E=d.useCallback(()=>{var D;((D=r.current)==null?void 0:D.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]);return d.useEffect(()=>{T.getState().token&&(m.current=!1,j());const k=()=>{h.current=!1,o.current=ae,p.current=!0;const N=r.current;(!N||N.readyState===WebSocket.CLOSED||N.readyState===WebSocket.CLOSING)&&j()},b=()=>{h.current=!0},S=()=>{if(document.visibilityState!=="visible")return;const N=r.current;if(!N||N.readyState!==WebSocket.OPEN){!h.current&&!u.current&&(o.current=ae,p.current=!0,j());return}x.current=performance.now(),N.send(JSON.stringify({type:"ping"})),l.current&&clearTimeout(l.current),l.current=window.setTimeout(()=>{x.current>0&&(x.current=0,N.close())},Ne)};return window.addEventListener("online",k),window.addEventListener("offline",b),document.addEventListener("visibilitychange",S),()=>{u.current=!0,L(),window.removeEventListener("online",k),window.removeEventListener("offline",b),document.removeEventListener("visibilitychange",S),r.current&&(r.current.close(),r.current=null)}},[j,L,t]),{sendInput:y,sendResize:R,requestScrollback:E}}const et={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"},tt="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",yn=d.forwardRef(function({sessionId:t},n){const r=d.useRef(null),o=d.useRef(null),a=d.useRef(null),[c,l]=d.useState(!1),[i,m]=d.useState(""),f=T(v=>v.fontSize),u=d.useCallback(v=>{m(v),l(!0)},[]),{sendInput:x,sendResize:p,requestScrollback:h}=bn(o,t,u);d.useImperativeHandle(n,()=>({sendInput:x}),[x]);const w=d.useRef(x),C=d.useRef(p);return w.current=x,C.current=p,d.useEffect(()=>{if(!r.current)return;let v=!1,L=null,j=null,y=null,R=null;if(v||!r.current)return;const E=new Ue({cursorBlink:!0,scrollback:1e4,fontSize:T.getState().fontSize,fontFamily:tt,theme:et,allowProposedApi:!0}),D=new We;E.loadAddon(D),E.loadAddon(new pt((S,N)=>{window.open(N,"_blank","noopener,noreferrer")})),E.open(r.current);try{const S=new He;S.onContextLoss(()=>{S.dispose()}),E.loadAddon(S)}catch{}o.current=E,a.current=D;const k=()=>{try{const S=r.current;if(S&&S.clientWidth>0&&S.clientHeight>0)return D.fit(),C.current(E.cols,E.rows),!0}catch{}return!1};requestAnimationFrame(()=>k());let b=0;return L=setInterval(()=>{b++,(k()||b>=10)&&(clearInterval(L),L=null)},100),document.fonts.ready.then(()=>{if(!v)try{D.fit(),C.current(E.cols,E.rows)}catch{}}),E.onData(S=>{w.current(S)}),R=new ResizeObserver(()=>{j||(j=requestAnimationFrame(()=>{j=null;try{D.fit(),y&&clearTimeout(y),y=setTimeout(()=>{y=null,C.current(E.cols,E.rows)},50)}catch{}}))}),R.observe(r.current),()=>{v=!0,L&&clearInterval(L),j&&cancelAnimationFrame(j),y&&clearTimeout(y),R&&R.disconnect(),o.current&&(o.current.dispose(),o.current=null),a.current=null}},[t]),d.useEffect(()=>{const v=o.current,L=a.current;if(!(!v||!L)&&v.options.fontSize!==f){v.options.fontSize=f;try{L.fit()}catch{}C.current(v.cols,v.rows)}},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"#1a1b26",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:v=>{v.currentTarget.blur(),c?(l(!1),m("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize:12,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:v=>{v.currentTarget.style.opacity="1"},onMouseLeave:v=>{v.currentTarget.style.opacity="0.8"},children:c?"✕":"↑"}),c&&s.jsx(gn,{data:i,onClose:()=>{l(!1),m("")}})]})});function gn({data:e,onClose:t}){const n=d.useRef(null),r=d.useRef(t);r.current=t;const o=T(i=>i.fontSize),a=d.useRef(null),c=d.useRef(null);d.useEffect(()=>{if(!n.current)return;const i=new Ue({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:tt,theme:et});a.current=i;const m=new We;c.current=m,i.loadAddon(m),i.open(n.current);try{const w=new He;w.onContextLoss(()=>w.dispose()),i.loadAddon(w)}catch{}i.attachCustomKeyEventHandler(w=>(w.key==="Escape"&&r.current(),!1)),i.write(e);let f=null;const u=()=>{const w=n.current;if(!w||w.clientWidth<=0||w.clientHeight<=0)return!1;try{return m.fit(),i.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!u()){let w=0;f=setInterval(()=>{w++,(u()||w>=30)&&(clearInterval(f),f=null)},50)}});let x=null;const p=new ResizeObserver(()=>{x||(x=requestAnimationFrame(()=>{x=null,u()}))});p.observe(n.current);const h=w=>{w.key==="Escape"&&r.current()};return document.addEventListener("keydown",h),()=>{f&&clearInterval(f),x&&cancelAnimationFrame(x),document.removeEventListener("keydown",h),p.disconnect(),i.dispose(),a.current=null,c.current=null}},[e]),d.useEffect(()=>{var i;if(a.current){a.current.options.fontSize=o;try{(i=c.current)==null||i.fit()}catch{}}},[o]);const l=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26"},children:[s.jsx("div",{style:{height:l,boxSizing:"border-box",padding:"0 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",display:"flex",alignItems:"center"},children:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{position:"absolute",top:l,left:0,right:0,bottom:0,overflow:"hidden"}})]})}async function oe(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:U(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function wn(e,t,n,r){return new Promise((o,a)=>{const c=new FormData;for(const i of n)c.append("files",i);const l=new XMLHttpRequest;l.open("POST",`${_}/api/sessions/${encodeURIComponent(t)}/upload`),l.setRequestHeader("Authorization",`Bearer ${e}`),l.upload.addEventListener("progress",i=>{i.lengthComputable&&r&&r(Math.round(i.loaded/i.total*100))}),l.addEventListener("load",()=>{l.status>=200&&l.status<300?o():a(new Error(`Upload failed: ${l.status}`))}),l.addEventListener("error",()=>a(new Error("Upload network error"))),l.addEventListener("abort",()=>a(new Error("Upload aborted"))),l.send(c)})}async function vn(e,t){const n=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:U(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function Sn(e,t,n){const r=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:U(e)});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 ve({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=T(j=>j.token),[a,c]=d.useState(""),[l,i]=d.useState([]),[m,f]=d.useState(!0),[u,x]=d.useState(null),p=d.useRef(""),h=d.useCallback(async j=>{if(o){f(!0),x(null);try{const y=await oe(o,e,j);j||(p.current=y.cwd),c(y.cwd),i(n?n(y.files):y.files)}catch(y){x(y instanceof Error?y.message:"Failed to load files")}finally{f(!1)}}},[o,e,n]);d.useEffect(()=>{h()},[h]),d.useEffect(()=>{if(!r||!o)return;let j=!1;const y=setInterval(async()=>{if(!j)try{const R=await vn(o,e);if(j)return;if(R!==p.current){p.current=R;const E=await oe(o,e);if(j)return;c(E.cwd),i(n?n(E.files):E.files)}}catch{}},r);return()=>{j=!0,clearInterval(y)}},[r,o,e,n]);const w=d.useRef(t);w.current=t,d.useEffect(()=>{const j=y=>{y.key==="Escape"&&w.current()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[]);const C=d.useCallback(j=>{h(a+"/"+j)},[h,a]),v=d.useCallback(()=>{const j=a.replace(/\/[^/]+$/,"")||"/";h(j)},[h,a]),L=d.useCallback(()=>{h(a)},[h,a]);return{cwd:a,files:l,loading:m,error:u,setError:x,handleNavigate:C,handleGoUp:v,handleRefresh:L}}function Tn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function nt(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Se({cwd:e,onGoUp:t,onRefresh:n,onClose:r}){return s.jsxs("div",{style:{padding:"6px 12px",background:"#24283b",borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[s.jsx("button",{onClick:t,style:{background:"none",border:"1px solid #414868",color:"#7aa2f7",borderRadius:3,padding:"1px 8px",fontSize:12,cursor:"pointer",flexShrink:0},title:"Go to parent directory",children:".."}),s.jsx("span",{style:{color:"#7aa2f7",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e||"..."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[s.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Refresh",children:"↻"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Close (ESC)",children:"✕"})]})]})}function Te({loading:e,error:t,empty:n,emptyText:r="Empty directory"}){return e?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):t?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:t}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function kn({sessionId:e,onClose:t}){const n=T(h=>h.token),{cwd:r,files:o,loading:a,error:c,setError:l,handleNavigate:i,handleGoUp:m,handleRefresh:f}=ve({sessionId:e,onClose:t}),[u,x]=d.useState(null),p=async h=>{if(n){x(h);try{await Sn(n,e,r+"/"+h)}catch(w){l(w instanceof Error?w.message:"Download failed")}finally{x(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Se,{cwd:r,onGoUp:m,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{loading:a,error:c,empty:o.length===0,emptyText:"Empty directory"}),!a&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&i(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:w=>{w.stopPropagation(),p(h.name)},disabled:u===h.name,style:{background:"none",border:"1px solid #414868",color:u===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:u===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:u===h.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:h.type==="directory"?"#7aa2f7":"#565f89"},children:h.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:h.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:h.type==="file"?Tn(h.size):""})]},h.name))]})]})}function In({content:e}){const t=T(r=>r.fontSize),n=d.useMemo(()=>{if(!e)return"";const r=mt.parse(e,{async:!1});return ht.sanitize(r,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[e]);return e?s.jsx("div",{className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${t}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 Cn(e,t){const n=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:U(e)});return n.ok?(await n.json()).content??"":""}async function Oe(e,t,n){await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const $e=[{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"}],jn=d.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},a){const c=T(g=>g.fontSize),[l,i]=d.useState(""),m=d.useRef(null),f=d.useRef(),u=d.useRef(!1),[x,p]=d.useState(!1),[h,w]=d.useState(""),[C,v]=d.useState(0),[L,j]=d.useState(!1),[y,R]=d.useState(""),[E,D]=d.useState(""),[k,b]=d.useState(0),[S,N]=d.useState([]),[$,W]=d.useState(!1),P=d.useRef(""),z=d.useRef(null),M=d.useMemo(()=>{if(!h)return $e;const g=h.toLowerCase();return $e.filter(I=>I.cmd.toLowerCase().includes(g)||I.desc.toLowerCase().includes(g))},[h]),A=d.useMemo(()=>{let g=S;if(y){const I=y.toLowerCase();g=g.filter(O=>O.name.toLowerCase().includes(I))}return[...g].sort((I,O)=>I.type==="directory"&&O.type!=="directory"?-1:I.type!=="directory"&&O.type==="directory"?1:I.name.localeCompare(O.name))},[S,y]);d.useEffect(()=>{let g=!1;return Cn(o,r).then(I=>{!g&&I&&i(I),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(()=>{Oe(o,r,l).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[l,o,r]),d.useEffect(()=>{var g;(g=m.current)==null||g.focus()},[]),d.useEffect(()=>{if(!L)return;let g=!1;return W(!0),(async()=>{try{if(E){if(!P.current){const F=await oe(o,r);if(g)return;P.current=F.cwd}const I=`${P.current}/${E.replace(/\/$/,"")}`,O=await oe(o,r,I);if(g)return;N(O.files)}else{const I=await oe(o,r);if(g)return;P.current=I.cwd,N(I.files)}W(!1)}catch{if(g)return;N([]),W(!1)}})(),()=>{g=!0}},[L,E,o,r]),d.useEffect(()=>{if(!L||!z.current)return;const g=z.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[k,L]);const G=d.useCallback(()=>{const g=l.trim();g&&(t(g),i(""),Oe(o,r,"").catch(()=>{}))},[l,t,o,r]);d.useImperativeHandle(a,()=>({send:G}),[G]),d.useEffect(()=>{n==null||n(l.trim().length>0)},[l,n]);const fe=d.useCallback(g=>{const I=m.current;if(!I)return;const O=I.selectionStart,F=l.slice(0,O),J=l.slice(O),K=F.lastIndexOf(`
|
|
26
|
+
`)+1,q=F.slice(K).match(/\/[a-zA-Z-]*$/);if(q){const H=K+(q.index??0),ee=g+" ",me=l.slice(0,H)+ee+J;i(me);const lt=H+ee.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=lt,I.focus()})}else{const H=F+g+J;i(H);const ee=O+g.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=ee,I.focus()})}p(!1),w(""),v(0)},[l]),pe=d.useCallback(g=>{const I=m.current;if(!I)return;const O=I.selectionStart,F=l.slice(0,O),J=l.slice(O),Q=F.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!Q)return;const K=F.length-Q[0].length;if(g.type==="directory"){const Y="@"+E+g.name+"/",q=l.slice(0,K)+Y+J;i(q);const H=K+Y.length;D(E+g.name+"/"),R(""),b(0),requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=H,I.focus()})}else{const Y=g.name+" ",q=l.slice(0,K)+Y+J;i(q);const H=K+Y.length;j(!1),R(""),D(""),b(0),N([]),P.current="",requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=H,I.focus()})}},[l,E]),it=d.useCallback(g=>{const I=g.target.value;i(I);const O=g.target.selectionStart,F=I.slice(0,O),J=F.lastIndexOf(`
|
|
27
|
+
`),K=F.slice(J+1).match(/^\/([a-zA-Z-]*)$/);if(K)p(!0),w(K[1]),v(0),j(!1);else{p(!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;R(me),b(0),D(ee),j(!0)}else j(!1)}},[]),at=d.useCallback(g=>{if(x&&M.length>0){if(g.key==="ArrowDown"){g.preventDefault(),v(I=>(I+1)%M.length);return}if(g.key==="ArrowUp"){g.preventDefault(),v(I=>(I-1+M.length)%M.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),fe(M[C].cmd);return}if(g.key==="Escape"){g.preventDefault(),p(!1);return}}if(L&&A.length>0){if(g.key==="ArrowDown"){g.preventDefault(),b(I=>(I+1)%A.length);return}if(g.key==="ArrowUp"){g.preventDefault(),b(I=>(I-1+A.length)%A.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),pe(A[k]);return}if(g.key==="Escape"){g.preventDefault(),j(!1);return}}if(g.key==="Tab"){g.preventDefault();const I=m.current;if(I){const O=I.selectionStart,F=I.selectionEnd,J=l.slice(0,O)+" "+l.slice(F);i(J);const Q=O+2;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Q})}return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),G())},[G,x,M,C,fe,l,L,A,k,pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[x&&M.length>0&&s.jsx("div",{className:"slash-dropdown",children:M.map((g,I)=>s.jsxs("div",{className:`slash-item${I===C?" slash-item--active":""}`,onMouseDown:O=>{O.preventDefault(),fe(g.cmd)},onMouseEnter:()=>v(I),children:[s.jsx("span",{className:"slash-cmd",children:g.cmd}),s.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),L&&($||A.length>0)&&s.jsx("div",{className:"file-dropdown",ref:z,children:$?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):A.map((g,I)=>s.jsxs("div",{className:`file-item${I===k?" file-item--active":""}`,onMouseDown:O=>{O.preventDefault(),pe(g)},onMouseEnter:()=>b(I),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:m,className:"md-editor-textarea",value:l,onChange:it,onKeyDown:at,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function En(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Rn(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function zn({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:a,error:c,handleNavigate:l,handleGoUp:i,handleRefresh:m}=ve({sessionId:e,onClose:n}),f=u=>{t(r+"/"+u)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Se,{cwd:r,onGoUp:i,onRefresh:m,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{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:x=>{x.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent"},onClick:()=>{u.type==="directory"?l(u.name):f(u.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:u.type==="directory"?"#7aa2f7":"#565f89"},children:Rn(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.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:En(u.size)}),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 Ln="modulepreload",Dn=function(e){return"/"+e},Pe={},Nn=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(i=>{if(i=Dn(i),i in Pe)return;Pe[i]=!0;const m=i.endsWith(".css"),f=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${i}"]${f}`))return;const u=document.createElement("link");if(u.rel=m?"stylesheet":Ln,m||(u.as="script"),u.crossOrigin="",u.href=i,l&&u.setAttribute("nonce",l),document.head.appendChild(u),m)return new Promise((x,p)=>{u.addEventListener("load",x),u.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${i}`)))})}))}function a(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return o.then(c=>{for(const l of c||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})};let ge=null,be=null;function Mn(){return be||(be=Nn(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(ge=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),be}function An({data:e,scrollRef:t}){const n=d.useRef(null),[r,o]=d.useState(null),[a,c]=d.useState(!0),l=d.useRef(0),i=m=>{n.current=m,t==null||t(m)};return d.useEffect(()=>{if(!e)return;const m=++l.current;return c(!0),o(null),(async()=>{try{if(await Mn(),!ge||m!==l.current)return;const f=atob(e),u=new Uint8Array(f.length);for(let w=0;w<f.length;w++)u[w]=f.charCodeAt(w);const x=await ge.getDocument({data:u}).promise;if(m!==l.current)return;const p=n.current;if(!p)return;for(;p.firstChild;)p.removeChild(p.firstChild);const h=p.clientWidth-24;for(let w=1;w<=x.numPages;w++){const C=await x.getPage(w);if(m!==l.current)return;const v=C.getViewport({scale:1}),L=Math.min(h/v.width,2),j=C.getViewport({scale:L}),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 R=y.getContext("2d");if(R){if(await C.render({canvasContext:R,viewport:j,canvas:y}).promise,m!==l.current)return;p.appendChild(y)}}c(!1)}catch(f){if(m!==l.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{l.current++}},[e]),s.jsxs("div",{ref:i,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 _e(e,t,n,r){const o=new URLSearchParams({path:n});r&&o.set("since",String(r));const a=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/file-content?${o}`,{headers:U(e)});if(a.status===304)return null;if(!a.ok)throw new Error("Failed to fetch file content");return a.json()}function On(e=50,t=20,n=80){const[r,o]=d.useState(e),a=d.useRef(null),c=d.useCallback(l=>{l.preventDefault();const i=a.current;if(!i)return;const m=i.getBoundingClientRect(),f=m.width;document.body.classList.add("resizing-panes-h");let u=null;const x=h=>{u||(u=requestAnimationFrame(()=>{u=null;const w=h.clientX-m.left,C=Math.min(n,Math.max(t,w/f*100));o(C)}))},p=()=>{u&&cancelAnimationFrame(u),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",p)};document.addEventListener("mousemove",x),document.addEventListener("mouseup",p)},[t,n]);return{leftWidthPercent:r,containerRef:a,onDividerMouseDown:c}}const $n=3e3;function Pn(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":"text"}function Fe(e){return e.split("/").pop()||e}function _n(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Fn(e){if(e.type==="directory")return"📁";const t=e.name.slice(e.name.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}const Bn=3e3;function Un({sessionId:e,onSelect:t}){const n=d.useCallback(()=>{},[]),{cwd:r,files:o,loading:a,error:c,handleNavigate:l,handleGoUp:i,handleRefresh:m}=ve({sessionId:e,onClose:n,pollCwd:Bn});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(Se,{cwd:r,onGoUp:i,onRefresh:m,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{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"?l(f.name):t(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Fn(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.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:_n(f.size)}),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 Wn({sessionId:e,token:t,onClose:n,onSend:r}){const[o,a]=d.useState(null),[c,l]=d.useState(""),[i,m]=d.useState(null),f=d.useRef(0),[u,x]=d.useState(!1),[p,h]=d.useState(!1),[w,C]=d.useState(!1),{leftWidthPercent:v,containerRef:L,onDividerMouseDown:j}=On(50),y=d.useRef(null),[R,E]=d.useState(!1),D=d.useRef(new Map),k=d.useRef(null),b=d.useRef(null),S=d.useCallback(()=>{if(!o)return;const z=p?b.current:k.current;z&&D.current.set(o,z.scrollTop)},[o,p]),N=d.useCallback(z=>{const M=D.current.get(z);M!=null&&requestAnimationFrame(()=>{const A=p?b.current:k.current;A&&(A.scrollTop=M)})},[p]),$=d.useCallback(z=>{S();const M=Pn(z);a(z),m(M),l(""),f.current=0,x(!1),_e(t,e,z).then(A=>{A&&(l(A.content),f.current=A.mtime,requestAnimationFrame(()=>N(z)))}).catch(()=>{})},[t,e,S,N]);d.useEffect(()=>{if(!o)return;let z=!1;const A=setInterval(async()=>{if(!z)try{const G=await _e(t,e,o,f.current);if(z)return;G&&(l(G.content),f.current=G.mtime)}catch{}},$n);return()=>{z=!0,clearInterval(A)}},[t,e,o]);const W=d.useCallback(()=>{o&&navigator.clipboard.writeText(o).then(()=>{C(!0),setTimeout(()=>C(!1),1500)}).catch(()=>{})},[o]);d.useEffect(()=>{if(!p)return;const z=M=>{M.key==="Escape"&&(S(),h(!1))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[p,S]),d.useEffect(()=>{o&&N(o)},[p,o,N]);const P=z=>o?!c&&i!=="pdf"?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:"13px"},children:"Loading..."}):i==="md"?s.jsx("div",{ref:z,style:{height:"100%",overflow:"auto"},children:s.jsx(In,{content:c})}):i==="html"?s.jsx("div",{ref:z,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:c,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})}):i==="pdf"?s.jsx(An,{data:c,scrollRef:z}):s.jsx("div",{ref:z,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:e,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:`${v}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>x(z=>!z),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:W,title:w?"Copied!":`Click to copy: ${o}`,children:w?"Copied!":Fe(o)}),s.jsx("button",{className:"pane-btn",onClick:()=>{S(),h(!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 z;return(z=y.current)==null?void 0:z.send()},disabled:!R,title:"Send to terminal (Ctrl+Enter)",style:R?{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:L,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${v}%`,flexShrink:0},children:[P(z=>{k.current=z}),u&&s.jsx(zn,{sessionId:e,onSelect:$,onClose:()=>x(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:j}),s.jsx("div",{className:"plan-editor-wrap",children:s.jsx(jn,{ref:y,onSend:r,onContentChange:E,sessionId:e,token:t})})]}),p&&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?Fe(o):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{S(),h(!1)},title:"Close expanded view (ESC)",children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:P(z=>{b.current=z})})]})]})}const Hn=100,Vn=600,te=typeof window<"u"?window.matchMedia(`(max-width: ${Vn-1}px)`):null;function Gn(){const[e,t]=d.useState(()=>(te==null?void 0:te.matches)??!1);return d.useEffect(()=>{if(!te)return;const n=r=>t(r.matches);return te.addEventListener("change",n),()=>te.removeEventListener("change",n)},[]),e}const qn=d.memo(function({terminal:t,canClose:n}){const r=Gn(),o=T(k=>k.killServerSession),a=T(k=>k.splitTerminal),c=T(k=>k.token),l=d.useRef(null),i=d.useRef(null),[m,f]=d.useState(!1),[u,x]=d.useState(!1),[p,h]=d.useState(0),[w,C]=d.useState(!1),[v,L]=d.useState(50),j=d.useRef(null),y=async k=>{const b=k.target.files;if(!(!b||b.length===0||!c)){x(!0),h(0);try{await wn(c,t.id,b,S=>{h(S)})}catch(S){alert(`Upload failed: ${S instanceof Error?S.message:"Unknown error"}`)}finally{x(!1),h(0),l.current&&(l.current.value="")}}},R=d.useRef(),E=d.useCallback(k=>{if(i.current){const b=k.replace(/\r?\n/g," ").trimEnd();i.current.sendInput(b),R.current=window.setTimeout(()=>{var S;return(S=i.current)==null?void 0:S.sendInput("\r")},50)}},[]);d.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]);const D=d.useCallback(k=>{k.preventDefault();const b=j.current;if(!b)return;const S=b.getBoundingClientRect(),N=S.height;document.body.classList.add("resizing-panes-v");const $=P=>{const z=(P.clientY-S.top)/N*100,M=Math.min(80,Math.max(20,z));L(100-M)},W=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",$),document.addEventListener("mouseup",W)},[]);return s.jsxs("div",{ref:j,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:t.connected?"#9ece6a":"#f7768e"}}),s.jsxs("span",{style:{fontSize:"11px",color:"#565f89"},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:l,type:"file",multiple:!0,style:{display:"none"},onChange:y}),s.jsx("button",{className:"pane-btn",onClick:()=>{var k;return(k=l.current)==null?void 0:k.click()},disabled:u,style:u?{color:"#e0af68"}:void 0,title:u?`Uploading ${p}%`:"Upload files","aria-label":"Upload files",children:u?`${p}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>f(k=>!k),style:m?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${w?" pane-btn--active":""}`,onClick:()=>C(k=>!k),title:"Toggle Document browser","aria-label":"Toggle Document browser",children:"Doc"}),s.jsx("button",{className:"pane-btn",onClick:()=>a(t.id,r?"vertical":"horizontal"),title:r?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>a(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"}),n&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>o(t.id),title:"Close terminal","aria-label":"Close terminal",children:"×"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(yn,{ref:i,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(26, 27, 38, 0.85)",zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"#565f89",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})}),m&&s.jsx(kn,{sessionId:t.id,onClose:()=>f(!1)})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:D}),s.jsx("div",{style:{height:`${v}%`,minHeight:Hn,flexShrink:0,overflow:"hidden"},children:s.jsx(Wn,{onSend:E,onClose:()=>C(!1),sessionId:t.id,token:c||""})})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:t.error})]})});class rt extends d.Component{constructor(){super(...arguments);ke(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,Be=10;function Jn(){const e=T(o=>o.layout),t=T(o=>o.terminalIds.length),n=T(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#1a1b26"},children:s.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed #292e42",color:"#565f89",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(ot,{node:e,canClose:r})})}const ot=d.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(Yn,{terminalId:t.terminalId,canClose:n}):s.jsx(Xn,{node:t,canClose:n})}),Yn=d.memo(function({terminalId:t,canClose:n}){const r=T(o=>o.terminalsMap[t]);return r?s.jsx(rt,{inline:!0,children:s.jsx(qn,{terminal:r,canClose:n})}):null}),Xn=d.memo(function({node:t,canClose:n}){const r=T(m=>m.setSplitSizes),o=d.useRef(null),a=t.direction==="horizontal",c=d.useRef(t.sizes);c.current=t.sizes;const l=d.useCallback((m,f)=>{f.preventDefault();const u=a?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const x=a?f.clientX:f.clientY,p=[...c.current],h=o.current,w=a?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let C=null;const v=j=>{C||(C=requestAnimationFrame(()=>{C=null;const E=((a?j.clientX:j.clientY)-x)/w*100,D=p[m]+E,k=p[m+1]-E;if(D>=Be&&k>=Be){const b=[...p];b[m]=D,b[m+1]=k,r(t.id,b)}}))},L=()=>{C&&cancelAnimationFrame(C),document.body.classList.remove(u),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",L)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",L)},[a,t.id,r]),i=[];return t.children.forEach((m,f)=>{const u=m.type==="leaf"?m.terminalId:m.id;i.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(ot,{node:m,canClose:n})},u)),f<t.children.length-1&&i.push(s.jsx("div",{onMouseDown:x=>l(f,x),style:{flex:`0 0 ${Kn}px`,cursor:a?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:a?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:i})});function Zn({tabId:e}){const t=T(b=>b.tabs.find(S=>S.id===e)),n=T(b=>b.activeTabId),r=T(b=>b.switchTab),o=T(b=>b.closeTab),a=T(b=>b.reopenTab),c=T(b=>b.deleteTab),l=T(b=>b.renameTab),i=T(b=>t?t.terminalIds.map(S=>{const N=b.terminalsMap[S];return N?{id:S,connected:N.connected}:{id:S,connected:!1}}):[]),[m,f]=d.useState(!1),[u,x]=d.useState(""),[p,h]=d.useState(!1),w=d.useRef(null);if(!t)return null;const C=n===e,v=t.status==="open",L=()=>{v&&r(e)},j=b=>{v&&(b.stopPropagation(),x(t.name),f(!0),setTimeout(()=>{var S;return(S=w.current)==null?void 0:S.focus()},0))},y=()=>{const b=u.trim();b&&l(e,b),f(!1)},R=b=>{b.stopPropagation(),a(e)},E=b=>{b.stopPropagation(),o(e)},D=async b=>{b.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},k=b=>{b.stopPropagation(),h(!p)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:v?"pointer":"default",borderLeft:C?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:C?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s",opacity:v?1:.5},onMouseEnter:b=>{v&&!C&&(b.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:b=>{C||(b.currentTarget.style.backgroundColor="transparent")},children:[v&&t.terminalIds.length>0&&s.jsx("button",{onClick:k,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:p?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[m?s.jsx("input",{ref:w,value:u,onChange:b=>x(b.target.value),onBlur:y,onKeyDown:b=>{b.key==="Enter"&&y(),b.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:j,style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:v?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",nt(Math.floor(t.createdAt/1e3))]})]}),v?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:E,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:R,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:D,title:"Delete tab",children:"×"})]})]}),v&&p&&i.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:i.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 Qn({sessionId:e,active:t,createdAt:n}){const r=T(l=>l.addTerminal),o=T(l=>l.killServerSession),a=()=>{r("horizontal",e)},c=l=>{l.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};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:l=>{l.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:nt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function er(){const e=T(i=>i.sidebarOpen),t=T(i=>i.toggleSidebar),n=T(i=>i.fetchSessions),r=T(i=>e?i.serverSessions:[]),o=T(i=>e?i.tabs:[]),a=T(i=>i.terminalIds.length),c=new Set(o.flatMap(i=>i.terminalIds)),l=r.filter(i=>!c.has(i.sessionId));return d.useEffect(()=>{if(!e)return;n();let i=setInterval(n,5e3);const m=()=>{document.hidden?i&&(clearInterval(i),i=null):(n(),i||(i=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",m),()=>{i&&clearInterval(i),document.removeEventListener("visibilitychange",m)}},[e,n]),d.useEffect(()=>{if(!e)return;const i=setTimeout(n,800);return()=>clearTimeout(i)},[a,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:e?"1px solid #292e42":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("span",{style:{color:"#7aa2f7",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Sessions"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"#7aa2f7",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid #292e42"},children:"TABS"}),o.length===0?s.jsx("div",{style:{color:"#565f89",fontSize:"13px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(i=>s.jsx(Zn,{tabId:i.id},i.id))]}),l.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"}),l.map(i=>s.jsx(Qn,{sessionId:i.sessionId,active:i.active,createdAt:i.createdAt},i.sessionId))]})]})]})}const st=we.memo(()=>{const e=T(y=>y.tabs),t=T(y=>y.activeTabId),n=T(y=>y.addTab),r=T(y=>y.switchTab),o=T(y=>y.closeTab),a=T(y=>y.renameTab),[c,l]=d.useState(null),[i,m]=d.useState(""),f=d.useRef(null),u=e.filter(y=>y.status==="open");d.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const x=y=>{l(y.id),m(y.name)},p=()=>{c&&i.trim()&&a(c,i.trim()),l(null),m("")},h=()=>{l(null),m("")},w=y=>{y.key==="Enter"?p():y.key==="Escape"&&h()},C=y=>{c||r(y)},v=(y,R)=>{y.stopPropagation(),o(R)},L=(y,R)=>{y.button===1&&(y.preventDefault(),o(R))},j=u.length>1;return s.jsxs("div",{className:"tab-bar",children:[u.map(y=>{const R=y.id===t,E=c===y.id,D=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${R?"tab-item--active":""}`,onClick:()=>C(y.id),onDoubleClick:()=>x(y),onMouseDown:k=>L(k,y.id),children:E?s.jsx("input",{ref:f,type:"text",value:i,onChange:k=>m(k.target.value),onBlur:p,onKeyDown:w,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",D>0&&`(${D})`]}),j&&s.jsx("button",{className:"tab-item__close",onClick:k=>v(k,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:"+"})]})});st.displayName="TabBar";function tr(){return localStorage.getItem("ai-cli-online-token")}function nr(){const e=T(i=>i.token),t=T(i=>i.setToken),n=T(i=>i.tabs),r=T(i=>i.addTab),o=T(i=>i.toggleSidebar),a=T(i=>i.fontSize),c=T(i=>i.setFontSize),l=T(i=>i.tabsLoading);return d.useEffect(()=>{const i=tr();i&&!e&&t(i)},[]),d.useEffect(()=>{e&&!l&&n.filter(i=>i.status==="open").length===0&&r("Default")},[e,l]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"#1a1b26"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"#7aa2f7",letterSpacing:"0.5px"},children:"AI-Cli Online"})}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>c(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(or,{}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Sessions Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Jn,{})}),s.jsx(er,{})]}),s.jsx(st,{})]}):s.jsx(on,{})}const rr=[1,2,3,4];function or(){const e=T(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="#9ece6a",n=4):e<150?(t="#e0af68",n=3):e<300?(t="#ff9e64",n=2):(t="#f7768e",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[rr.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}ye.createRoot(document.getElementById("root")).render(s.jsx(we.StrictMode,{children:s.jsx(rt,{children:s.jsx(nr,{})})}));
|
package/web/dist/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<!-- Fonts loaded locally from /fonts/ -->
|
|
8
8
|
<title>AI-Cli Online</title>
|
|
9
9
|
<link rel="preload" href="/fonts/JetBrainsMono-Regular.woff2" as="font" type="font/woff2" crossorigin />
|
|
10
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-C2U1eAjl.js"></script>
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/react-vendor-BCIvbQoU.js">
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/terminal-DnNpv9tw.js">
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/markdown-BERZKN_L.js">
|
package/web/package.json
CHANGED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
var at=Object.defineProperty;var lt=(e,t,n)=>t in e?at(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ke=(e,t,n)=>lt(e,typeof t!="symbol"?t+"":t,n);import{r as d,a as ct,g as dt,R as we}from"./react-vendor-BCIvbQoU.js";import{D as Be,o as Ue,L as ut,x as ft}from"./terminal-DnNpv9tw.js";import{d as pt,p as mt}from"./markdown-BERZKN_L.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const 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 We={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 ht=d,xt=Symbol.for("react.element"),bt=Symbol.for("react.fragment"),yt=Object.prototype.hasOwnProperty,gt=ht.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,wt={key:!0,ref:!0,__self:!0,__source:!0};function He(e,t,n){var r,o={},a=null,c=null;n!==void 0&&(a=""+n),t.key!==void 0&&(a=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)yt.call(t,r)&&!wt.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:xt,type:e,key:a,ref:c,props:o,_owner:gt.current}}de.Fragment=bt;de.jsx=He;de.jsxs=He;We.exports=de;var s=We.exports,ye={},Ie=ct;ye.createRoot=Ie.createRoot,ye.hydrateRoot=Ie.hydrateRoot;const vt={},Ce=e=>{let t;const n=new Set,r=(f,u)=>{const x=typeof f=="function"?f(t):f;if(!Object.is(x,t)){const m=t;t=u??(typeof x!="object"||x===null)?x:Object.assign({},t,x),n.forEach(h=>h(t,m))}},o=()=>t,l={setState:r,getState:o,getInitialState:()=>p,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},p=t=e(r,o,l);return l},St=e=>e?Ce(e):Ce;var Ve={exports:{}},Ge={},qe={exports:{}},Je={};/**
|
|
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 ne=d;function Tt(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var kt=typeof Object.is=="function"?Object.is:Tt,It=ne.useState,Ct=ne.useEffect,jt=ne.useLayoutEffect,Et=ne.useDebugValue;function Rt(e,t){var n=t(),r=It({inst:{value:n,getSnapshot:t}}),o=r[0].inst,a=r[1];return jt(function(){o.value=n,o.getSnapshot=t,he(o)&&a({inst:o})},[e,n,t]),Ct(function(){return he(o)&&a({inst:o}),e(function(){he(o)&&a({inst:o})})},[e]),Et(n),n}function he(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!kt(e,n)}catch{return!0}}function zt(e,t){return t()}var Lt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?zt:Rt;Je.useSyncExternalStore=ne.useSyncExternalStore!==void 0?ne.useSyncExternalStore:Lt;qe.exports=Je;var Dt=qe.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,Mt=Dt;function Nt(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ot=typeof Object.is=="function"?Object.is:Nt,At=Mt.useSyncExternalStore,Pt=ue.useRef,$t=ue.useEffect,_t=ue.useMemo,Ft=ue.useDebugValue;Ge.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var a=Pt(null);if(a.current===null){var c={hasValue:!1,value:null};a.current=c}else c=a.current;a=_t(function(){function l(m){if(!p){if(p=!0,f=m,m=r(m),o!==void 0&&c.hasValue){var h=c.value;if(o(h,m))return u=h}return u=m}if(h=u,Ot(f,m))return h;var I=r(m);return o!==void 0&&o(h,I)?(f=m,h):(f=m,u=I)}var p=!1,f,u,x=n===void 0?null:n;return[function(){return l(t())},x===null?void 0:function(){return l(x())}]},[t,n,r,o]);var i=At(e,a[0],a[1]);return $t(function(){c.hasValue=!0,c.value=i},[i]),Ft(i),i};Ve.exports=Ge;var Bt=Ve.exports;const Ut=dt(Bt),Ke={},{useDebugValue:Wt}=we,{useSyncExternalStoreWithSelector:Ht}=Ut;let je=!1;const Vt=e=>e;function Gt(e,t=Vt,n){(Ke?"production":void 0)!=="production"&&n&&!je&&(je=!0);const r=Ht(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Wt(r),r}const Ee=e=>{const t=typeof e=="function"?St(e):e,n=(r,o)=>Gt(t,r,o);return Object.assign(n,t),n},qt=e=>e?Ee(e):Ee,_="";function U(e){return{Authorization:`Bearer ${e}`}}async function Jt(e){try{const t=await fetch(`${_}/api/settings/font-size`,{headers:U(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function Kt(e,t){try{await fetch(`${_}/api/settings/font-size`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function Yt(e){try{const t=await fetch(`${_}/api/settings/tabs-layout`,{headers:U(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function Xt(e,t){try{await fetch(`${_}/api/settings/tabs-layout`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function Re(e,t){try{const n=`${_}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const ce="ai-cli-online-tabs",ze="ai-cli-online-layout",Le="ai-cli-online-session-names";function se(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let c=0;c<e.children.length;c++){const i=se(e.children[c],t);i!==null&&(n.push(i),r.push(e.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{...e,children:n,sizes:a}}function Ye(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(a=>Ye(a,t,n,r,o))}}function Xe(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Xe(r,t,n))}}function xe(e){return e.tabs.find(t=>t.id===e.activeTabId)}function X(e,t,n){return e.map(r=>r.id===t?n(r):r)}function V(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(ce,JSON.stringify(t))}catch{}Zt(t)}let ie=null,ae=null,Z=null,re=null;function Zt(e){re=e,Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,re=null;const t=S.getState().token;t&&Xt(t,e)},2e3)}function Qt(e){ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null,V(e)},500)}function en(){try{const e=localStorage.getItem(ce);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(ze);if(e){const t=JSON.parse(e);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:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(ce,JSON.stringify(o))}catch{}return localStorage.removeItem(ze),localStorage.removeItem(Le),o}}catch{}return null}function B(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function tn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.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=se(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=se(l,p));r.push({...c,terminalIds:i,layout:l})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(i=>i.status==="open");o=(c==null?void 0:c.id)||""}return{...e,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var t,n;const e=(n=(t=S==null?void 0:S.getState)==null?void 0:t.call(S))==null?void 0:n.token;if(e)if(re)Z&&(clearTimeout(Z),Z=null),Re(e,re),re=null;else{const r=S.getState();r.tabs.length>0&&Re(e,B(r))}});const S=qt((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Jt(n).then(o=>{t().token===n&&e({fontSize:o})});const r=en();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)||"";e({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 e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});nn(n,r);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(ce),e({token:n,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:n=>{const r=t(),o=`tab${r.nextTabId}`,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 e({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(B(t())),o},switchTab:n=>{const o=t().tabs.find(a=>a.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),V(B(t())))},closeTab:n=>{const r=t(),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(h=>h.id===n),x=i.filter(h=>h.status==="open"),m=x.find(h=>i.findIndex(C=>C.id===h.id)>u)||x[x.length-1];m&&(l=m.id,p=m.terminalIds,f=m.layout)}e({tabs:i,activeTabId:l,terminalsMap:c,terminalIds:p,layout:f}),V(B(t()))},reopenTab:n=>{const r=t(),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"}));e({tabs:c,activeTabId:n,terminalsMap:a,terminalIds:o.terminalIds,layout:o.layout}),V(B(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(m=>m.id===n);if(!o)return;const a=r.token;a&&await Promise.all(o.terminalIds.map(m=>fetch(`${_}/api/sessions/${encodeURIComponent(m)}`,{method:"DELETE",headers:U(a)}).catch(()=>{})));const c=t(),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,x=c.layout;if(c.activeTabId===n){const m=p.find(h=>h.status==="open");m?(f=m.id,u=m.terminalIds,x=m.layout):(f="",u=[],x=null)}e({tabs:p,activeTabId:f,terminalsMap:l,terminalIds:u,layout:x}),V(B(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=X(t().tabs,n,a=>({...a,name:r}));e({tabs:o}),V(B(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const a=xe(o);if(!a){const R=`tab${o.nextTabId}`,E=r||`t${o.nextId}`;let D=o.nextId;const T=E.match(/^t(\d+)$/);T&&(D=Math.max(D,parseInt(T[1],10)+1));const b=r?D:D+1,v={id:E,connected:!1,sessionResumed:!1,error:null},M={type:"leaf",terminalId:E},P={id:R,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[E],layout:M,createdAt:Date.now()};return e({tabs:[...o.tabs,P],activeTabId:R,nextTabId:o.nextTabId+1,nextId:b,terminalsMap:{...o.terminalsMap,[E]:v},terminalIds:[E],layout:M}),V(B(t())),E}const{nextId:c,nextSplitId:i,terminalsMap:l}=o,{terminalIds:p,layout:f}=a,u=r||`t${c}`;let x=c;const m=u.match(/^t(\d+)$/);m&&(x=Math.max(x,parseInt(m[1],10)+1));const h={id:u,connected:!1,sessionResumed:!1,error:null},I={type:"leaf",terminalId:u};let C,w=i;if(!f)C=I;else if(f.type==="leaf"){const R=n||"horizontal";C={id:`s${w}`,type:"split",direction:R,children:[f,I],sizes:[50,50]},w++}else if(f.direction===(n||"horizontal")){const E=100/(f.children.length+1),D=(100-E)/100,T=[...f.sizes.map(b=>b*D),E];C={...f,children:[...f.children,I],sizes:T}}else{const R=n||"horizontal";C={id:`s${w}`,type:"split",direction:R,children:[f,I],sizes:[50,50]},w++}const L=[...p,u],j=r?x:x+1,y=X(o.tabs,a.id,R=>({...R,terminalIds:L,layout:C}));return e({terminalsMap:{...l,[u]:h},terminalIds:L,layout:C,tabs:y,nextId:j,nextSplitId:w}),V(B(t())),u},splitTerminal:(n,r)=>{const o=t(),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},x=`s${i}`,m=Ye(a.layout,n,r,u,x),h=[...a.terminalIds,p],I=c+1,C=i+1,w=X(o.tabs,a.id,L=>({...L,terminalIds:h,layout:m}));return e({terminalsMap:{...l,[p]:f},terminalIds:h,layout:m,tabs:w,nextId:I,nextSplitId:C}),V(B(t())),p},removeTerminal:n=>{const r=t(),o=r.tabs.find(f=>f.terminalIds.includes(n));if(!o){const{[n]:f,...u}=r.terminalsMap;e({terminalsMap:u});return}const a=o.terminalIds.filter(f=>f!==n),c=o.layout?se(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?e({terminalsMap:p,terminalIds:a,layout:c,tabs:i}):e({terminalsMap:p,tabs:i}),V(B(t()))},setTerminalConnected:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,error:r}}}})},setSplitSizes:(n,r)=>{const o=t(),a=xe(o);if(!a||!a.layout)return;const c=Xe(a.layout,n,r),i=X(o.tabs,a.id,l=>({...l,layout:c}));e({layout:c,tabs:i}),Qt(B(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),ae&&clearTimeout(ae),ae=setTimeout(()=>{ae=null;const o=t().token;o&&Kt(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${_}/api/sessions`,{headers:U(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}},killServerSession:async n=>{const r=t().token;if(!r)return;try{await fetch(`${_}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:U(r)})}catch{}const o=t(),a=o.tabs.find(c=>c.terminalIds.includes(n));if(a){const c=a.terminalIds.filter(u=>u!==n),i=a.layout?se(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?e({terminalsMap:f,terminalIds:c,layout:i,tabs:l}):e({terminalsMap:f,tabs:l}),V(B(t()))}else{const{[n]:c,...i}=o.terminalsMap;e({terminalsMap:i})}setTimeout(()=>t().fetchSessions(),500)}}));async function nn(e,t){var o;const{setState:n,getState:r}=S;try{const[a,c]=await Promise.all([Yt(e),fetch(`${_}/api/sessions`,{headers:U(e)}).then(m=>m.ok?m.json():[]).catch(()=>[])]);if(r().token!==e)return;const i=a&&((o=a.tabs)==null?void 0:o.length)>0?a:t;if(!i||i.tabs.length===0){n({tabsLoading:!1});return}const l=tn(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 h of m.terminalIds)f[h]=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"),x=(u==null?void 0:u.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:l.tabs,activeTabId:x,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(B(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function rn(){const[e,t]=d.useState(""),n=S(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, #1a1b26 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"#24283b",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid #292e42"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, #7aa2f7 0%, #bb9af7 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"#1a1b26",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"#c0caf5",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"#565f89",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"#7aa2f7",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"#1a1b26",color:"#c0caf5",border:"1px solid #292e42",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:e.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#414868",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"#1a1b26",padding:"2px 6px",borderRadius:"4px",border:"1px solid #292e42",fontSize:"11px"},children:"server/.env"})]})})]})})}const on=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,le=500,sn=8e3,an=1e4,De=4e3,ln=5e3,cn=5,dn=64*1024,un=1,Me=2,fn=3,pn=4,mn=new TextDecoder,hn=new TextEncoder;function Ne(e,t){const n=hn.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function xn(e,t,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),f=d.useRef(n),u=d.useRef(!1),x=d.useRef(0),m=d.useRef(!0),h=d.useRef(!navigator.onLine),I=d.useRef(""),C=d.useRef(null),w=d.useRef("");f.current=n;const L=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),C.current&&(clearTimeout(C.current),C.current=null)},[]),j=d.useCallback(()=>{const{token:D,setTerminalError:T}=S.getState();if(!D||p.current)return;if(r.current){const P=r.current.readyState;if(P===WebSocket.OPEN||P===WebSocket.CONNECTING)return}u.current=!1;const b=`${on}?sessionId=${encodeURIComponent(t)}`,v=new WebSocket(b);v.binaryType="arraybuffer",l.current=window.setTimeout(()=>{v.readyState===WebSocket.CONNECTING&&v.close()},ln);const M=()=>{v.readyState===WebSocket.OPEN&&(x.current=performance.now(),v.send(JSON.stringify({type:"ping"})),i.current=window.setTimeout(()=>{x.current>0&&(x.current=0,v.close())},De))};v.onopen=()=>{l.current&&(clearTimeout(l.current),l.current=null),v.send(JSON.stringify({type:"auth",token:D})),T(t,null),o.current=le,m.current=!0},v.onclose=P=>{const{setTerminalConnected:W,setTerminalError:$,setToken:z}=S.getState();if(W(t,!1),L(),u.current)return;if(P.code===4001){p.current=!0,$(t,"Authentication failed"),z(null),localStorage.removeItem("ai-cli-online-token");return}if(P.code===4002)return;if(P.code===4005){$(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(m.current){m.current=!1,a.current=window.setTimeout(()=>j(),50);return}const N=o.current;o.current=Math.min(N*2,sn);const O=Math.round(N*(.5+Math.random()));a.current=window.setTimeout(()=>{j()},O)},v.onerror=()=>{},v.onmessage=P=>{var W;try{const $=e.current;if(P.data instanceof ArrayBuffer){const N=new Uint8Array(P.data);if(N.length<1)return;const O=N[0],G=N.subarray(1);switch(O){case un:$==null||$.write(G);break;case fn:$==null||$.write(G);break;case pn:{(W=f.current)==null||W.call(f,mn.decode(G));break}}return}const z=JSON.parse(P.data);switch(z.type){case"connected":{const N=S.getState();N.setTerminalConnected(t,!0),N.setTerminalResumed(t,z.resumed);const O=e.current;O&&v.readyState===WebSocket.OPEN&&v.send(JSON.stringify({type:"resize",cols:O.cols,rows:O.rows})),w.current&&(v.send(Ne(Me,w.current)),w.current=""),M(),c.current=window.setInterval(M,an);break}case"error":S.getState().setTerminalError(t,z.error);break;case"pong":{if(i.current&&(clearTimeout(i.current),i.current=null),x.current>0){const N=Math.round(performance.now()-x.current),O=S.getState();(O.terminalIds.length===0||O.terminalIds[0]===t)&&O.setLatency(N),x.current=0}break}}}catch{}},r.current=v},[t,e,L]),y=d.useCallback(D=>{const T=r.current;if(!T||T.readyState!==WebSocket.OPEN){w.current.length<dn&&(w.current+=D);return}I.current+=D,C.current||(C.current=window.setTimeout(()=>{const b=I.current;I.current="",C.current=null,b&&T.readyState===WebSocket.OPEN&&T.send(Ne(Me,b))},cn))},[]),R=d.useCallback((D,T)=>{var b;((b=r.current)==null?void 0:b.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:D,rows:T}))},[]),E=d.useCallback(()=>{var D;((D=r.current)==null?void 0:D.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]);return d.useEffect(()=>{S.getState().token&&(p.current=!1,j());const T=()=>{h.current=!1,o.current=le,m.current=!0;const M=r.current;(!M||M.readyState===WebSocket.CLOSED||M.readyState===WebSocket.CLOSING)&&j()},b=()=>{h.current=!0},v=()=>{if(document.visibilityState!=="visible")return;const M=r.current;if(!M||M.readyState!==WebSocket.OPEN){!h.current&&!u.current&&(o.current=le,m.current=!0,j());return}x.current=performance.now(),M.send(JSON.stringify({type:"ping"})),i.current&&clearTimeout(i.current),i.current=window.setTimeout(()=>{x.current>0&&(x.current=0,M.close())},De)};return window.addEventListener("online",T),window.addEventListener("offline",b),document.addEventListener("visibilitychange",v),()=>{u.current=!0,L(),window.removeEventListener("online",T),window.removeEventListener("offline",b),document.removeEventListener("visibilitychange",v),r.current&&(r.current.close(),r.current=null)}},[j,L,t]),{sendInput:y,sendResize:R,requestScrollback:E}}const Ze={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"},Qe="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",bn=d.forwardRef(function({sessionId:t},n){const r=d.useRef(null),o=d.useRef(null),a=d.useRef(null),[c,i]=d.useState(!1),[l,p]=d.useState(""),f=S(w=>w.fontSize),u=d.useCallback(w=>{p(w),i(!0)},[]),{sendInput:x,sendResize:m,requestScrollback:h}=xn(o,t,u);d.useImperativeHandle(n,()=>({sendInput:x}),[x]);const I=d.useRef(x),C=d.useRef(m);return I.current=x,C.current=m,d.useEffect(()=>{if(!r.current)return;let w=!1,L=null,j=null,y=null,R=null;if(w||!r.current)return;const E=new Be({cursorBlink:!0,scrollback:1e4,fontSize:S.getState().fontSize,fontFamily:Qe,theme:Ze,allowProposedApi:!0}),D=new Ue;E.loadAddon(D),E.loadAddon(new ut((v,M)=>{window.open(M,"_blank","noopener,noreferrer")})),E.open(r.current);try{const v=new ft;v.onContextLoss(()=>{v.dispose()}),E.loadAddon(v)}catch{}o.current=E,a.current=D;const T=()=>{try{const v=r.current;if(v&&v.clientWidth>0&&v.clientHeight>0)return D.fit(),C.current(E.cols,E.rows),!0}catch{}return!1};requestAnimationFrame(()=>T());let b=0;return L=setInterval(()=>{b++,(T()||b>=10)&&(clearInterval(L),L=null)},100),document.fonts.ready.then(()=>{if(!w)try{D.fit(),C.current(E.cols,E.rows)}catch{}}),E.onData(v=>{I.current(v)}),R=new ResizeObserver(()=>{j||(j=requestAnimationFrame(()=>{j=null;try{D.fit(),y&&clearTimeout(y),y=setTimeout(()=>{y=null,C.current(E.cols,E.rows)},50)}catch{}}))}),R.observe(r.current),()=>{w=!0,L&&clearInterval(L),j&&cancelAnimationFrame(j),y&&clearTimeout(y),R&&R.disconnect(),o.current&&(o.current.dispose(),o.current=null),a.current=null}},[t]),d.useEffect(()=>{const w=o.current,L=a.current;if(!(!w||!L)&&w.options.fontSize!==f){w.options.fontSize=f;try{L.fit()}catch{}C.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("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize: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(yn,{data:l,onClose:()=>{i(!1),p("")}})]})});function yn({data:e,onClose:t}){const n=d.useRef(null),r=d.useRef(t);r.current=t;const o=S(i=>i.fontSize),a=d.useRef(null),c=d.useRef(null);return d.useEffect(()=>{if(!n.current)return;const i=new Be({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:Qe,theme:Ze});a.current=i;const l=new Ue;c.current=l,i.loadAddon(l),i.open(n.current),requestAnimationFrame(()=>{try{l.fit()}catch{}i.write(e,()=>{i.scrollToBottom()})});let p=null;const f=new ResizeObserver(()=>{p||(p=requestAnimationFrame(()=>{p=null;try{l.fit()}catch{}}))});f.observe(n.current);const u=x=>{x.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}},[e]),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 oe(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:U(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function gn(e,t,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",`${_}/api/sessions/${encodeURIComponent(t)}/upload`),i.setRequestHeader("Authorization",`Bearer ${e}`),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 wn(e,t){const n=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:U(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function vn(e,t,n){const r=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:U(e)});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 ve({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=S(j=>j.token),[a,c]=d.useState(""),[i,l]=d.useState([]),[p,f]=d.useState(!0),[u,x]=d.useState(null),m=d.useRef(""),h=d.useCallback(async j=>{if(o){f(!0),x(null);try{const y=await oe(o,e,j);j||(m.current=y.cwd),c(y.cwd),l(n?n(y.files):y.files)}catch(y){x(y instanceof Error?y.message:"Failed to load files")}finally{f(!1)}}},[o,e,n]);d.useEffect(()=>{h()},[h]),d.useEffect(()=>{if(!r||!o)return;let j=!1;const y=setInterval(async()=>{if(!j)try{const R=await wn(o,e);if(j)return;if(R!==m.current){m.current=R;const E=await oe(o,e);if(j)return;c(E.cwd),l(n?n(E.files):E.files)}}catch{}},r);return()=>{j=!0,clearInterval(y)}},[r,o,e,n]);const I=d.useRef(t);I.current=t,d.useEffect(()=>{const j=y=>{y.key==="Escape"&&I.current()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[]);const C=d.useCallback(j=>{h(a+"/"+j)},[h,a]),w=d.useCallback(()=>{const j=a.replace(/\/[^/]+$/,"")||"/";h(j)},[h,a]),L=d.useCallback(()=>{h(a)},[h,a]);return{cwd:a,files:i,loading:p,error:u,setError:x,handleNavigate:C,handleGoUp:w,handleRefresh:L}}function Sn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function et(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Se({cwd:e,onGoUp:t,onRefresh:n,onClose:r}){return s.jsxs("div",{style:{padding:"6px 12px",background:"#24283b",borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[s.jsx("button",{onClick:t,style:{background:"none",border:"1px solid #414868",color:"#7aa2f7",borderRadius:3,padding:"1px 8px",fontSize:12,cursor:"pointer",flexShrink:0},title:"Go to parent directory",children:".."}),s.jsx("span",{style:{color:"#7aa2f7",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e||"..."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[s.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Refresh",children:"↻"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Close (ESC)",children:"✕"})]})]})}function Te({loading:e,error:t,empty:n,emptyText:r="Empty directory"}){return e?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):t?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:t}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function Tn({sessionId:e,onClose:t}){const n=S(h=>h.token),{cwd:r,files:o,loading:a,error:c,setError:i,handleNavigate:l,handleGoUp:p,handleRefresh:f}=ve({sessionId:e,onClose:t}),[u,x]=d.useState(null),m=async h=>{if(n){x(h);try{await vn(n,e,r+"/"+h)}catch(I){i(I instanceof Error?I.message:"Download failed")}finally{x(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Se,{cwd:r,onGoUp:p,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{loading:a,error:c,empty:o.length===0,emptyText:"Empty directory"}),!a&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&l(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:I=>{I.stopPropagation(),m(h.name)},disabled:u===h.name,style:{background:"none",border:"1px solid #414868",color:u===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:u===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:u===h.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:h.type==="directory"?"#7aa2f7":"#565f89"},children:h.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:h.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:h.type==="file"?Sn(h.size):""})]},h.name))]})]})}function kn({content:e}){const t=S(r=>r.fontSize),n=d.useMemo(()=>{if(!e)return"";const r=pt.parse(e,{async:!1});return mt.sanitize(r,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[e]);return e?s.jsx("div",{className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${t}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 In(e,t){const n=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:U(e)});return n.ok?(await n.json()).content??"":""}async function Oe(e,t,n){await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const Ae=[{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"}],Cn=d.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},a){const c=S(g=>g.fontSize),[i,l]=d.useState(""),p=d.useRef(null),f=d.useRef(),u=d.useRef(!1),[x,m]=d.useState(!1),[h,I]=d.useState(""),[C,w]=d.useState(0),[L,j]=d.useState(!1),[y,R]=d.useState(""),[E,D]=d.useState(""),[T,b]=d.useState(0),[v,M]=d.useState([]),[P,W]=d.useState(!1),$=d.useRef(""),z=d.useRef(null),N=d.useMemo(()=>{if(!h)return Ae;const g=h.toLowerCase();return Ae.filter(k=>k.cmd.toLowerCase().includes(g)||k.desc.toLowerCase().includes(g))},[h]),O=d.useMemo(()=>{let g=v;if(y){const k=y.toLowerCase();g=g.filter(A=>A.name.toLowerCase().includes(k))}return[...g].sort((k,A)=>k.type==="directory"&&A.type!=="directory"?-1:k.type!=="directory"&&A.type==="directory"?1:k.name.localeCompare(A.name))},[v,y]);d.useEffect(()=>{let g=!1;return In(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(()=>{Oe(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(!L)return;let g=!1;return W(!0),(async()=>{try{if(E){if(!$.current){const F=await oe(o,r);if(g)return;$.current=F.cwd}const k=`${$.current}/${E.replace(/\/$/,"")}`,A=await oe(o,r,k);if(g)return;M(A.files)}else{const k=await oe(o,r);if(g)return;$.current=k.cwd,M(k.files)}W(!1)}catch{if(g)return;M([]),W(!1)}})(),()=>{g=!0}},[L,E,o,r]),d.useEffect(()=>{if(!L||!z.current)return;const g=z.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[T,L]);const G=d.useCallback(()=>{const g=i.trim();g&&(t(g),l(""),Oe(o,r,"").catch(()=>{}))},[i,t,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 A=k.selectionStart,F=i.slice(0,A),K=i.slice(A),J=F.lastIndexOf(`
|
|
26
|
-
`)+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 it=H+ee.length;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=it,k.focus()})}else{const H=F+g+K;l(H);const ee=A+g.length;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=ee,k.focus()})}m(!1),I(""),w(0)},[i]),pe=d.useCallback(g=>{const k=p.current;if(!k)return;const A=k.selectionStart,F=i.slice(0,A),K=i.slice(A),Q=F.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!Q)return;const J=F.length-Q[0].length;if(g.type==="directory"){const Y="@"+E+g.name+"/",q=i.slice(0,J)+Y+K;l(q);const H=J+Y.length;D(E+g.name+"/"),R(""),b(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;j(!1),R(""),D(""),b(0),M([]),$.current="",requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=H,k.focus()})}},[i,E]),ot=d.useCallback(g=>{const k=g.target.value;l(k);const A=g.target.selectionStart,F=k.slice(0,A),K=F.lastIndexOf(`
|
|
27
|
-
`),J=F.slice(K+1).match(/^\/([a-zA-Z-]*)$/);if(J)m(!0),I(J[1]),w(0),j(!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;R(me),b(0),D(ee),j(!0)}else j(!1)}},[]),st=d.useCallback(g=>{if(x&&N.length>0){if(g.key==="ArrowDown"){g.preventDefault(),w(k=>(k+1)%N.length);return}if(g.key==="ArrowUp"){g.preventDefault(),w(k=>(k-1+N.length)%N.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),fe(N[C].cmd);return}if(g.key==="Escape"){g.preventDefault(),m(!1);return}}if(L&&O.length>0){if(g.key==="ArrowDown"){g.preventDefault(),b(k=>(k+1)%O.length);return}if(g.key==="ArrowUp"){g.preventDefault(),b(k=>(k-1+O.length)%O.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),pe(O[T]);return}if(g.key==="Escape"){g.preventDefault(),j(!1);return}}if(g.key==="Tab"){g.preventDefault();const k=p.current;if(k){const A=k.selectionStart,F=k.selectionEnd,K=i.slice(0,A)+" "+i.slice(F);l(K);const Q=A+2;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=Q})}return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),G())},[G,x,N,C,fe,i,L,O,T,pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[x&&N.length>0&&s.jsx("div",{className:"slash-dropdown",children:N.map((g,k)=>s.jsxs("div",{className:`slash-item${k===C?" slash-item--active":""}`,onMouseDown:A=>{A.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))}),L&&(P||O.length>0)&&s.jsx("div",{className:"file-dropdown",ref:z,children:P?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):O.map((g,k)=>s.jsxs("div",{className:`file-item${k===T?" file-item--active":""}`,onMouseDown:A=>{A.preventDefault(),pe(g)},onMouseEnter:()=>b(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:ot,onKeyDown:st,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function jn(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function En({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:a,error:c,handleNavigate:i,handleGoUp:l,handleRefresh:p}=ve({sessionId:e,onClose:n}),f=u=>{t(r+"/"+u)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Se,{cwd:r,onGoUp:l,onRefresh:p,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{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:x=>{x.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:x=>{x.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:jn(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 Rn="modulepreload",zn=function(e){return"/"+e},Pe={},Ln=function(t,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=zn(l),l in Pe)return;Pe[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":Rn,p||(u.as="script"),u.crossOrigin="",u.href=l,i&&u.setAttribute("nonce",i),document.head.appendChild(u),p)return new Promise((x,m)=>{u.addEventListener("load",x),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 t().catch(a)})};let ge=null,be=null;function Dn(){return be||(be=Ln(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(ge=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),be}function Mn({data:e,scrollRef:t}){const n=d.useRef(null),[r,o]=d.useState(null),[a,c]=d.useState(!0),i=d.useRef(0),l=p=>{n.current=p,t==null||t(p)};return d.useEffect(()=>{if(!e)return;const p=++i.current;return c(!0),o(null),(async()=>{try{if(await Dn(),!ge||p!==i.current)return;const f=atob(e),u=new Uint8Array(f.length);for(let I=0;I<f.length;I++)u[I]=f.charCodeAt(I);const x=await ge.getDocument({data:u}).promise;if(p!==i.current)return;const m=n.current;if(!m)return;for(;m.firstChild;)m.removeChild(m.firstChild);const h=m.clientWidth-24;for(let I=1;I<=x.numPages;I++){const C=await x.getPage(I);if(p!==i.current)return;const w=C.getViewport({scale:1}),L=Math.min(h/w.width,2),j=C.getViewport({scale:L}),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 R=y.getContext("2d");if(R){if(await C.render({canvasContext:R,viewport:j,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++}},[e]),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 $e(e,t,n,r){const o=new URLSearchParams({path:n});r&&o.set("since",String(r));const a=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/file-content?${o}`,{headers:U(e)});if(a.status===304)return null;if(!a.ok)throw new Error("Failed to fetch file content");return a.json()}function Nn(e=50,t=20,n=80){const[r,o]=d.useState(e),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 x=h=>{u||(u=requestAnimationFrame(()=>{u=null;const I=h.clientX-p.left,C=Math.min(n,Math.max(t,I/f*100));o(C)}))},m=()=>{u&&cancelAnimationFrame(u),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",m)};document.addEventListener("mousemove",x),document.addEventListener("mouseup",m)},[t,n]);return{leftWidthPercent:r,containerRef:a,onDividerMouseDown:c}}const On=3e3;function An(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":"text"}function _e(e){return e.split("/").pop()||e}function Pn(e){if(e.type==="directory")return"📁";const t=e.name.slice(e.name.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}const $n=3e3;function _n({sessionId:e,onSelect:t}){const n=d.useCallback(()=>{},[]),{cwd:r,files:o,loading:a,error:c,handleNavigate:i,handleGoUp:l,handleRefresh:p}=ve({sessionId:e,onClose:n,pollCwd:$n});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(Se,{cwd:r,onGoUp:l,onRefresh:p,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{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):t(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Pn(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 Fn({sessionId:e,token:t,onClose:n,onSend:r}){const[o,a]=d.useState(null),[c,i]=d.useState(""),[l,p]=d.useState(null),f=d.useRef(0),[u,x]=d.useState(!1),[m,h]=d.useState(!1),[I,C]=d.useState(!1),{leftWidthPercent:w,containerRef:L,onDividerMouseDown:j}=Nn(50),y=d.useRef(null),[R,E]=d.useState(!1),D=d.useRef(new Map),T=d.useRef(null),b=d.useRef(null),v=d.useCallback(()=>{if(!o)return;const z=m?b.current:T.current;z&&D.current.set(o,z.scrollTop)},[o,m]),M=d.useCallback(z=>{const N=D.current.get(z);N!=null&&requestAnimationFrame(()=>{const O=m?b.current:T.current;O&&(O.scrollTop=N)})},[m]),P=d.useCallback(z=>{v();const N=An(z);a(z),p(N),i(""),f.current=0,x(!1),$e(t,e,z).then(O=>{O&&(i(O.content),f.current=O.mtime,requestAnimationFrame(()=>M(z)))}).catch(()=>{})},[t,e,v,M]);d.useEffect(()=>{if(!o)return;let z=!1;const O=setInterval(async()=>{if(!z)try{const G=await $e(t,e,o,f.current);if(z)return;G&&(i(G.content),f.current=G.mtime)}catch{}},On);return()=>{z=!0,clearInterval(O)}},[t,e,o]);const W=d.useCallback(()=>{o&&navigator.clipboard.writeText(o).then(()=>{C(!0),setTimeout(()=>C(!1),1500)}).catch(()=>{})},[o]);d.useEffect(()=>{if(!m)return;const z=N=>{N.key==="Escape"&&(v(),h(!1))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m,v]),d.useEffect(()=>{o&&M(o)},[m,o,M]);const $=z=>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:z,style:{height:"100%",overflow:"auto"},children:s.jsx(kn,{content:c})}):l==="html"?s.jsx("div",{ref:z,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:c,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})}):l==="pdf"?s.jsx(Mn,{data:c,scrollRef:z}):s.jsx("div",{ref:z,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(_n,{sessionId:e,onSelect:P});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:()=>x(z=>!z),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:W,title:I?"Copied!":`Click to copy: ${o}`,children:I?"Copied!":_e(o)}),s.jsx("button",{className:"pane-btn",onClick:()=>{v(),h(!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 z;return(z=y.current)==null?void 0:z.send()},disabled:!R,title:"Send to terminal (Ctrl+Enter)",style:R?{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:L,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${w}%`,flexShrink:0},children:[$(z=>{T.current=z}),u&&s.jsx(En,{sessionId:e,onSelect:P,onClose:()=>x(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:j}),s.jsx("div",{className:"plan-editor-wrap",children:s.jsx(Cn,{ref:y,onSend:r,onContentChange:E,sessionId:e,token:t})})]}),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:()=>{v(),h(!1)},title:"Close expanded view (ESC)",children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:$(z=>{b.current=z})})]})]})}const Bn=100,Un=600,te=typeof window<"u"?window.matchMedia(`(max-width: ${Un-1}px)`):null;function Wn(){const[e,t]=d.useState(()=>(te==null?void 0:te.matches)??!1);return d.useEffect(()=>{if(!te)return;const n=r=>t(r.matches);return te.addEventListener("change",n),()=>te.removeEventListener("change",n)},[]),e}const Hn=d.memo(function({terminal:t,canClose:n}){const r=Wn(),o=S(T=>T.killServerSession),a=S(T=>T.splitTerminal),c=S(T=>T.token),i=d.useRef(null),l=d.useRef(null),[p,f]=d.useState(!1),[u,x]=d.useState(!1),[m,h]=d.useState(0),[I,C]=d.useState(!1),[w,L]=d.useState(50),j=d.useRef(null),y=async T=>{const b=T.target.files;if(!(!b||b.length===0||!c)){x(!0),h(0);try{await gn(c,t.id,b,v=>{h(v)})}catch(v){alert(`Upload failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{x(!1),h(0),i.current&&(i.current.value="")}}},R=d.useRef(),E=d.useCallback(T=>{if(l.current){const b=T.replace(/\r?\n/g," ").trimEnd();l.current.sendInput(b),R.current=window.setTimeout(()=>{var v;return(v=l.current)==null?void 0:v.sendInput("\r")},50)}},[]);d.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]);const D=d.useCallback(T=>{T.preventDefault();const b=j.current;if(!b)return;const v=b.getBoundingClientRect(),M=v.height;document.body.classList.add("resizing-panes-v");const P=$=>{const z=($.clientY-v.top)/M*100,N=Math.min(80,Math.max(20,z));L(100-N)},W=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",P),document.addEventListener("mouseup",W)},[]);return s.jsxs("div",{ref:j,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:t.connected?"#9ece6a":"#f7768e"}}),s.jsxs("span",{style:{fontSize:"11px",color:"#565f89"},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:i,type:"file",multiple:!0,style:{display:"none"},onChange:y}),s.jsx("button",{className:"pane-btn",onClick:()=>{var T;return(T=i.current)==null?void 0:T.click()},disabled:u,style:u?{color:"#e0af68"}:void 0,title:u?`Uploading ${m}%`:"Upload files","aria-label":"Upload files",children:u?`${m}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>f(T=>!T),style:p?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${I?" pane-btn--active":""}`,onClick:()=>C(T=>!T),title:"Toggle Document browser","aria-label":"Toggle Document browser",children:"Doc"}),s.jsx("button",{className:"pane-btn",onClick:()=>a(t.id,r?"vertical":"horizontal"),title:r?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>a(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"}),n&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>o(t.id),title:"Close terminal","aria-label":"Close terminal",children:"×"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(bn,{ref:l,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(26, 27, 38, 0.85)",zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"#565f89",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})}),p&&s.jsx(Tn,{sessionId:t.id,onClose:()=>f(!1)})]}),I&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:D}),s.jsx("div",{style:{height:`${w}%`,minHeight:Bn,flexShrink:0,overflow:"hidden"},children:s.jsx(Fn,{onSend:E,onClose:()=>C(!1),sessionId:t.id,token:c||""})})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:t.error})]})});class tt extends d.Component{constructor(){super(...arguments);ke(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 Vn=4,Fe=10;function Gn(){const e=S(o=>o.layout),t=S(o=>o.terminalIds.length),n=S(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#1a1b26"},children:s.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed #292e42",color:"#565f89",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(nt,{node:e,canClose:r})})}const nt=d.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(qn,{terminalId:t.terminalId,canClose:n}):s.jsx(Jn,{node:t,canClose:n})}),qn=d.memo(function({terminalId:t,canClose:n}){const r=S(o=>o.terminalsMap[t]);return r?s.jsx(tt,{inline:!0,children:s.jsx(Hn,{terminal:r,canClose:n})}):null}),Jn=d.memo(function({node:t,canClose:n}){const r=S(p=>p.setSplitSizes),o=d.useRef(null),a=t.direction==="horizontal",c=d.useRef(t.sizes);c.current=t.sizes;const i=d.useCallback((p,f)=>{f.preventDefault();const u=a?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const x=a?f.clientX:f.clientY,m=[...c.current],h=o.current,I=a?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let C=null;const w=j=>{C||(C=requestAnimationFrame(()=>{C=null;const E=((a?j.clientX:j.clientY)-x)/I*100,D=m[p]+E,T=m[p+1]-E;if(D>=Fe&&T>=Fe){const b=[...m];b[p]=D,b[p+1]=T,r(t.id,b)}}))},L=()=>{C&&cancelAnimationFrame(C),document.body.classList.remove(u),document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",L)};document.addEventListener("mousemove",w),document.addEventListener("mouseup",L)},[a,t.id,r]),l=[];return t.children.forEach((p,f)=>{const u=p.type==="leaf"?p.terminalId:p.id;l.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(nt,{node:p,canClose:n})},u)),f<t.children.length-1&&l.push(s.jsx("div",{onMouseDown:x=>i(f,x),style:{flex:`0 0 ${Vn}px`,cursor:a?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:a?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:l})});function Kn({tabId:e}){const t=S(b=>b.tabs.find(v=>v.id===e)),n=S(b=>b.activeTabId),r=S(b=>b.switchTab),o=S(b=>b.closeTab),a=S(b=>b.reopenTab),c=S(b=>b.deleteTab),i=S(b=>b.renameTab),l=S(b=>t?t.terminalIds.map(v=>{const M=b.terminalsMap[v];return M?{id:v,connected:M.connected}:{id:v,connected:!1}}):[]),[p,f]=d.useState(!1),[u,x]=d.useState(""),[m,h]=d.useState(!1),I=d.useRef(null);if(!t)return null;const C=n===e,w=t.status==="open",L=()=>{w&&r(e)},j=b=>{w&&(b.stopPropagation(),x(t.name),f(!0),setTimeout(()=>{var v;return(v=I.current)==null?void 0:v.focus()},0))},y=()=>{const b=u.trim();b&&i(e,b),f(!1)},R=b=>{b.stopPropagation(),a(e)},E=b=>{b.stopPropagation(),o(e)},D=async b=>{b.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},T=b=>{b.stopPropagation(),h(!m)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:w?"pointer":"default",borderLeft:C?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:C?"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:b=>{w&&!C&&(b.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:b=>{C||(b.currentTarget.style.backgroundColor="transparent")},children:[w&&t.terminalIds.length>0&&s.jsx("button",{onClick:T,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:I,value:u,onChange:b=>x(b.target.value),onBlur:y,onKeyDown:b=>{b.key==="Enter"&&y(),b.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:j,style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:w?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",et(Math.floor(t.createdAt/1e3))]})]}),w?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:E,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:R,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:D,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(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 Yn({sessionId:e,active:t,createdAt:n}){const r=S(i=>i.addTerminal),o=S(i=>i.killServerSession),a=()=>{r("horizontal",e)},c=i=>{i.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};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:t?"#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:e}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:et(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function Xn(){const e=S(l=>l.sidebarOpen),t=S(l=>l.toggleSidebar),n=S(l=>l.fetchSessions),r=S(l=>e?l.serverSessions:[]),o=S(l=>e?l.tabs:[]),a=S(l=>l.terminalIds.length),c=new Set(o.flatMap(l=>l.terminalIds)),i=r.filter(l=>!c.has(l.sessionId));return d.useEffect(()=>{if(!e)return;n();let l=setInterval(n,5e3);const p=()=>{document.hidden?l&&(clearInterval(l),l=null):(n(),l||(l=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",p),()=>{l&&clearInterval(l),document.removeEventListener("visibilitychange",p)}},[e,n]),d.useEffect(()=>{if(!e)return;const l=setTimeout(n,800);return()=>clearTimeout(l)},[a,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:e?"1px solid #292e42":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("span",{style:{color:"#7aa2f7",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Sessions"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"#7aa2f7",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid #292e42"},children:"TABS"}),o.length===0?s.jsx("div",{style:{color:"#565f89",fontSize:"13px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(l=>s.jsx(Kn,{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(Yn,{sessionId:l.sessionId,active:l.active,createdAt:l.createdAt},l.sessionId))]})]})]})}const rt=we.memo(()=>{const e=S(y=>y.tabs),t=S(y=>y.activeTabId),n=S(y=>y.addTab),r=S(y=>y.switchTab),o=S(y=>y.closeTab),a=S(y=>y.renameTab),[c,i]=d.useState(null),[l,p]=d.useState(""),f=d.useRef(null),u=e.filter(y=>y.status==="open");d.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const x=y=>{i(y.id),p(y.name)},m=()=>{c&&l.trim()&&a(c,l.trim()),i(null),p("")},h=()=>{i(null),p("")},I=y=>{y.key==="Enter"?m():y.key==="Escape"&&h()},C=y=>{c||r(y)},w=(y,R)=>{y.stopPropagation(),o(R)},L=(y,R)=>{y.button===1&&(y.preventDefault(),o(R))},j=u.length>1;return s.jsxs("div",{className:"tab-bar",children:[u.map(y=>{const R=y.id===t,E=c===y.id,D=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${R?"tab-item--active":""}`,onClick:()=>C(y.id),onDoubleClick:()=>x(y),onMouseDown:T=>L(T,y.id),children:E?s.jsx("input",{ref:f,type:"text",value:l,onChange:T=>p(T.target.value),onBlur:m,onKeyDown:I,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",D>0&&`(${D})`]}),j&&s.jsx("button",{className:"tab-item__close",onClick:T=>w(T,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:"+"})]})});rt.displayName="TabBar";function Zn(){return localStorage.getItem("ai-cli-online-token")}function Qn(){const e=S(l=>l.token),t=S(l=>l.setToken),n=S(l=>l.tabs),r=S(l=>l.addTab),o=S(l=>l.toggleSidebar),a=S(l=>l.fontSize),c=S(l=>l.setFontSize),i=S(l=>l.tabsLoading);return d.useEffect(()=>{const l=Zn();l&&!e&&t(l)},[]),d.useEffect(()=>{e&&!i&&n.filter(l=>l.status==="open").length===0&&r("Default")},[e,i]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"#1a1b26"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"#7aa2f7",letterSpacing:"0.5px"},children:"AI-Cli Online"})}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>c(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(tr,{}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Sessions Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Gn,{})}),s.jsx(Xn,{})]}),s.jsx(rt,{})]}):s.jsx(rn,{})}const er=[1,2,3,4];function tr(){const e=S(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="#9ece6a",n=4):e<150?(t="#e0af68",n=3):e<300?(t="#ff9e64",n=2):(t="#f7768e",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[er.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}ye.createRoot(document.getElementById("root")).render(s.jsx(we.StrictMode,{children:s.jsx(tt,{children:s.jsx(Qn,{})})}));
|