ai-cli-online 2.2.5 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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** | ~12 MB | ~300 MB+ |
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
- | **包大小** | ~12 MB | ~300 MB+ |
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online",
3
- "version": "2.2.5",
3
+ "version": "2.3.1",
4
4
  "description": "AI-Cli Online - Web Terminal for Claude Code via xterm.js + tmux",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -148,7 +148,7 @@ async function main() {
148
148
  function resolveSession(req, res) {
149
149
  if (!checkAuth(req, res))
150
150
  return null;
151
- const { sessionId } = req.params;
151
+ const sessionId = req.params.sessionId;
152
152
  if (!isValidSessionId(sessionId)) {
153
153
  res.status(400).json({ error: 'Invalid sessionId' });
154
154
  return null;
@@ -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',
@@ -1,5 +1,8 @@
1
1
  import { WebSocket } from 'ws';
2
- import { buildSessionName, isValidSessionId, tokenToSessionName, hasSession, createSession, captureScrollback, resizeSession, } from './tmux.js';
2
+ import { buildSessionName, isValidSessionId, tokenToSessionName, hasSession, createSession, captureScrollback, resizeSession, getCwd, } from './tmux.js';
3
+ import { validatePath } from './files.js';
4
+ import { createReadStream } from 'fs';
5
+ import { stat as fsStat } from 'fs/promises';
3
6
  import { PtySession } from './pty.js';
4
7
  /**
5
8
  * Binary protocol for hot-path messages (output/input/scrollback).
@@ -10,6 +13,11 @@ const BIN_TYPE_OUTPUT = 0x01;
10
13
  const BIN_TYPE_INPUT = 0x02;
11
14
  const BIN_TYPE_SCROLLBACK = 0x03;
12
15
  const BIN_TYPE_SCROLLBACK_CONTENT = 0x04;
16
+ const BIN_TYPE_FILE_CHUNK = 0x05;
17
+ const MAX_STREAM_SIZE = 50 * 1024 * 1024; // 50MB
18
+ const STREAM_CHUNK_SIZE = 64 * 1024; // 64KB highWaterMark
19
+ const STREAM_HIGH_WATER = 1024 * 1024; // 1MB backpressure threshold
20
+ const STREAM_LOW_WATER = 512 * 1024; // 512KB resume threshold
13
21
  /** Track active connections per session name to prevent duplicates */
14
22
  const activeConnections = new Map();
15
23
  /** Rate-limit failed WebSocket auth attempts per IP */
@@ -131,10 +139,12 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
131
139
  // First-message auth: wait for { type: 'auth', token } before setting up session.
132
140
  // A 5-second timeout ensures unauthenticated connections don't linger.
133
141
  let authenticated = !authToken; // skip auth if no token configured
142
+ let authenticatedToken = ''; // saved for buildSessionName in stream-file
134
143
  let sessionName = '';
135
144
  let ptySession = null;
136
145
  let sessionInitializing = false; // guard against concurrent initSession calls
137
146
  let lastScrollbackTime = 0; // throttle capture-scrollback requests
147
+ let activeFileStream = null;
138
148
  const SCROLLBACK_THROTTLE_MS = 2000;
139
149
  const AUTH_TIMEOUT = 5000;
140
150
  const authTimer = authToken
@@ -258,6 +268,7 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
258
268
  return;
259
269
  }
260
270
  authenticated = true;
271
+ authenticatedToken = msg.token;
261
272
  await initSession(msg.token);
262
273
  return;
263
274
  }
@@ -294,6 +305,76 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
294
305
  sendBinary(ws, BIN_TYPE_SCROLLBACK_CONTENT, normalized);
295
306
  break;
296
307
  }
308
+ case 'stream-file': {
309
+ // Cancel any existing stream
310
+ if (activeFileStream) {
311
+ activeFileStream.destroy();
312
+ activeFileStream = null;
313
+ }
314
+ try {
315
+ const cwd = await getCwd(sessionName);
316
+ const resolved = await validatePath(msg.path, cwd);
317
+ if (!resolved) {
318
+ send(ws, { type: 'file-stream-error', error: 'Invalid path' });
319
+ break;
320
+ }
321
+ const fileStat = await fsStat(resolved);
322
+ if (!fileStat.isFile()) {
323
+ send(ws, { type: 'file-stream-error', error: 'Not a file' });
324
+ break;
325
+ }
326
+ if (fileStat.size > MAX_STREAM_SIZE) {
327
+ send(ws, { type: 'file-stream-error', error: `File too large (${(fileStat.size / 1024 / 1024).toFixed(1)}MB > 50MB limit)` });
328
+ break;
329
+ }
330
+ send(ws, { type: 'file-stream-start', size: fileStat.size, mtime: fileStat.mtimeMs });
331
+ const stream = createReadStream(resolved, { highWaterMark: STREAM_CHUNK_SIZE });
332
+ activeFileStream = stream;
333
+ stream.on('data', (chunk) => {
334
+ const data = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
335
+ if (ws.readyState !== WebSocket.OPEN) {
336
+ stream.destroy();
337
+ return;
338
+ }
339
+ const buf = Buffer.allocUnsafe(1 + data.length);
340
+ buf[0] = BIN_TYPE_FILE_CHUNK;
341
+ buf.set(data, 1);
342
+ ws.send(buf);
343
+ // Backpressure: pause stream when WS send buffer is full
344
+ if (ws.bufferedAmount > STREAM_HIGH_WATER) {
345
+ stream.pause();
346
+ const checkDrain = () => {
347
+ if (ws.bufferedAmount < STREAM_LOW_WATER) {
348
+ stream.resume();
349
+ }
350
+ else {
351
+ setTimeout(checkDrain, 10);
352
+ }
353
+ };
354
+ setTimeout(checkDrain, 10);
355
+ }
356
+ });
357
+ stream.on('end', () => {
358
+ activeFileStream = null;
359
+ send(ws, { type: 'file-stream-end' });
360
+ });
361
+ stream.on('error', (err) => {
362
+ activeFileStream = null;
363
+ send(ws, { type: 'file-stream-error', error: err.message });
364
+ });
365
+ }
366
+ catch (err) {
367
+ send(ws, { type: 'file-stream-error', error: err instanceof Error ? err.message : 'Stream failed' });
368
+ }
369
+ break;
370
+ }
371
+ case 'cancel-stream': {
372
+ if (activeFileStream) {
373
+ activeFileStream.destroy();
374
+ activeFileStream = null;
375
+ }
376
+ break;
377
+ }
297
378
  }
298
379
  }
299
380
  catch (err) {
@@ -303,6 +384,10 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
303
384
  ws.on('close', () => {
304
385
  if (authTimer)
305
386
  clearTimeout(authTimer);
387
+ if (activeFileStream) {
388
+ activeFileStream.destroy();
389
+ activeFileStream = null;
390
+ }
306
391
  if (sessionName) {
307
392
  console.log(`[WS] Client disconnected, session: ${sessionName}`);
308
393
  if (activeConnections.get(sessionName) === ws) {
@@ -18,6 +18,11 @@ export type ClientMessage = {
18
18
  type: 'ping';
19
19
  } | {
20
20
  type: 'capture-scrollback';
21
+ } | {
22
+ type: 'stream-file';
23
+ path: string;
24
+ } | {
25
+ type: 'cancel-stream';
21
26
  };
22
27
  export type ServerMessage = {
23
28
  type: 'output';
@@ -37,4 +42,13 @@ export type ServerMessage = {
37
42
  } | {
38
43
  type: 'pong';
39
44
  timestamp: number;
45
+ } | {
46
+ type: 'file-stream-start';
47
+ size: number;
48
+ mtime: number;
49
+ } | {
50
+ type: 'file-stream-end';
51
+ } | {
52
+ type: 'file-stream-error';
53
+ error: string;
40
54
  };
@@ -0,0 +1,28 @@
1
+ var yt=Object.defineProperty;var vt=(e,t,n)=>t in e?yt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Me=(e,t,n)=>vt(e,typeof t!="symbol"?t+"":t,n);import{r as d,a as wt,g as St,R as Re}from"./react-vendor-BCIvbQoU.js";import{D as Qe,o as et,L as kt,x as tt}from"./terminal-DnNpv9tw.js";import{d as Ct,p as It}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 i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var nt={exports:{}},be={};/**
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 Tt=d,Et=Symbol.for("react.element"),jt=Symbol.for("react.fragment"),Rt=Object.prototype.hasOwnProperty,zt=Tt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Lt={key:!0,ref:!0,__self:!0,__source:!0};function rt(e,t,n){var r,o={},i=null,c=null;n!==void 0&&(i=""+n),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)Rt.call(t,r)&&!Lt.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:Et,type:e,key:i,ref:c,props:o,_owner:zt.current}}be.Fragment=jt;be.jsx=rt;be.jsxs=rt;nt.exports=be;var s=nt.exports,Ee={},Ne=wt;Ee.createRoot=Ne.createRoot,Ee.hydrateRoot=Ne.hydrateRoot;const Ot={},De=e=>{let t;const n=new Set,r=(f,p)=>{const m=typeof f=="function"?f(t):f;if(!Object.is(m,t)){const x=t;t=p??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(h=>h(t,x))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>u,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},u=t=e(r,o,a);return a},Mt=e=>e?De(e):De;var ot={exports:{}},st={},it={exports:{}},at={};/**
10
+ * @license React
11
+ * use-sync-external-store-shim.production.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var ie=d;function Nt(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Dt=typeof Object.is=="function"?Object.is:Nt,At=ie.useState,$t=ie.useEffect,Pt=ie.useLayoutEffect,Ft=ie.useDebugValue;function _t(e,t){var n=t(),r=At({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Pt(function(){o.value=n,o.getSnapshot=t,we(o)&&i({inst:o})},[e,n,t]),$t(function(){return we(o)&&i({inst:o}),e(function(){we(o)&&i({inst:o})})},[e]),Ft(n),n}function we(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Dt(e,n)}catch{return!0}}function Bt(e,t){return t()}var Wt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Bt:_t;at.useSyncExternalStore=ie.useSyncExternalStore!==void 0?ie.useSyncExternalStore:Wt;it.exports=at;var Ut=it.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 ge=d,Ht=Ut;function Vt(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gt=typeof Object.is=="function"?Object.is:Vt,qt=Ht.useSyncExternalStore,Yt=ge.useRef,Kt=ge.useEffect,Jt=ge.useMemo,Xt=ge.useDebugValue;st.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Yt(null);if(i.current===null){var c={hasValue:!1,value:null};i.current=c}else c=i.current;i=Jt(function(){function a(x){if(!u){if(u=!0,f=x,x=r(x),o!==void 0&&c.hasValue){var h=c.value;if(o(h,x))return p=h}return p=x}if(h=p,Gt(f,x))return h;var g=r(x);return o!==void 0&&o(h,g)?(f=x,h):(f=x,p=g)}var u=!1,f,p,m=n===void 0?null:n;return[function(){return a(t())},m===null?void 0:function(){return a(m())}]},[t,n,r,o]);var l=qt(e,i[0],i[1]);return Kt(function(){c.hasValue=!0,c.value=l},[l]),Xt(l),l};ot.exports=st;var Zt=ot.exports;const Qt=St(Zt),ct={},{useDebugValue:en}=Re,{useSyncExternalStoreWithSelector:tn}=Qt;let Ae=!1;const nn=e=>e;function rn(e,t=nn,n){(ct?"production":void 0)!=="production"&&n&&!Ae&&(Ae=!0);const r=tn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return en(r),r}const $e=e=>{const t=typeof e=="function"?Mt(e):e,n=(r,o)=>rn(t,r,o);return Object.assign(n,t),n},on=e=>e?$e(e):$e,U="";function Y(e){return{Authorization:`Bearer ${e}`}}async function sn(e){try{const t=await fetch(`${U}/api/settings/font-size`,{headers:Y(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function an(e,t){try{await fetch(`${U}/api/settings/font-size`,{method:"PUT",headers:{...Y(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function cn(e){try{const t=await fetch(`${U}/api/settings/tabs-layout`,{headers:Y(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function ln(e,t){try{await fetch(`${U}/api/settings/tabs-layout`,{method:"PUT",headers:{...Y(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function Pe(e,t){try{const n=`${U}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const he="ai-cli-online-tabs",Fe="ai-cli-online-layout",_e="ai-cli-online-session-names";function xe(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=xe(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),i=r.map(c=>c/o*100);return{...e,children:n,sizes:i}}function lt(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(i=>lt(i,t,n,r,o))}}function dt(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>dt(r,t,n))}}function Se(e){return e.tabs.find(t=>t.id===e.activeTabId)}function ee(e,t,n){return e.map(r=>r.id===t?n(r):r)}function q(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(he,JSON.stringify(t))}catch{}dn(t)}let fe=null,pe=null,te=null,ae=null;function dn(e){ae=e,te&&clearTimeout(te),te=setTimeout(()=>{te=null,ae=null;const t=E.getState().token;t&&ln(t,e)},2e3)}function un(e){fe&&clearTimeout(fe),fe=setTimeout(()=>{fe=null,q(e)},500)}function fn(){try{const e=localStorage.getItem(he);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(Fe);if(e){const t=JSON.parse(e);let n="Default";try{const i=localStorage.getItem(_e);if(i){const c=JSON.parse(i),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(he,JSON.stringify(o))}catch{}return localStorage.removeItem(Fe),localStorage.removeItem(_e),o}}catch{}return null}function V(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function pn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.tabs){if(c.status!=="open"){const u=c.terminalIds.filter(f=>n.has(f));if(u.length>0){let f=c.layout;for(const p of c.terminalIds)!n.has(p)&&f&&(f=xe(f,p));r.push({...c,terminalIds:u,layout:f})}continue}const l=c.terminalIds.filter(u=>n.has(u));if(l.length===0)continue;let a=c.layout;for(const u of c.terminalIds)!n.has(u)&&a&&(a=xe(a,u));r.push({...c,terminalIds:l,layout:a})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(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=E==null?void 0:E.getState)==null?void 0:t.call(E))==null?void 0:n.token;if(e)if(ae)te&&(clearTimeout(te),te=null),Pe(e,ae),ae=null;else{const r=E.getState();r.tabs.length>0&&Pe(e,V(r))}});function Be(e,t){const n=e.tabs.find(u=>u.terminalIds.includes(t));if(!n){const{[t]:u,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(u=>u!==t),o=n.layout?xe(n.layout,t):null,i=ee(e.tabs,n.id,u=>({...u,terminalIds:r,layout:o})),{[t]:c,...l}=e.terminalsMap,a={terminalsMap:l,tabs:i};return n.id===e.activeTabId&&(a.terminalIds=r,a.layout=o),a}const E=on((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}sn(n).then(o=>{t().token===n&&e({fontSize:o})});const r=fn();if(r&&r.tabs.length>0){const o={};for(const l of r.tabs)if(l.status==="open")for(const a of l.terminalIds)o[a]={id:a,connected:!1,sessionResumed:!1,error:null};const i=r.tabs.find(l=>l.id===r.activeTabId&&l.status==="open")||r.tabs.find(l=>l.status==="open"),c=(i==null?void 0:i.id)||"";e({token:n,tabsLoading:!0,terminalsMap:o,tabs:r.tabs,activeTabId:c,nextId:r.nextId,nextSplitId:r.nextSplitId,nextTabId:r.nextTabId,terminalIds:(i==null?void 0:i.terminalIds)||[],layout:(i==null?void 0:i.layout)||null})}else e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});mn(n,r);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(he),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}`,i=`t${r.nextId}`,c={id:i,connected:!1,sessionResumed:!1,error:null},l={type:"leaf",terminalId:i},a={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[i],layout:l,createdAt:Date.now()};return e({tabs:[...r.tabs,a],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[i]:c},terminalIds:a.terminalIds,layout:a.layout}),q(V(t())),o},switchTab:n=>{const o=t().tabs.find(i=>i.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),q(V(t())))},closeTab:n=>{const r=t(),o=r.tabs.find(p=>p.id===n);if(!o||o.status!=="open"||r.tabs.filter(p=>p.status==="open").length<=1)return;const c={...r.terminalsMap};for(const p of o.terminalIds)delete c[p];const l=ee(r.tabs,n,p=>({...p,status:"closed"}));let a=r.activeTabId,u=r.terminalIds,f=r.layout;if(r.activeTabId===n){const p=r.tabs.findIndex(h=>h.id===n),m=l.filter(h=>h.status==="open"),x=m.find(h=>l.findIndex(I=>I.id===h.id)>p)||m[m.length-1];x&&(a=x.id,u=x.terminalIds,f=x.layout)}e({tabs:l,activeTabId:a,terminalsMap:c,terminalIds:u,layout:f}),q(V(t()))},reopenTab:n=>{const r=t(),o=r.tabs.find(l=>l.id===n);if(!o||o.status!=="closed")return;const i={...r.terminalsMap};for(const l of o.terminalIds)i[l]={id:l,connected:!1,sessionResumed:!1,error:null};const c=ee(r.tabs,n,l=>({...l,status:"open"}));e({tabs:c,activeTabId:n,terminalsMap:i,terminalIds:o.terminalIds,layout:o.layout}),q(V(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(x=>x.id===n);if(!o)return;const i=r.token;i&&await Promise.all(o.terminalIds.map(x=>fetch(`${U}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:Y(i)}).catch(()=>{})));const c=t(),l=c.tabs.find(x=>x.id===n);if(!l)return;const a={...c.terminalsMap};for(const x of l.terminalIds)delete a[x];const u=c.tabs.filter(x=>x.id!==n);let f=c.activeTabId,p=c.terminalIds,m=c.layout;if(c.activeTabId===n){const x=u.find(h=>h.status==="open");x?(f=x.id,p=x.terminalIds,m=x.layout):(f="",p=[],m=null)}e({tabs:u,activeTabId:f,terminalsMap:a,terminalIds:p,layout:m}),q(V(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=ee(t().tabs,n,i=>({...i,name:r}));e({tabs:o}),q(V(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const i=Se(o);if(!i){const O=`tab${o.nextTabId}`,k=r||`t${o.nextId}`;let R=o.nextId;const T=k.match(/^t(\d+)$/);T&&(R=Math.max(R,parseInt(T[1],10)+1));const j=r?R:R+1,b={id:k,connected:!1,sessionResumed:!1,error:null},L={type:"leaf",terminalId:k},M={id:O,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[k],layout:L,createdAt:Date.now()};return e({tabs:[...o.tabs,M],activeTabId:O,nextTabId:o.nextTabId+1,nextId:j,terminalsMap:{...o.terminalsMap,[k]:b},terminalIds:[k],layout:L}),q(V(t())),k}const{nextId:c,nextSplitId:l,terminalsMap:a}=o,{terminalIds:u,layout:f}=i,p=r||`t${c}`;let m=c;const x=p.match(/^t(\d+)$/);x&&(m=Math.max(m,parseInt(x[1],10)+1));const h={id:p,connected:!1,sessionResumed:!1,error:null},g={type:"leaf",terminalId:p};let I,C=l;if(!f)I=g;else if(f.type==="leaf"){const O=n||"horizontal";I={id:`s${C}`,type:"split",direction:O,children:[f,g],sizes:[50,50]},C++}else if(f.direction===(n||"horizontal")){const k=100/(f.children.length+1),R=(100-k)/100,T=[...f.sizes.map(j=>j*R),k];I={...f,children:[...f.children,g],sizes:T}}else{const O=n||"horizontal";I={id:`s${C}`,type:"split",direction:O,children:[f,g],sizes:[50,50]},C++}const w=[...u,p],v=r?m:m+1,y=ee(o.tabs,i.id,O=>({...O,terminalIds:w,layout:I}));return e({terminalsMap:{...a,[p]:h},terminalIds:w,layout:I,tabs:y,nextId:v,nextSplitId:C}),q(V(t())),p},splitTerminal:(n,r)=>{const o=t(),i=Se(o);if(!i||!i.layout)return"";const{nextId:c,nextSplitId:l,terminalsMap:a}=o,u=`t${c}`,f={id:u,connected:!1,sessionResumed:!1,error:null},p={type:"leaf",terminalId:u},m=`s${l}`,x=lt(i.layout,n,r,p,m),h=[...i.terminalIds,u],g=c+1,I=l+1,C=ee(o.tabs,i.id,w=>({...w,terminalIds:h,layout:x}));return e({terminalsMap:{...a,[u]:f},terminalIds:h,layout:x,tabs:C,nextId:g,nextSplitId:I}),q(V(t())),u},removeTerminal:n=>{const r=Be(t(),n);r&&(e(r),q(V(t())))},setTerminalConnected:(n,r)=>{e(o=>{const i=o.terminalsMap[n];return!i||i.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...i,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const i=o.terminalsMap[n];return!i||i.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...i,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const i=o.terminalsMap[n];return!i||i.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...i,error:r}}}})},setSplitSizes:(n,r)=>{const o=t(),i=Se(o);if(!i||!i.layout)return;const c=dt(i.layout,n,r),l=ee(o.tabs,i.id,a=>({...a,layout:c}));e({layout:c,tabs:l}),un(V(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),pe&&clearTimeout(pe),pe=setTimeout(()=>{pe=null;const o=t().token;o&&an(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(`${U}/api/sessions`,{headers:Y(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(`${U}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:Y(r)})}catch{}const o=Be(t(),n);o&&(e(o),q(V(t()))),setTimeout(()=>t().fetchSessions(),500)}}));async function mn(e,t){var o;const{setState:n,getState:r}=E;try{const[i,c]=await Promise.all([cn(e),fetch(`${U}/api/sessions`,{headers:Y(e)}).then(x=>x.ok?x.json():[]).catch(()=>[])]);if(r().token!==e)return;const l=i&&((o=i.tabs)==null?void 0:o.length)>0?i:t;if(!l||l.tabs.length===0){n({tabsLoading:!1});return}const a=pn(l,c);if(!a){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:[],layout:null});return}const u=r().terminalsMap,f={};for(const x of a.tabs)if(x.status==="open")for(const h of x.terminalIds)f[h]=u[h]||{id:h,connected:!1,sessionResumed:!1,error:null};const p=a.tabs.find(x=>x.id===a.activeTabId&&x.status==="open")||a.tabs.find(x=>x.status==="open"),m=(p==null?void 0:p.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:a.tabs,activeTabId:m,nextId:a.nextId,nextSplitId:a.nextSplitId,nextTabId:a.nextTabId,terminalIds:(p==null?void 0:p.terminalIds)||[],layout:(p==null?void 0:p.layout)||null}),q(V(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function hn(){const[e,t]=d.useState(""),n=E(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 ye=new Map;function xn(e,t,n){ye.set(e,{onChunk:t,onControl:n})}function bn(e){ye.delete(e)}function gn(e,t){var n;(n=ye.get(e))==null||n.onChunk(t)}function yn(e,t){var n;(n=ye.get(e))==null||n.onControl(t)}const vn=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,me=500,wn=8e3,Sn=1e4,We=4e3,kn=5e3,Cn=5,In=64*1024,Tn=1,Ue=2,En=3,jn=4,Rn=5,zn=new TextDecoder,Ln=new TextEncoder;function He(e,t){const n=Ln.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function On(e,t,n){const r=d.useRef(null),o=d.useRef(me),i=d.useRef(null),c=d.useRef(null),l=d.useRef(null),a=d.useRef(null),u=d.useRef(!1),f=d.useRef(n),p=d.useRef(!1),m=d.useRef(0),x=d.useRef(!0),h=d.useRef(!navigator.onLine),g=d.useRef(""),I=d.useRef(null),C=d.useRef("");f.current=n;const w=d.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),i.current&&(clearTimeout(i.current),i.current=null),a.current&&(clearTimeout(a.current),a.current=null),I.current&&(clearTimeout(I.current),I.current=null)},[]),v=d.useCallback(()=>{const{token:j,setTerminalError:b}=E.getState();if(!j||u.current)return;if(r.current){const D=r.current.readyState;if(D===WebSocket.OPEN||D===WebSocket.CONNECTING)return}p.current=!1;const L=`${vn}?sessionId=${encodeURIComponent(t)}`,M=new WebSocket(L);M.binaryType="arraybuffer",a.current=window.setTimeout(()=>{M.readyState===WebSocket.CONNECTING&&M.close()},kn);const A=()=>{M.readyState===WebSocket.OPEN&&(m.current=performance.now(),M.send(JSON.stringify({type:"ping"})),l.current=window.setTimeout(()=>{m.current>0&&(m.current=0,M.close())},We))};M.onopen=()=>{a.current&&(clearTimeout(a.current),a.current=null),M.send(JSON.stringify({type:"auth",token:j})),b(t,null),o.current=me,x.current=!0},M.onclose=D=>{const{setTerminalConnected:_,setTerminalError:P,setToken:B}=E.getState();if(_(t,!1),w(),p.current)return;if(D.code===4001){u.current=!0,P(t,"Authentication failed"),B(null),localStorage.removeItem("ai-cli-online-token");return}if(D.code===4002)return;if(D.code===4005){P(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(x.current){x.current=!1,i.current=window.setTimeout(()=>v(),50);return}const N=o.current;o.current=Math.min(N*2,wn);const $=Math.round(N*(.5+Math.random()));i.current=window.setTimeout(()=>{v()},$)},M.onerror=()=>{},M.onmessage=D=>{var _;try{const P=e.current;if(D.data instanceof ArrayBuffer){const N=new Uint8Array(D.data);if(N.length<1)return;const $=N[0],W=N.subarray(1);switch($){case Tn:P==null||P.write(W);break;case En:P==null||P.write(W);break;case jn:{(_=f.current)==null||_.call(f,zn.decode(W));break}case Rn:{gn(t,W);break}}return}const B=JSON.parse(D.data);switch(B.type){case"connected":{const N=E.getState();N.setTerminalConnected(t,!0),N.setTerminalResumed(t,B.resumed);const $=e.current;$&&M.readyState===WebSocket.OPEN&&M.send(JSON.stringify({type:"resize",cols:$.cols,rows:$.rows})),C.current&&(M.send(He(Ue,C.current)),C.current=""),A(),c.current=window.setInterval(A,Sn);break}case"error":E.getState().setTerminalError(t,B.error);break;case"pong":{if(l.current&&(clearTimeout(l.current),l.current=null),m.current>0){const N=Math.round(performance.now()-m.current),$=E.getState();($.terminalIds.length===0||$.terminalIds[0]===t)&&$.setLatency(N),m.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":yn(t,B);break}}catch{}},r.current=M},[t,e,w]),y=d.useCallback(j=>{const b=r.current;if(!b||b.readyState!==WebSocket.OPEN){C.current.length<In&&(C.current+=j);return}g.current+=j,I.current||(I.current=window.setTimeout(()=>{const L=g.current;g.current="",I.current=null,L&&b.readyState===WebSocket.OPEN&&b.send(He(Ue,L))},Cn))},[]),O=d.useCallback((j,b)=>{var L;((L=r.current)==null?void 0:L.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:j,rows:b}))},[]),k=d.useCallback(()=>{var j;((j=r.current)==null?void 0:j.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),R=d.useCallback(j=>{var b;((b=r.current)==null?void 0:b.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:j}))},[]),T=d.useCallback(()=>{var j;((j=r.current)==null?void 0:j.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return d.useEffect(()=>{E.getState().token&&(u.current=!1,v());const b=()=>{h.current=!1,o.current=me,x.current=!0;const A=r.current;(!A||A.readyState===WebSocket.CLOSED||A.readyState===WebSocket.CLOSING)&&v()},L=()=>{h.current=!0},M=()=>{if(document.visibilityState!=="visible")return;const A=r.current;if(!A||A.readyState!==WebSocket.OPEN){!h.current&&!p.current&&(o.current=me,x.current=!0,v());return}m.current=performance.now(),A.send(JSON.stringify({type:"ping"})),l.current&&clearTimeout(l.current),l.current=window.setTimeout(()=>{m.current>0&&(m.current=0,A.close())},We)};return window.addEventListener("online",b),window.addEventListener("offline",L),document.addEventListener("visibilitychange",M),()=>{p.current=!0,w(),window.removeEventListener("online",b),window.removeEventListener("offline",L),document.removeEventListener("visibilitychange",M),r.current&&(r.current.close(),r.current=null)}},[v,w,t]),{sendInput:y,sendResize:O,requestScrollback:k,requestFileStream:R,cancelFileStream:T}}const ut={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"},ft="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",Mn=d.forwardRef(function({sessionId:t},n){const r=d.useRef(null),o=d.useRef(null),i=d.useRef(null),[c,l]=d.useState(!1),[a,u]=d.useState(""),f=E(v=>v.fontSize),p=d.useCallback(v=>{u(v),l(!0)},[]),{sendInput:m,sendResize:x,requestScrollback:h,requestFileStream:g,cancelFileStream:I}=On(o,t,p);d.useImperativeHandle(n,()=>({sendInput:m,requestFileStream:g,cancelFileStream:I}),[m,g,I]);const C=d.useRef(m),w=d.useRef(x);return C.current=m,w.current=x,d.useEffect(()=>{if(!r.current)return;let v=!1,y=null,O=null,k=null,R=null;if(v||!r.current)return;const T=new Qe({cursorBlink:!0,scrollback:1e4,fontSize:E.getState().fontSize,fontFamily:ft,theme:ut,allowProposedApi:!0}),j=new et;T.loadAddon(j),T.loadAddon(new kt((M,A)=>{window.open(A,"_blank","noopener,noreferrer")})),T.open(r.current);try{const M=new tt;M.onContextLoss(()=>{M.dispose()}),T.loadAddon(M)}catch{}o.current=T,i.current=j;const b=()=>{try{const M=r.current;if(M&&M.clientWidth>0&&M.clientHeight>0)return j.fit(),w.current(T.cols,T.rows),!0}catch{}return!1};requestAnimationFrame(()=>b());let L=0;return y=setInterval(()=>{L++,(b()||L>=10)&&(clearInterval(y),y=null)},100),document.fonts.ready.then(()=>{if(!v)try{j.fit(),w.current(T.cols,T.rows)}catch{}}),T.onData(M=>{C.current(M)}),R=new ResizeObserver(()=>{O||(O=requestAnimationFrame(()=>{O=null;try{j.fit(),k&&clearTimeout(k),k=setTimeout(()=>{k=null,w.current(T.cols,T.rows)},50)}catch{}}))}),R.observe(r.current),()=>{v=!0,y&&clearInterval(y),O&&cancelAnimationFrame(O),k&&clearTimeout(k),R&&R.disconnect(),o.current&&(o.current.dispose(),o.current=null),i.current=null}},[t]),d.useEffect(()=>{const v=o.current,y=i.current;if(!(!v||!y)&&v.options.fontSize!==f){v.options.fontSize=f;try{y.fit()}catch{}w.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),u("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize: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(Nn,{data:a,onClose:()=>{l(!1),u("")}})]})});function Nn({data:e,onClose:t}){const n=d.useRef(null),r=d.useRef(t);r.current=t;const o=E(a=>a.fontSize),i=d.useRef(null),c=d.useRef(null);d.useEffect(()=>{if(!n.current)return;const a=new Qe({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:ft,theme:ut});i.current=a;const u=new et;c.current=u,a.loadAddon(u),a.open(n.current);try{const g=new tt;g.onContextLoss(()=>g.dispose()),a.loadAddon(g)}catch{}a.attachCustomKeyEventHandler(g=>(g.key==="Escape"&&r.current(),!1)),a.write(e);let f=null;const p=()=>{const g=n.current;if(!g||g.clientWidth<=0||g.clientHeight<=0)return!1;try{return u.fit(),a.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!p()){let g=0;f=setInterval(()=>{g++,(p()||g>=30)&&(clearInterval(f),f=null)},50)}});let m=null;const x=new ResizeObserver(()=>{m||(m=requestAnimationFrame(()=>{m=null,p()}))});x.observe(n.current);const h=g=>{g.key==="Escape"&&r.current()};return document.addEventListener("keydown",h),()=>{f&&clearInterval(f),m&&cancelAnimationFrame(m),document.removeEventListener("keydown",h),x.disconnect(),a.dispose(),i.current=null,c.current=null}},[e]),d.useEffect(()=>{var a;if(i.current){i.current.options.fontSize=o;try{(a=c.current)==null||a.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 ce(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${U}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:Y(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function Dn(e,t,n,r){return new Promise((o,i)=>{const c=new FormData;for(const a of n)c.append("files",a);const l=new XMLHttpRequest;l.open("POST",`${U}/api/sessions/${encodeURIComponent(t)}/upload`),l.setRequestHeader("Authorization",`Bearer ${e}`),l.upload.addEventListener("progress",a=>{a.lengthComputable&&r&&r(Math.round(a.loaded/a.total*100))}),l.addEventListener("load",()=>{l.status>=200&&l.status<300?o():i(new Error(`Upload failed: ${l.status}`))}),l.addEventListener("error",()=>i(new Error("Upload network error"))),l.addEventListener("abort",()=>i(new Error("Upload aborted"))),l.send(c)})}async function An(e,t){const n=await fetch(`${U}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:Y(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function $n(e,t,n){const r=await fetch(`${U}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:Y(e)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),i=URL.createObjectURL(o),c=document.createElement("a");c.href=i,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(i)}function ze({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=E(v=>v.token),[i,c]=d.useState(""),[l,a]=d.useState([]),[u,f]=d.useState(!0),[p,m]=d.useState(null),x=d.useRef(""),h=d.useCallback(async v=>{if(o){f(!0),m(null);try{const y=await ce(o,e,v);v||(x.current=y.cwd),c(y.cwd),a(n?n(y.files):y.files)}catch(y){m(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 v=!1;const y=setInterval(async()=>{if(!v)try{const O=await An(o,e);if(v)return;if(O!==x.current){x.current=O;const k=await ce(o,e);if(v)return;c(k.cwd),a(n?n(k.files):k.files)}}catch{}},r);return()=>{v=!0,clearInterval(y)}},[r,o,e,n]);const g=d.useRef(t);g.current=t,d.useEffect(()=>{const v=y=>{y.key==="Escape"&&g.current()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[]);const I=d.useCallback(v=>{h(i+"/"+v)},[h,i]),C=d.useCallback(()=>{const v=i.replace(/\/[^/]+$/,"")||"/";h(v)},[h,i]),w=d.useCallback(()=>{h(i)},[h,i]);return{cwd:i,files:l,loading:u,error:p,setError:m,handleNavigate:I,handleGoUp:C,handleRefresh:w}}function Pn(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 pt(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 Le({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 Oe({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 Fn({sessionId:e,onClose:t}){const n=E(h=>h.token),{cwd:r,files:o,loading:i,error:c,setError:l,handleNavigate:a,handleGoUp:u,handleRefresh:f}=ze({sessionId:e,onClose:t}),[p,m]=d.useState(null),x=async h=>{if(n){m(h);try{await $n(n,e,r+"/"+h)}catch(g){l(g instanceof Error?g.message:"Download failed")}finally{m(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Le,{cwd:r,onGoUp:u,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Oe,{loading:i,error:c,empty:o.length===0,emptyText:"Empty directory"}),!i&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&a(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:g=>{g.stopPropagation(),x(h.name)},disabled:p===h.name,style:{background:"none",border:"1px solid #414868",color:p===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:p===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:p===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"?Pn(h.size):""})]},h.name))]})]})}function _n({content:e}){const t=E(r=>r.fontSize),n=d.useMemo(()=>{if(!e)return"";const r=Ct.parse(e,{async:!1});return It.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 Bn(e,t){const n=await fetch(`${U}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:Y(e)});return n.ok?(await n.json()).content??"":""}async function Ve(e,t,n){await fetch(`${U}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...Y(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const Ge=[{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/token-planner",desc:"Task complexity grading & token routing"}],Wn=d.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},i){const c=E(S=>S.fontSize),[l,a]=d.useState(""),u=d.useRef(null),f=d.useRef(void 0),p=d.useRef(!1),[m,x]=d.useState(!1),[h,g]=d.useState(""),[I,C]=d.useState(0),[w,v]=d.useState(!1),[y,O]=d.useState(""),[k,R]=d.useState(""),[T,j]=d.useState(0),[b,L]=d.useState([]),[M,A]=d.useState(!1),D=d.useRef(""),_=d.useRef(null),P=d.useMemo(()=>{if(!h)return Ge;const S=h.toLowerCase();return Ge.filter(z=>z.cmd.toLowerCase().includes(S)||z.desc.toLowerCase().includes(S))},[h]),B=d.useMemo(()=>{let S=b;if(y){const z=y.toLowerCase();S=S.filter(F=>F.name.toLowerCase().includes(z))}return[...S].sort((z,F)=>z.type==="directory"&&F.type!=="directory"?-1:z.type!=="directory"&&F.type==="directory"?1:z.name.localeCompare(F.name))},[b,y]);d.useEffect(()=>{let S=!1;return Bn(o,r).then(z=>{!S&&z&&a(z),p.current=!0}).catch(()=>{p.current=!0}),()=>{S=!0}},[o,r]),d.useEffect(()=>{if(p.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{Ve(o,r,l).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[l,o,r]),d.useEffect(()=>{var S;(S=u.current)==null||S.focus()},[]),d.useEffect(()=>{if(!w)return;let S=!1;return A(!0),(async()=>{try{if(k){if(!D.current){const H=await ce(o,r);if(S)return;D.current=H.cwd}const z=`${D.current}/${k.replace(/\/$/,"")}`,F=await ce(o,r,z);if(S)return;L(F.files)}else{const z=await ce(o,r);if(S)return;D.current=z.cwd,L(z.files)}A(!1)}catch{if(S)return;L([]),A(!1)}})(),()=>{S=!0}},[w,k,o,r]),d.useEffect(()=>{if(!w||!_.current)return;const S=_.current.querySelector(".file-item--active");S==null||S.scrollIntoView({block:"nearest"})},[T,w]);const N=d.useCallback(()=>{const S=l.trim();S&&(t(S),a(""),Ve(o,r,"").catch(()=>{}))},[l,t,o,r]);d.useImperativeHandle(i,()=>({send:N}),[N]),d.useEffect(()=>{n==null||n(l.trim().length>0)},[l,n]);const $=d.useCallback(S=>{const z=u.current;if(!z)return;const F=z.selectionStart,H=l.slice(0,F),X=l.slice(F),J=H.lastIndexOf(`
26
+ `)+1,K=H.slice(J).match(/\/[a-zA-Z-]*$/);if(K){const G=J+(K.index??0),oe=S+" ",ve=l.slice(0,G)+oe+X;a(ve);const gt=G+oe.length;requestAnimationFrame(()=>{z.selectionStart=z.selectionEnd=gt,z.focus()})}else{const G=H+S+X;a(G);const oe=F+S.length;requestAnimationFrame(()=>{z.selectionStart=z.selectionEnd=oe,z.focus()})}x(!1),g(""),C(0)},[l]),W=d.useCallback(S=>{const z=u.current;if(!z)return;const F=z.selectionStart,H=l.slice(0,F),X=l.slice(F),re=H.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!re)return;const J=H.length-re[0].length;if(S.type==="directory"){const Z="@"+k+S.name+"/",K=l.slice(0,J)+Z+X;a(K);const G=J+Z.length;R(k+S.name+"/"),O(""),j(0),requestAnimationFrame(()=>{z.selectionStart=z.selectionEnd=G,z.focus()})}else{const Z=S.name+" ",K=l.slice(0,J)+Z+X;a(K);const G=J+Z.length;v(!1),O(""),R(""),j(0),L([]),D.current="",requestAnimationFrame(()=>{z.selectionStart=z.selectionEnd=G,z.focus()})}},[l,k]),ne=d.useCallback(S=>{const z=S.target.value;a(z);const F=S.target.selectionStart,H=z.slice(0,F),X=H.lastIndexOf(`
27
+ `),J=H.slice(X+1).match(/^\/([a-zA-Z-]*)$/);if(J)x(!0),g(J[1]),C(0),v(!1);else{x(!1);const Z=H.match(/@([a-zA-Z0-9_.\-/]*)$/);if(Z){const K=Z[1],G=K.lastIndexOf("/"),oe=G>=0?K.slice(0,G+1):"",ve=G>=0?K.slice(G+1):K;O(ve),j(0),R(oe),v(!0)}else v(!1)}},[]),ue=d.useCallback(S=>{if(m&&P.length>0){if(S.key==="ArrowDown"){S.preventDefault(),C(z=>(z+1)%P.length);return}if(S.key==="ArrowUp"){S.preventDefault(),C(z=>(z-1+P.length)%P.length);return}if(S.key==="Enter"||S.key==="Tab"){S.preventDefault(),$(P[I].cmd);return}if(S.key==="Escape"){S.preventDefault(),x(!1);return}}if(w&&B.length>0){if(S.key==="ArrowDown"){S.preventDefault(),j(z=>(z+1)%B.length);return}if(S.key==="ArrowUp"){S.preventDefault(),j(z=>(z-1+B.length)%B.length);return}if(S.key==="Tab"||S.key==="Enter"){S.preventDefault(),W(B[T]);return}if(S.key==="Escape"){S.preventDefault(),v(!1);return}}if(S.key==="Tab"){S.preventDefault();const z=u.current;if(z){const F=z.selectionStart,H=z.selectionEnd,X=l.slice(0,F)+" "+l.slice(H);a(X);const re=F+2;requestAnimationFrame(()=>{z.selectionStart=z.selectionEnd=re})}return}S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),N())},[N,m,P,I,$,l,w,B,T,W]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[m&&P.length>0&&s.jsx("div",{className:"slash-dropdown",children:P.map((S,z)=>s.jsxs("div",{className:`slash-item${z===I?" slash-item--active":""}`,onMouseDown:F=>{F.preventDefault(),$(S.cmd)},onMouseEnter:()=>C(z),children:[s.jsx("span",{className:"slash-cmd",children:S.cmd}),s.jsx("span",{className:"slash-desc",children:S.desc})]},S.cmd))}),w&&(M||B.length>0)&&s.jsx("div",{className:"file-dropdown",ref:_,children:M?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):B.map((S,z)=>s.jsxs("div",{className:`file-item${z===T?" file-item--active":""}`,onMouseDown:F=>{F.preventDefault(),W(S)},onMouseEnter:()=>j(z),children:[s.jsx("span",{className:"file-icon",children:S.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:S.name})]},S.name))}),s.jsx("textarea",{ref:u,className:"md-editor-textarea",value:l,onChange:ne,onKeyDown:ue,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function Un(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Hn(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function Vn({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:i,error:c,handleNavigate:l,handleGoUp:a,handleRefresh:u}=ze({sessionId:e,onClose:n}),f=(p,m)=>{t(r+"/"+p,m)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Le,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Oe,{loading:i,error:c,empty:o.length===0,emptyText:"No files found"}),!i&&!c&&o.map(p=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent"},onClick:()=>{p.type==="directory"?l(p.name):f(p.name,p.size)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:p.type==="directory"?"#7aa2f7":"#565f89"},children:Hn(p.name,p.type)}),s.jsx("span",{style:{flex:1,color:p.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:p.name}),p.type==="file"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:Un(p.size)}),s.jsx("span",{style:{fontSize:10,color:"#565f89",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:p.name.slice(p.name.lastIndexOf(".")).toLowerCase()})]})]},p.name))]})]})}const Gn="modulepreload",qn=function(e){return"/"+e},qe={},Yn=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(a=>{if(a=qn(a),a in qe)return;qe[a]=!0;const u=a.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${f}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":Gn,u||(p.as="script"),p.crossOrigin="",p.href=a,l&&p.setAttribute("nonce",l),document.head.appendChild(p),u)return new Promise((m,x)=>{p.addEventListener("load",m),p.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${a}`)))})}))}function i(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"&&i(l.reason);return t().catch(i)})};let je=null,ke=null;function Kn(){return ke||(ke=Yn(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(je=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),ke}function Jn({data:e,scrollRef:t}){const n=d.useRef(null),[r,o]=d.useState(null),[i,c]=d.useState(!0),l=d.useRef(0),a=u=>{n.current=u,t==null||t(u)};return d.useEffect(()=>{if(!e)return;const u=++l.current;return c(!0),o(null),(async()=>{try{if(await Kn(),!je||u!==l.current)return;let f;if(e instanceof Uint8Array)f=e;else{const h=atob(e);f=new Uint8Array(h.length);for(let g=0;g<h.length;g++)f[g]=h.charCodeAt(g)}const p=await je.getDocument({data:f}).promise;if(u!==l.current)return;const m=n.current;if(!m)return;for(;m.firstChild;)m.removeChild(m.firstChild);const x=m.clientWidth-24;for(let h=1;h<=p.numPages;h++){const g=await p.getPage(h);if(u!==l.current)return;const I=g.getViewport({scale:1}),C=Math.min(x/I.width,2),w=g.getViewport({scale:C}),v=document.createElement("canvas");v.width=w.width,v.height=w.height,v.style.display="block",v.style.margin="0 auto 8px",v.style.maxWidth="100%";const y=v.getContext("2d");if(y){if(await g.render({canvasContext:y,viewport:w,canvas:v}).promise,u!==l.current)return;m.appendChild(v)}}c(!1)}catch(f){if(u!==l.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{l.current++}},[e]),s.jsxs("div",{ref:a,className:"pdf-renderer",children:[i&&s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading PDF..."}),r&&s.jsxs("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:["PDF Error: ",r]})]})}const de=typeof window<"u"?d.useLayoutEffect:d.useEffect;function Ye(e){if(e!==void 0)switch(typeof e){case"number":return e;case"string":{if(e.endsWith("px"))return parseFloat(e);break}}}function Xn({box:e,defaultHeight:t,defaultWidth:n,disabled:r,element:o,mode:i,style:c}){const{styleHeight:l,styleWidth:a}=d.useMemo(()=>({styleHeight:Ye(c==null?void 0:c.height),styleWidth:Ye(c==null?void 0:c.width)}),[c==null?void 0:c.height,c==null?void 0:c.width]),[u,f]=d.useState({height:t,width:n}),p=r||l!==void 0||i==="only-width"||l!==void 0&&a!==void 0;return de(()=>{if(o===null||p)return;const m=new ResizeObserver(x=>{for(const h of x){const{contentRect:g,target:I}=h;o===I&&f(C=>C.height===g.height&&C.width===g.width?C:{height:g.height,width:g.width})}});return m.observe(o,{box:e}),()=>{m==null||m.unobserve(o)}},[e,p,o,l,a]),d.useMemo(()=>({height:l??u.height,width:a??u.width}),[u,l,a])}function Zn(e){const t=d.useRef(()=>{throw new Error("Cannot call during render.")});return de(()=>{t.current=e},[e]),d.useCallback(n=>{var r;return(r=t.current)==null?void 0:r.call(t,n)},[t])}function Ce({containerElement:e,direction:t,isRtl:n,scrollOffset:r}){return r}function Q(e,t="Assertion error"){if(!e)throw Error(t)}function le(e,t){if(e===t)return!0;if(!!e!=!!t||(Q(e!==void 0),Q(t!==void 0),Object.keys(e).length!==Object.keys(t).length))return!1;for(const n in e)if(!Object.is(t[n],e[n]))return!1;return!0}function mt({cachedBounds:e,itemCount:t,itemSize:n}){if(t===0)return 0;if(typeof n=="number")return t*n;{const r=e.get(e.size===0?0:e.size-1);Q(r!==void 0,"Unexpected bounds cache miss");const o=(r.scrollOffset+r.size)/e.size;return t*o}}function Qn({align:e,cachedBounds:t,index:n,itemCount:r,itemSize:o,containerScrollOffset:i,containerSize:c}){if(n<0||n>=r)throw RangeError(`Invalid index specified: ${n}`,{cause:`Index ${n} is not within the range of 0 - ${r-1}`});const l=mt({cachedBounds:t,itemCount:r,itemSize:o}),a=t.get(n),u=Math.max(0,Math.min(l-c,a.scrollOffset)),f=Math.max(0,a.scrollOffset-c+a.size);switch(e==="smart"&&(i>=f&&i<=u?e="auto":e="center"),e){case"start":return u;case"end":return f;case"center":return a.scrollOffset<=c/2?0:a.scrollOffset+a.size/2>=l-c/2?l-c:a.scrollOffset+a.size/2-c/2;case"auto":default:return i>=f&&i<=u?i:i<f?f:u}}function Ie({cachedBounds:e,containerScrollOffset:t,containerSize:n,itemCount:r,overscanCount:o}){const i=r-1;let c=0,l=-1,a=0,u=-1,f=0;for(;f<i;){const p=e.get(f);if(p.scrollOffset+p.size>t)break;f++}for(c=f,a=Math.max(0,c-o);f<i;){const p=e.get(f);if(p.scrollOffset+p.size>=t+n)break;f++}return l=Math.min(i,f),u=Math.min(r-1,l+o),c<0&&(c=0,l=-1,a=0,u=-1),{startIndexVisible:c,stopIndexVisible:l,startIndexOverscan:a,stopIndexOverscan:u}}function er({itemCount:e,itemProps:t,itemSize:n}){const r=new Map;return{get(o){for(Q(o<e,`Invalid index ${o}`);r.size-1<o;){const c=r.size;let l;switch(typeof n){case"function":{l=n(c,t);break}case"number":{l=n;break}}if(c===0)r.set(c,{size:l,scrollOffset:0});else{const a=r.get(c-1);Q(a!==void 0,`Unexpected bounds cache miss for index ${o}`),r.set(c,{scrollOffset:a.scrollOffset+a.size,size:l})}}const i=r.get(o);return Q(i!==void 0,`Unexpected bounds cache miss for index ${o}`),i},set(o,i){r.set(o,i)},get size(){return r.size}}}function tr({itemCount:e,itemProps:t,itemSize:n}){return d.useMemo(()=>er({itemCount:e,itemProps:t,itemSize:n}),[e,t,n])}function nr({containerSize:e,itemSize:t}){let n;switch(typeof t){case"string":{Q(t.endsWith("%"),`Invalid item size: "${t}"; string values must be percentages (e.g. "100%")`),Q(e!==void 0,"Container size must be defined if a percentage item size is specified"),n=e*parseInt(t)/100;break}default:{n=t;break}}return n}function rr({containerElement:e,containerStyle:t,defaultContainerSize:n=0,direction:r,isRtl:o=!1,itemCount:i,itemProps:c,itemSize:l,onResize:a,overscanCount:u}){const{height:f=n,width:p=n}=Xn({defaultHeight:n,defaultWidth:void 0,element:e,mode:"only-height",style:t}),m=d.useRef({height:0,width:0}),x=f,h=nr({containerSize:x,itemSize:l});d.useLayoutEffect(()=>{if(typeof a=="function"){const b=m.current;(b.height!==f||b.width!==p)&&(a({height:f,width:p},{...b}),b.height=f,b.width=p)}},[f,a,p]);const g=tr({itemCount:i,itemProps:c,itemSize:h}),I=d.useCallback(b=>g.get(b),[g]),[C,w]=d.useState(()=>Ie({cachedBounds:g,containerScrollOffset:0,containerSize:x,itemCount:i,overscanCount:u})),{startIndexVisible:v,startIndexOverscan:y,stopIndexVisible:O,stopIndexOverscan:k}={startIndexVisible:Math.min(i-1,C.startIndexVisible),startIndexOverscan:Math.min(i-1,C.startIndexOverscan),stopIndexVisible:Math.min(i-1,C.stopIndexVisible),stopIndexOverscan:Math.min(i-1,C.stopIndexOverscan)},R=d.useCallback(()=>mt({cachedBounds:g,itemCount:i,itemSize:h}),[g,i,h]),T=d.useCallback(b=>{const L=Ce({containerElement:e,direction:r,isRtl:o,scrollOffset:b});return Ie({cachedBounds:g,containerScrollOffset:L,containerSize:x,itemCount:i,overscanCount:u})},[g,e,x,r,o,i,u]);de(()=>{const b=(e==null?void 0:e.scrollTop)??0;w(T(b))},[e,r,T]),de(()=>{if(!e)return;const b=()=>{w(L=>{const{scrollLeft:M,scrollTop:A}=e,D=Ce({containerElement:e,direction:r,isRtl:o,scrollOffset:A}),_=Ie({cachedBounds:g,containerScrollOffset:D,containerSize:x,itemCount:i,overscanCount:u});return le(_,L)?L:_})};return e.addEventListener("scroll",b),()=>{e.removeEventListener("scroll",b)}},[g,e,x,r,i,u]);const j=Zn(({align:b="auto",containerScrollOffset:L,index:M})=>{let A=Qn({align:b,cachedBounds:g,containerScrollOffset:L,containerSize:x,index:M,itemCount:i,itemSize:h});if(e){if(A=Ce({containerElement:e,direction:r,isRtl:o,scrollOffset:A}),typeof e.scrollTo!="function"){const D=T(A);le(C,D)||w(D)}return A}});return{getCellBounds:I,getEstimatedSize:R,scrollToIndex:j,startIndexOverscan:y,startIndexVisible:v,stopIndexOverscan:k,stopIndexVisible:O}}function or(e){return d.useMemo(()=>e,Object.values(e))}function sr(e,t){const{ariaAttributes:n,style:r,...o}=e,{ariaAttributes:i,style:c,...l}=t;return le(n,i)&&le(r,c)&&le(o,l)}function ir(e){return e!=null&&typeof e=="object"&&"getAverageRowHeight"in e&&typeof e.getAverageRowHeight=="function"}const ar="data-react-window-index";function cr({children:e,className:t,defaultHeight:n=0,listRef:r,onResize:o,onRowsRendered:i,overscanCount:c=3,rowComponent:l,rowCount:a,rowHeight:u,rowProps:f,tagName:p="div",style:m,...x}){const h=or(f),g=d.useMemo(()=>d.memo(l,sr),[l]),[I,C]=d.useState(null),w=ir(u),v=d.useMemo(()=>w?A=>u.getRowHeight(A)??u.getAverageRowHeight():u,[w,u]),{getCellBounds:y,getEstimatedSize:O,scrollToIndex:k,startIndexOverscan:R,startIndexVisible:T,stopIndexOverscan:j,stopIndexVisible:b}=rr({containerElement:I,containerStyle:m,defaultContainerSize:n,direction:"vertical",itemCount:a,itemProps:h,itemSize:v,onResize:o,overscanCount:c});d.useImperativeHandle(r,()=>({get element(){return I},scrollToRow({align:A="auto",behavior:D="auto",index:_}){const P=k({align:A,containerScrollOffset:(I==null?void 0:I.scrollTop)??0,index:_});typeof(I==null?void 0:I.scrollTo)=="function"&&I.scrollTo({behavior:D,top:P})}}),[I,k]),de(()=>{if(!I)return;const A=Array.from(I.children).filter((D,_)=>{if(D.hasAttribute("aria-hidden"))return!1;const P=`${R+_}`;return D.setAttribute(ar,P),!0});if(w)return u.observeRowElements(A)},[I,w,u,R,j]),d.useEffect(()=>{R>=0&&j>=0&&i&&i({startIndex:T,stopIndex:b},{startIndex:R,stopIndex:j})},[i,R,T,j,b]);const L=d.useMemo(()=>{const A=[];if(a>0)for(let D=R;D<=j;D++){const _=y(D);A.push(d.createElement(g,{...h,ariaAttributes:{"aria-posinset":D+1,"aria-setsize":a,role:"listitem"},key:D,index:D,style:{position:"absolute",left:0,transform:`translateY(${_.scrollOffset}px)`,height:w?void 0:_.size,width:"100%"}}))}return A},[g,y,w,a,h,R,j]),M=s.jsx("div",{"aria-hidden":!0,style:{height:O(),width:"100%",zIndex:-1}});return d.createElement(p,{role:"list",...x,className:t,ref:C,style:{position:"relative",maxHeight:"100%",flexGrow:1,overflowY:"auto",...m}},L,e,M)}const lr='"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',dr=20;function ur({index:e,style:t,lines:n}){return s.jsx("div",{style:{...t,padding:"0 12px",color:"#a9b1d6",whiteSpace:"pre",overflow:"hidden",boxSizing:"border-box"},children:n[e]})}function Ke({lines:e,totalSize:t,receivedBytes:n,streaming:r}){const o=d.useRef(null),[,i]=d.useState(0),c=E(x=>x.fontSize),l=Math.round(c*1.5);d.useEffect(()=>{const x=o.current;if(!x)return;const h=new ResizeObserver(()=>i(g=>g+1));return h.observe(x),()=>h.disconnect()},[]);const a=t>0?Math.round(n/t*100):0,u=e.length.toLocaleString(),f=o.current,p=(f==null?void 0:f.clientWidth)||0,m=(f==null?void 0:f.clientHeight)||0;return s.jsxs("div",{ref:o,style:{height:"100%",width:"100%",position:"relative",fontFamily:lr,fontSize:c,lineHeight:`${l}px`},children:[m>0&&s.jsx(cr,{rowComponent:ur,rowCount:e.length,rowHeight:l,rowProps:{lines:e},overscanCount:dr,style:{height:m,width:p}}),s.jsxs("div",{style:{position:"absolute",bottom:6,right:14,fontSize:10,color:"#565f89",background:"rgba(22, 22, 30, 0.85)",padding:"2px 8px",borderRadius:4,pointerEvents:"none",userSelect:"none"},children:[u," lines",r&&` (${a}%)`]})]})}const Te={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},fr=200;function pr(){const[e,t]=d.useState(Te),n=d.useRef("lines"),r=d.useRef([]),o=d.useRef(""),i=d.useRef(""),c=d.useRef([]),l=d.useRef(0),a=d.useRef(0),u=d.useRef(null),f=d.useRef(null),p=d.useCallback(()=>{const C=n.current;t(w=>({...w,receivedBytes:l.current,...C==="lines"?{lines:[...r.current]}:{},...C==="content"?{content:i.current}:{}}))},[]),m=d.useCallback(()=>{u.current===null&&(u.current=window.setTimeout(()=>{u.current=null,p()},fr))},[p]),x=d.useCallback(C=>{n.current=C,r.current=[],o.current="",i.current="",c.current=[],l.current=0,a.current=0,f.current=new TextDecoder,u.current!==null&&(clearTimeout(u.current),u.current=null),t({...Te,mode:C,status:"streaming"})},[]),h=d.useCallback(C=>{l.current+=C.length;const w=n.current;if(w==="lines"){const y=f.current.decode(C,{stream:!0}).split(`
28
+ `);y[0]=o.current+y[0],o.current=y.pop(),y.length>0&&r.current.push(...y)}else if(w==="content"){const v=f.current.decode(C,{stream:!0});i.current+=v}else c.current.push(new Uint8Array(C));m()},[m]),g=d.useCallback(C=>{switch(C.type){case"file-stream-start":a.current=C.size,t(w=>({...w,totalSize:C.size,mtime:C.mtime}));break;case"file-stream-end":{u.current!==null&&(clearTimeout(u.current),u.current=null);const w=n.current;let v=r.current,y=i.current,O=null;if(w==="lines"){const k=f.current.decode(),R=o.current+k;R&&(v=[...v,R],r.current=v),o.current=""}else if(w==="content"){const k=f.current.decode();y=i.current+k,i.current=y}else{const k=c.current.reduce((T,j)=>T+j.length,0);O=new Uint8Array(k);let R=0;for(const T of c.current)O.set(T,R),R+=T.length;c.current=[]}t({status:"complete",mode:w,lines:w==="lines"?[...v]:[],content:w==="content"?y:"",buffer:w==="binary"?O:null,totalSize:a.current,receivedBytes:l.current,mtime:0,error:null});break}case"file-stream-error":u.current!==null&&(clearTimeout(u.current),u.current=null),t(w=>({...w,status:"error",error:C.error}));break}},[]),I=d.useCallback(()=>{u.current!==null&&(clearTimeout(u.current),u.current=null),r.current=[],o.current="",i.current="",c.current=[],l.current=0,a.current=0,f.current=null,t(Te)},[]);return{state:e,startStream:x,handleChunk:h,handleControl:g,reset:I}}function mr(e=50,t=20,n=80){const[r,o]=d.useState(e),i=d.useRef(null),c=d.useCallback(l=>{l.preventDefault();const a=i.current;if(!a)return;const u=a.getBoundingClientRect(),f=u.width;document.body.classList.add("resizing-panes-h");let p=null;const m=h=>{p||(p=requestAnimationFrame(()=>{p=null;const g=h.clientX-u.left,I=Math.min(n,Math.max(t,g/f*100));o(I)}))},x=()=>{p&&cancelAnimationFrame(p),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",x)};document.addEventListener("mousemove",m),document.addEventListener("mouseup",x)},[t,n]);return{leftWidthPercent:r,containerRef:i,onDividerMouseDown:c}}function hr(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":"text"}function Je(e){return e.split("/").pop()||e}function xr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function br(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 gr=3e3;function Xe({sessionId:e,onSelect:t}){const n=d.useCallback(()=>{},[]),{cwd:r,files:o,loading:i,error:c,handleNavigate:l,handleGoUp:a,handleRefresh:u}=ze({sessionId:e,onClose:n,pollCwd:gr});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(Le,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Oe,{loading:i,error:c,empty:o.length===0,emptyText:"No files found"}),!i&&!c&&o.map(f=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent"},onClick:()=>{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:br(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:xr(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 yr({sessionId:e,token:t,onClose:n,onSend:r,onRequestFileStream:o}){const[i,c]=d.useState(null),[l,a]=d.useState(null),u=pr(),[f,p]=d.useState(!1),[m,x]=d.useState(!1),[h,g]=d.useState(!1),{leftWidthPercent:I,containerRef:C,onDividerMouseDown:w}=mr(50),v=d.useRef(null),[y,O]=d.useState(!1),k=d.useRef(new Map),R=d.useRef(null),T=d.useRef(null);d.useEffect(()=>(xn(e,u.handleChunk,u.handleControl),()=>bn(e)),[e,u.handleChunk,u.handleControl]);const j=d.useCallback(()=>{if(!i)return;const N=m?T.current:R.current;N&&k.current.set(i,N.scrollTop)},[i,m]),b=d.useCallback(N=>{const $=k.current.get(N);$!=null&&requestAnimationFrame(()=>{const W=m?T.current:R.current;W&&(W.scrollTop=$)})},[m]),L=d.useCallback((N,$)=>{j();const W=hr(N);c(N),a(W),p(!1),u.reset();const ne=W==="text"?"lines":W==="pdf"?"binary":"content";u.startStream(ne),o==null||o(N)},[j,u,o]),M=d.useCallback(()=>{i&&navigator.clipboard.writeText(i).then(()=>{g(!0),setTimeout(()=>g(!1),1500)}).catch(()=>{})},[i]);d.useEffect(()=>{if(!m)return;const N=$=>{$.key==="Escape"&&(j(),x(!1))};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[m,j]),d.useEffect(()=>{i&&u.state.status==="complete"&&b(i)},[m,i,b,u.state.status]);const{status:A,totalSize:D,receivedBytes:_}=u.state,P=D>0?Math.round(_/D*100):0,B=N=>{if(!i)return s.jsx(Xe,{sessionId:e,onSelect:L});const{status:$,lines:W,content:ne,buffer:ue}=u.state;if($==="error")return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#f7768e",fontSize:"13px",padding:"12px",textAlign:"center"},children:u.state.error||"Stream error"});if($==="streaming")return l==="text"?s.jsx(Ke,{lines:W,totalSize:D,receivedBytes:_,streaming:!0}):s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:"13px"},children:"Loading..."});if($==="complete"){if(l==="text")return s.jsx(Ke,{lines:W,totalSize:D,receivedBytes:_,streaming:!1});if(l==="md")return s.jsx("div",{ref:N,style:{height:"100%",overflow:"auto"},children:s.jsx(_n,{content:ne})});if(l==="html")return s.jsx("div",{ref:N,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:ne,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})});if(l==="pdf"&&ue)return s.jsx(Jn,{data:ue,scrollRef:N})}return $==="idle"?s.jsx(Xe,{sessionId:e,onSelect:L}):null};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",height:"28px",flexShrink:0,backgroundColor:"#16161e",borderBottom:"1px solid #292e42"},children:[s.jsxs("div",{style:{width:`${I}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>p(N=>!N),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),i&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:M,title:h?"Copied!":`Click to copy: ${i}`,children:h?"Copied!":Je(i)}),s.jsx("button",{className:"pane-btn",onClick:()=>{j(),x(!0)},title:"Expand document view",style:{fontSize:"12px"},children:"⛶"})]}),A==="streaming"&&s.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:6,marginLeft:4},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"#292e42",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${P}%`,backgroundColor:"#7aa2f7",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"#565f89",whiteSpace:"nowrap"},children:[P,"%"]})]})]}),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 N;return(N=v.current)==null?void 0:N.send()},disabled:!y,title:"Send to terminal (Ctrl+Enter)",style:y?{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:C,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${I}%`,flexShrink:0},children:[B(N=>{R.current=N}),f&&s.jsx(Vn,{sessionId:e,onSelect:L,onClose:()=>p(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:w}),s.jsx("div",{className:"plan-editor-wrap",children:s.jsx(Wn,{ref:v,onSend:r,onContentChange:O,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:i?Je(i):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{j(),x(!1)},title:"Close expanded view (ESC)",children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:B(N=>{T.current=N})})]})]})}const vr=100,wr=600,se=typeof window<"u"?window.matchMedia(`(max-width: ${wr-1}px)`):null;function Sr(){const[e,t]=d.useState(()=>(se==null?void 0:se.matches)??!1);return d.useEffect(()=>{if(!se)return;const n=r=>t(r.matches);return se.addEventListener("change",n),()=>se.removeEventListener("change",n)},[]),e}const kr=d.memo(function({terminal:t}){const n=Sr(),r=E(k=>k.splitTerminal),o=E(k=>k.token),i=d.useRef(null),c=d.useRef(null),[l,a]=d.useState(!1),[u,f]=d.useState(!1),[p,m]=d.useState(0),[x,h]=d.useState(!1),[g,I]=d.useState(50),C=d.useRef(null),w=async k=>{const R=k.target.files;if(!(!R||R.length===0||!o)){f(!0),m(0);try{await Dn(o,t.id,R,T=>{m(T)})}catch(T){alert(`Upload failed: ${T instanceof Error?T.message:"Unknown error"}`)}finally{f(!1),m(0),i.current&&(i.current.value="")}}},v=d.useRef(void 0),y=d.useCallback(k=>{if(c.current){const R=k.replace(/\r?\n/g," ").trimEnd();c.current.sendInput(R),v.current=window.setTimeout(()=>{var T;return(T=c.current)==null?void 0:T.sendInput("\r")},50)}},[]);d.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const O=d.useCallback(k=>{k.preventDefault();const R=C.current;if(!R)return;const T=R.getBoundingClientRect(),j=T.height;document.body.classList.add("resizing-panes-v");const b=M=>{const A=(M.clientY-T.top)/j*100,D=Math.min(80,Math.max(20,A));I(100-D)},L=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",L)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",L)},[]);return s.jsxs("div",{ref:C,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"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:w}),s.jsx("button",{className:"pane-btn",onClick:()=>{var k;return(k=i.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:()=>a(k=>!k),style:l?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${x?" pane-btn--active":""}`,onClick:()=>h(k=>!k),title:"Toggle Document browser","aria-label":"Toggle Document browser",children:"Doc"}),s.jsx("button",{className:"pane-btn",onClick:()=>r(t.id,n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>r(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(Mn,{ref:c,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..."})}),l&&s.jsx(Fn,{sessionId:t.id,onClose:()=>a(!1)})]}),x&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:O}),s.jsx("div",{style:{height:`${g}%`,minHeight:vr,flexShrink:0,overflow:"hidden"},children:s.jsx(yr,{onSend:y,onClose:()=>h(!1),sessionId:t.id,token:o||"",onRequestFileStream:k=>{var R;return(R=c.current)==null?void 0:R.requestFileStream(k)},onCancelFileStream:()=>{var k;return(k=c.current)==null?void 0:k.cancelFileStream()}})})]}),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 ht extends d.Component{constructor(){super(...arguments);Me(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 Cr=4,Ze=10;function Ir(){const e=E(o=>o.layout),t=E(o=>o.terminalIds.length),n=E(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(xt,{node:e,canClose:r})})}const xt=d.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(Tr,{terminalId:t.terminalId,canClose:n}):s.jsx(Er,{node:t,canClose:n})}),Tr=d.memo(function({terminalId:t,canClose:n}){const r=E(o=>o.terminalsMap[t]);return r?s.jsx(ht,{inline:!0,children:s.jsx(kr,{terminal:r,canClose:n})}):null}),Er=d.memo(function({node:t,canClose:n}){const r=E(u=>u.setSplitSizes),o=d.useRef(null),i=t.direction==="horizontal",c=d.useRef(t.sizes);c.current=t.sizes;const l=d.useCallback((u,f)=>{f.preventDefault();const p=i?"resizing-panes":"resizing-panes-v";document.body.classList.add(p);const m=i?f.clientX:f.clientY,x=[...c.current],h=o.current,g=i?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let I=null;const C=v=>{I||(I=requestAnimationFrame(()=>{I=null;const k=((i?v.clientX:v.clientY)-m)/g*100,R=x[u]+k,T=x[u+1]-k;if(R>=Ze&&T>=Ze){const j=[...x];j[u]=R,j[u+1]=T,r(t.id,j)}}))},w=()=>{I&&cancelAnimationFrame(I),document.body.classList.remove(p),document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",w)};document.addEventListener("mousemove",C),document.addEventListener("mouseup",w)},[i,t.id,r]),a=[];return t.children.forEach((u,f)=>{const p=u.type==="leaf"?u.terminalId:u.id;a.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(xt,{node:u,canClose:n})},p)),f<t.children.length-1&&a.push(s.jsx("div",{onMouseDown:m=>l(f,m),style:{flex:`0 0 ${Cr}px`,cursor:i?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:i?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:a})});function jr({tabId:e}){const t=E(b=>b.tabs.find(L=>L.id===e)),n=E(b=>b.activeTabId),r=E(b=>b.switchTab),o=E(b=>b.closeTab),i=E(b=>b.reopenTab),c=E(b=>b.deleteTab),l=E(b=>b.renameTab),a=E(b=>t?t.terminalIds.map(L=>{const M=b.terminalsMap[L];return M?{id:L,connected:M.connected}:{id:L,connected:!1}}):[]),u=E(b=>b.killServerSession),[f,p]=d.useState(!1),[m,x]=d.useState(""),[h,g]=d.useState(!1),I=d.useRef(null);if(!t)return null;const C=n===e,w=t.status==="open",v=()=>{w&&r(e)},y=b=>{w&&(b.stopPropagation(),x(t.name),p(!0),setTimeout(()=>{var L;return(L=I.current)==null?void 0:L.focus()},0))},O=()=>{const b=m.trim();b&&l(e,b),p(!1)},k=b=>{b.stopPropagation(),i(e)},R=b=>{b.stopPropagation(),o(e)},T=async b=>{b.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},j=b=>{b.stopPropagation(),g(!h)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:v,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:j,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:h?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[f?s.jsx("input",{ref:I,value:m,onChange:b=>x(b.target.value),onBlur:O,onKeyDown:b=>{b.key==="Enter"&&O(),b.key==="Escape"&&p(!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:y,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":""," · ",pt(Math.floor(t.createdAt/1e3))]})]}),w?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:R,style:{flexShrink:0},title:"Close tab",children:"×"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:k,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:T,title:"Delete tab",children:"×"})]})]}),w&&h&&a.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:a.map(b=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)",display:"flex",alignItems:"center"},title:`Connected: ${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?"●":"○"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:L=>{L.stopPropagation(),window.confirm(`Close terminal "${b.id}"?`)&&u(b.id)},style:{marginLeft:"auto",flexShrink:0},title:"Close terminal",children:"×"})]},b.id))})]})}function Rr({sessionId:e,active:t,createdAt:n}){const r=E(l=>l.addTerminal),o=E(l=>l.killServerSession),i=()=>{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:i,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:pt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function zr(){const e=E(a=>a.sidebarOpen),t=E(a=>a.toggleSidebar),n=E(a=>a.fetchSessions),r=E(a=>e?a.serverSessions:[]),o=E(a=>e?a.tabs:[]),i=E(a=>a.terminalIds.length),c=new Set(o.flatMap(a=>a.terminalIds)),l=r.filter(a=>!c.has(a.sessionId));return d.useEffect(()=>{if(!e)return;n();let a=setInterval(n,5e3);const u=()=>{document.hidden?a&&(clearInterval(a),a=null):(n(),a||(a=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",u),()=>{a&&clearInterval(a),document.removeEventListener("visibilitychange",u)}},[e,n]),d.useEffect(()=>{if(!e)return;const a=setTimeout(n,800);return()=>clearTimeout(a)},[i,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(a=>s.jsx(jr,{tabId:a.id},a.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(a=>s.jsx(Rr,{sessionId:a.sessionId,active:a.active,createdAt:a.createdAt},a.sessionId))]})]})]})}const bt=Re.memo(()=>{const e=E(y=>y.tabs),t=E(y=>y.activeTabId),n=E(y=>y.addTab),r=E(y=>y.switchTab),o=E(y=>y.closeTab),i=E(y=>y.renameTab),[c,l]=d.useState(null),[a,u]=d.useState(""),f=d.useRef(null),p=e.filter(y=>y.status==="open");d.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const m=y=>{l(y.id),u(y.name)},x=()=>{c&&a.trim()&&i(c,a.trim()),l(null),u("")},h=()=>{l(null),u("")},g=y=>{y.key==="Enter"?x():y.key==="Escape"&&h()},I=y=>{c||r(y)},C=(y,O)=>{y.stopPropagation(),o(O)},w=(y,O)=>{y.button===1&&(y.preventDefault(),o(O))},v=p.length>1;return s.jsxs("div",{className:"tab-bar",children:[p.map(y=>{const O=y.id===t,k=c===y.id,R=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${O?"tab-item--active":""}`,onClick:()=>I(y.id),onDoubleClick:()=>m(y),onMouseDown:T=>w(T,y.id),children:k?s.jsx("input",{ref:f,type:"text",value:a,onChange:T=>u(T.target.value),onBlur:x,onKeyDown:g,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",R>0&&`(${R})`]}),v&&s.jsx("button",{className:"tab-item__close",onClick:T=>C(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:"+"})]})});bt.displayName="TabBar";function Lr(){return localStorage.getItem("ai-cli-online-token")}function Or(){const e=E(a=>a.token),t=E(a=>a.setToken),n=E(a=>a.tabs),r=E(a=>a.addTab),o=E(a=>a.toggleSidebar),i=E(a=>a.fontSize),c=E(a=>a.setFontSize),l=E(a=>a.tabsLoading);return d.useEffect(()=>{const a=Lr();a&&!e&&t(a)},[]),d.useEffect(()=>{e&&!l&&n.filter(a=>a.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(i-1),disabled:i<=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:i}),s.jsx("button",{className:"header-btn",onClick:()=>c(i+1),disabled:i>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(Nr,{}),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(Ir,{})}),s.jsx(zr,{})]}),s.jsx(bt,{})]}):s.jsx(hn,{})}const Mr=[1,2,3,4];function Nr(){const e=E(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:[Mr.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"]})]})}Ee.createRoot(document.getElementById("root")).render(s.jsx(Re.StrictMode,{children:s.jsx(ht,{children:s.jsx(Or,{})})}));
@@ -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-DPtjYW9O.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-CwCy8bpB.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
@@ -20,11 +20,13 @@
20
20
  "pdfjs-dist": "^5.4.624",
21
21
  "react": "^18.2.0",
22
22
  "react-dom": "^18.2.0",
23
+ "react-window": "^2.2.6",
23
24
  "zustand": "^4.4.7"
24
25
  },
25
26
  "devDependencies": {
26
27
  "@types/react": "^18.2.43",
27
- "@types/react-dom": "^18.2.17",
28
+ "@types/react-dom": "^18.3.7",
29
+ "@types/react-window": "^1.8.8",
28
30
  "@vitejs/plugin-react": "^4.2.1",
29
31
  "typescript": "^5.9.3",
30
32
  "vite": "^5.0.8"
@@ -1,27 +0,0 @@
1
- var lt=Object.defineProperty;var ct=(e,t,n)=>t in e?lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ke=(e,t,n)=>ct(e,typeof t!="symbol"?t+"":t,n);import{r as d,a as dt,g as ut,R as we}from"./react-vendor-BCIvbQoU.js";import{D as Ue,o as We,L as ft,x as pt}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 He={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 Ve(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=Ve;de.jsxs=Ve;He.exports=de;var s=He.exports,ye={},Ie=dt;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 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},Tt=e=>e?Ce(e):Ce;var Ge={exports:{}},qe={},Je={exports:{}},Ke={};/**
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;Ke.useSyncExternalStore=ne.useSyncExternalStore!==void 0?ne.useSyncExternalStore:Dt;Je.exports=Ke;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 Ot(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var At=typeof Object.is=="function"?Object.is:Ot,Pt=Mt.useSyncExternalStore,$t=ue.useRef,_t=ue.useEffect,Ft=ue.useMemo,Bt=ue.useDebugValue;qe.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var a=$t(null);if(a.current===null){var c={hasValue:!1,value:null};a.current=c}else c=a.current;a=Ft(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,At(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=Pt(e,a[0],a[1]);return _t(function(){c.hasValue=!0,c.value=i},[i]),Bt(i),i};Ge.exports=qe;var Ut=Ge.exports;const Wt=ut(Ut),Ye={},{useDebugValue:Ht}=we,{useSyncExternalStoreWithSelector:Vt}=Wt;let je=!1;const Gt=e=>e;function qt(e,t=Gt,n){(Ye?"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},Jt=e=>e?Ee(e):Ee,_="";function U(e){return{Authorization:`Bearer ${e}`}}async function Kt(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 i=ce(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 Xe(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=>Xe(a,t,n,r,o))}}function Ze(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Ze(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=S.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),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(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 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=ce(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=ce(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))}});function De(e,t){const n=e.tabs.find(p=>p.terminalIds.includes(t));if(!n){const{[t]:p,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(p=>p!==t),o=n.layout?ce(n.layout,t):null,a=X(e.tabs,n.id,p=>({...p,terminalIds:r,layout:o})),{[t]:c,...i}=e.terminalsMap,l={terminalsMap:i,tabs:a};return n.id===e.activeTabId&&(l.terminalIds=r,l.layout=o),l}const S=Jt((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Kt(n).then(o=>{t().token===n&&e({fontSize:o})});const r=tn();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});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},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},N={type:"leaf",terminalId:E},P={id:R,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[E],layout:N,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:N}),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=Xe(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=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=Ze(a.layout,n,r),i=X(o.tabs,a.id,l=>({...l,layout:c}));e({layout:c,tabs:i}),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}=S;try{const[a,c]=await Promise.all([Xt(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=nn(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 on(){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 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 Oe(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),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=`${sn}?sessionId=${encodeURIComponent(t)}`,v=new WebSocket(b);v.binaryType="arraybuffer",l.current=window.setTimeout(()=>{v.readyState===WebSocket.CONNECTING&&v.close()},cn);const N=()=>{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())},Ne))};v.onopen=()=>{l.current&&(clearTimeout(l.current),l.current=null),v.send(JSON.stringify({type:"auth",token:D})),T(t,null),o.current=ae,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 M=o.current;o.current=Math.min(M*2,an);const O=Math.round(M*(.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 M=new Uint8Array(P.data);if(M.length<1)return;const O=M[0],G=M.subarray(1);switch(O){case fn:$==null||$.write(G);break;case pn:$==null||$.write(G);break;case mn:{(W=f.current)==null||W.call(f,hn.decode(G));break}}return}const z=JSON.parse(P.data);switch(z.type){case"connected":{const M=S.getState();M.setTerminalConnected(t,!0),M.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(Oe(Me,w.current)),w.current=""),N(),c.current=window.setInterval(N,ln);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 M=Math.round(performance.now()-x.current),O=S.getState();(O.terminalIds.length===0||O.terminalIds[0]===t)&&O.setLatency(M),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<un&&(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(Oe(Me,b))},dn))},[]),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=ae,m.current=!0;const N=r.current;(!N||N.readyState===WebSocket.CLOSED||N.readyState===WebSocket.CLOSING)&&j()},b=()=>{h.current=!0},v=()=>{if(document.visibilityState!=="visible")return;const N=r.current;if(!N||N.readyState!==WebSocket.OPEN){!h.current&&!u.current&&(o.current=ae,m.current=!0,j());return}x.current=performance.now(),N.send(JSON.stringify({type:"ping"})),i.current&&clearTimeout(i.current),i.current=window.setTimeout(()=>{x.current>0&&(x.current=0,N.close())},Ne)};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 Qe={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"},et="'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,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}=bn(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 Ue({cursorBlink:!0,scrollback:1e4,fontSize:S.getState().fontSize,fontFamily:et,theme:Qe,allowProposedApi:!0}),D=new We;E.loadAddon(D),E.loadAddon(new ft((v,N)=>{window.open(N,"_blank","noopener,noreferrer")})),E.open(r.current);try{const v=new pt;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(gn,{data:l,onClose:()=>{i(!1),p("")}})]})});function gn({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 Ue({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:et,theme:Qe});a.current=i;const l=new We;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 wn(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 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=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 vn(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 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 tt(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=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 Sn(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"?Tn(h.size):""})]},h.name))]})]})}function In({content:e}){const t=S(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 Ae(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 Pe=[{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=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,N]=d.useState([]),[P,W]=d.useState(!1),$=d.useRef(""),z=d.useRef(null),M=d.useMemo(()=>{if(!h)return Pe;const g=h.toLowerCase();return Pe.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 Cn(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(()=>{Ae(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;N(A.files)}else{const k=await oe(o,r);if(g)return;$.current=k.cwd,N(k.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"})},[T,L]);const G=d.useCallback(()=>{const g=i.trim();g&&(t(g),l(""),Ae(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 at=H+ee.length;requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=at,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),N([]),$.current="",requestAnimationFrame(()=>{k.selectionStart=k.selectionEnd=H,k.focus()})}},[i,E]),st=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)}},[]),it=d.useCallback(g=>{if(x&&M.length>0){if(g.key==="ArrowDown"){g.preventDefault(),w(k=>(k+1)%M.length);return}if(g.key==="ArrowUp"){g.preventDefault(),w(k=>(k-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(),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,M,C,fe,i,L,O,T,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,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:st,onKeyDown:it,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function En(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function Rn({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:En(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 zn="modulepreload",Ln=function(e){return"/"+e},$e={},Dn=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=Ln(l),l in $e)return;$e[l]=!0;const p=l.endsWith(".css"),f=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${f}`))return;const u=document.createElement("link");if(u.rel=p?"stylesheet":zn,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 Nn(){return be||(be=Dn(()=>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 Nn(),!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 On(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 An=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){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 Fn({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:$n(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 Bn({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}=On(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]),N=d.useCallback(z=>{const M=D.current.get(z);M!=null&&requestAnimationFrame(()=>{const O=m?b.current:T.current;O&&(O.scrollTop=M)})},[m]),P=d.useCallback(z=>{v();const M=Pn(z);a(z),p(M),i(""),f.current=0,x(!1),_e(t,e,z).then(O=>{O&&(i(O.content),f.current=O.mtime,requestAnimationFrame(()=>N(z)))}).catch(()=>{})},[t,e,v,N]);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{}},An);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=M=>{M.key==="Escape"&&(v(),h(!1))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m,v]),d.useEffect(()=>{o&&N(o)},[m,o,N]);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(In,{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(Fn,{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!":Fe(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(Rn,{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(jn,{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?Fe(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 Un=100,Wn=600,te=typeof window<"u"?window.matchMedia(`(max-width: ${Wn-1}px)`):null;function Hn(){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 Vn=d.memo(function({terminal:t,canClose:n}){const r=Hn(),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 wn(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(),N=v.height;document.body.classList.add("resizing-panes-v");const P=$=>{const z=($.clientY-v.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",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(yn,{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(kn,{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:Un,flexShrink:0,overflow:"hidden"},children:s.jsx(Bn,{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 nt 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 Gn=4,Be=10;function qn(){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(rt,{node:e,canClose:r})})}const rt=d.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(Jn,{terminalId:t.terminalId,canClose:n}):s.jsx(Kn,{node:t,canClose:n})}),Jn=d.memo(function({terminalId:t,canClose:n}){const r=S(o=>o.terminalsMap[t]);return r?s.jsx(nt,{inline:!0,children:s.jsx(Vn,{terminal:r,canClose:n})}):null}),Kn=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>=Be&&T>=Be){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(rt,{node:p,canClose:n})},u)),f<t.children.length-1&&l.push(s.jsx("div",{onMouseDown:x=>i(f,x),style:{flex:`0 0 ${Gn}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 Yn({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 N=b.terminalsMap[v];return N?{id:v,connected:N.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":""," · ",tt(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 Xn({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:tt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function Zn(){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(Yn,{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(Xn,{sessionId:l.sessionId,active:l.active,createdAt:l.createdAt},l.sessionId))]})]})]})}const ot=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:"+"})]})});ot.displayName="TabBar";function Qn(){return localStorage.getItem("ai-cli-online-token")}function er(){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=Qn();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(nr,{}),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(qn,{})}),s.jsx(Zn,{})]}),s.jsx(ot,{})]}):s.jsx(on,{})}const tr=[1,2,3,4];function nr(){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:[tr.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(nt,{children:s.jsx(er,{})})}));