ai-cli-online 2.2.6 → 2.3.2

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
@@ -24,7 +24,7 @@ Ideal for **unstable networks** where SSH drops frequently, or as a **local stat
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
27
- - **Session Management** — sidebar to restore, delete, and rename sessions
27
+ - **Session Management** — sidebar to restore, delete, rename sessions, and close individual terminals (with confirmation)
28
28
  - **Font Size Control** — adjustable terminal font size (A−/A+) with server-side persistence
29
29
  - **Network Indicator** — real-time RTT latency display with signal bars
30
30
  - **Auto Reconnect** — exponential backoff with jitter to prevent thundering herd
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online",
3
- "version": "2.2.6",
3
+ "version": "2.3.2",
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;
@@ -17,6 +17,9 @@ export declare function isValidSessionId(sessionId: string): boolean;
17
17
  export declare function buildSessionName(token: string, sessionId?: string): string;
18
18
  /** Check if a tmux session exists */
19
19
  export declare function hasSession(name: string): Promise<boolean>;
20
+ /** Configure tmux session options for web terminal usage.
21
+ * Note: set-option does NOT support the = exact-match prefix, so use bare name. */
22
+ export declare function configureSession(name: string): Promise<void>;
20
23
  /** Create a new tmux session (detached) */
21
24
  export declare function createSession(name: string, cols: number, rows: number, cwd: string): Promise<void>;
22
25
  /**
@@ -37,6 +37,15 @@ export async function hasSession(name) {
37
37
  return false;
38
38
  }
39
39
  }
40
+ /** Configure tmux session options for web terminal usage.
41
+ * Note: set-option does NOT support the = exact-match prefix, so use bare name. */
42
+ export async function configureSession(name) {
43
+ await execFile('tmux', [
44
+ 'set-option', '-t', name, 'history-limit', '50000', ';',
45
+ 'set-option', '-t', name, 'status', 'off', ';',
46
+ 'set-option', '-t', name, 'mouse', 'off',
47
+ ]).catch(() => { });
48
+ }
40
49
  /** Create a new tmux session (detached) */
41
50
  export async function createSession(name, cols, rows, cwd) {
42
51
  await execFile('tmux', [
@@ -46,12 +55,7 @@ export async function createSession(name, cols, rows, cwd) {
46
55
  '-x', String(cols),
47
56
  '-y', String(rows),
48
57
  ], { cwd });
49
- // Configure tmux for web terminal usage (single call with \; separator)
50
- await execFile('tmux', [
51
- 'set-option', '-t', `=${name}`, 'history-limit', '50000', ';',
52
- 'set-option', '-t', `=${name}`, 'status', 'off', ';',
53
- 'set-option', '-t', `=${name}`, 'mouse', 'off',
54
- ]).catch(() => { });
58
+ await configureSession(name);
55
59
  console.log(`[tmux] Created session: ${name} (${cols}x${rows}) in ${cwd}`);
56
60
  }
57
61
  /**
@@ -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, configureSession, 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
@@ -172,10 +182,11 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
172
182
  await createSession(sessionName, cols, rows, defaultCwd);
173
183
  }
174
184
  else {
175
- // resizeSession and captureScrollback are independent — run in parallel
185
+ // resizeSession, captureScrollback, and configureSession are independent — run in parallel
176
186
  const [, scrollback] = await Promise.all([
177
187
  resizeSession(sessionName, cols, rows),
178
188
  captureScrollback(sessionName),
189
+ configureSession(sessionName),
179
190
  ]);
180
191
  if (scrollback) {
181
192
  sendBinary(ws, BIN_TYPE_SCROLLBACK, scrollback);
@@ -258,6 +269,7 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
258
269
  return;
259
270
  }
260
271
  authenticated = true;
272
+ authenticatedToken = msg.token;
261
273
  await initSession(msg.token);
262
274
  return;
263
275
  }
@@ -294,6 +306,76 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
294
306
  sendBinary(ws, BIN_TYPE_SCROLLBACK_CONTENT, normalized);
295
307
  break;
296
308
  }
309
+ case 'stream-file': {
310
+ // Cancel any existing stream
311
+ if (activeFileStream) {
312
+ activeFileStream.destroy();
313
+ activeFileStream = null;
314
+ }
315
+ try {
316
+ const cwd = await getCwd(sessionName);
317
+ const resolved = await validatePath(msg.path, cwd);
318
+ if (!resolved) {
319
+ send(ws, { type: 'file-stream-error', error: 'Invalid path' });
320
+ break;
321
+ }
322
+ const fileStat = await fsStat(resolved);
323
+ if (!fileStat.isFile()) {
324
+ send(ws, { type: 'file-stream-error', error: 'Not a file' });
325
+ break;
326
+ }
327
+ if (fileStat.size > MAX_STREAM_SIZE) {
328
+ send(ws, { type: 'file-stream-error', error: `File too large (${(fileStat.size / 1024 / 1024).toFixed(1)}MB > 50MB limit)` });
329
+ break;
330
+ }
331
+ send(ws, { type: 'file-stream-start', size: fileStat.size, mtime: fileStat.mtimeMs });
332
+ const stream = createReadStream(resolved, { highWaterMark: STREAM_CHUNK_SIZE });
333
+ activeFileStream = stream;
334
+ stream.on('data', (chunk) => {
335
+ const data = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
336
+ if (ws.readyState !== WebSocket.OPEN) {
337
+ stream.destroy();
338
+ return;
339
+ }
340
+ const buf = Buffer.allocUnsafe(1 + data.length);
341
+ buf[0] = BIN_TYPE_FILE_CHUNK;
342
+ buf.set(data, 1);
343
+ ws.send(buf);
344
+ // Backpressure: pause stream when WS send buffer is full
345
+ if (ws.bufferedAmount > STREAM_HIGH_WATER) {
346
+ stream.pause();
347
+ const checkDrain = () => {
348
+ if (ws.bufferedAmount < STREAM_LOW_WATER) {
349
+ stream.resume();
350
+ }
351
+ else {
352
+ setTimeout(checkDrain, 10);
353
+ }
354
+ };
355
+ setTimeout(checkDrain, 10);
356
+ }
357
+ });
358
+ stream.on('end', () => {
359
+ activeFileStream = null;
360
+ send(ws, { type: 'file-stream-end' });
361
+ });
362
+ stream.on('error', (err) => {
363
+ activeFileStream = null;
364
+ send(ws, { type: 'file-stream-error', error: err.message });
365
+ });
366
+ }
367
+ catch (err) {
368
+ send(ws, { type: 'file-stream-error', error: err instanceof Error ? err.message : 'Stream failed' });
369
+ }
370
+ break;
371
+ }
372
+ case 'cancel-stream': {
373
+ if (activeFileStream) {
374
+ activeFileStream.destroy();
375
+ activeFileStream = null;
376
+ }
377
+ break;
378
+ }
297
379
  }
298
380
  }
299
381
  catch (err) {
@@ -303,6 +385,10 @@ export function setupWebSocket(wss, authToken, defaultCwd, tokenCompare, maxConn
303
385
  ws.on('close', () => {
304
386
  if (authTimer)
305
387
  clearTimeout(authTimer);
388
+ if (activeFileStream) {
389
+ activeFileStream.destroy();
390
+ activeFileStream = null;
391
+ }
306
392
  if (sessionName) {
307
393
  console.log(`[WS] Client disconnected, session: ${sessionName}`);
308
394
  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-C2U1eAjl.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 ct=Object.defineProperty;var dt=(e,t,n)=>t in e?ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ke=(e,t,n)=>dt(e,typeof t!="symbol"?t+"":t,n);import{r as d,a as ut,g as ft,R as we}from"./react-vendor-BCIvbQoU.js";import{D as Ue,o as We,L as pt,x as He}from"./terminal-DnNpv9tw.js";import{d as mt,p as ht}from"./markdown-BERZKN_L.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();var Ve={exports:{}},de={};/**
2
- * @license React
3
- * react-jsx-runtime.production.min.js
4
- *
5
- * Copyright (c) Facebook, Inc. and its affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var xt=d,bt=Symbol.for("react.element"),yt=Symbol.for("react.fragment"),gt=Object.prototype.hasOwnProperty,wt=xt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,vt={key:!0,ref:!0,__self:!0,__source:!0};function Ge(e,t,n){var r,o={},a=null,c=null;n!==void 0&&(a=""+n),t.key!==void 0&&(a=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)gt.call(t,r)&&!vt.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:bt,type:e,key:a,ref:c,props:o,_owner:wt.current}}de.Fragment=yt;de.jsx=Ge;de.jsxs=Ge;Ve.exports=de;var s=Ve.exports,ye={},Ie=ut;ye.createRoot=Ie.createRoot,ye.hydrateRoot=Ie.hydrateRoot;const St={},Ce=e=>{let t;const n=new Set,r=(f,u)=>{const x=typeof f=="function"?f(t):f;if(!Object.is(x,t)){const p=t;t=u??(typeof x!="object"||x===null)?x:Object.assign({},t,x),n.forEach(h=>h(t,p))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>m,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},m=t=e(r,o,i);return i},Tt=e=>e?Ce(e):Ce;var qe={exports:{}},Ke={},Je={exports:{}},Ye={};/**
10
- * @license React
11
- * use-sync-external-store-shim.production.js
12
- *
13
- * Copyright (c) Meta Platforms, Inc. and affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var ne=d;function kt(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var It=typeof Object.is=="function"?Object.is:kt,Ct=ne.useState,jt=ne.useEffect,Et=ne.useLayoutEffect,Rt=ne.useDebugValue;function zt(e,t){var n=t(),r=Ct({inst:{value:n,getSnapshot:t}}),o=r[0].inst,a=r[1];return Et(function(){o.value=n,o.getSnapshot=t,he(o)&&a({inst:o})},[e,n,t]),jt(function(){return he(o)&&a({inst:o}),e(function(){he(o)&&a({inst:o})})},[e]),Rt(n),n}function he(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!It(e,n)}catch{return!0}}function Lt(e,t){return t()}var Dt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lt:zt;Ye.useSyncExternalStore=ne.useSyncExternalStore!==void 0?ne.useSyncExternalStore:Dt;Je.exports=Ye;var Nt=Je.exports;/**
18
- * @license React
19
- * use-sync-external-store-shim/with-selector.production.js
20
- *
21
- * Copyright (c) Meta Platforms, Inc. and affiliates.
22
- *
23
- * This source code is licensed under the MIT license found in the
24
- * LICENSE file in the root directory of this source tree.
25
- */var ue=d,Mt=Nt;function At(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ot=typeof Object.is=="function"?Object.is:At,$t=Mt.useSyncExternalStore,Pt=ue.useRef,_t=ue.useEffect,Ft=ue.useMemo,Bt=ue.useDebugValue;Ke.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var a=Pt(null);if(a.current===null){var c={hasValue:!1,value:null};a.current=c}else c=a.current;a=Ft(function(){function i(p){if(!m){if(m=!0,f=p,p=r(p),o!==void 0&&c.hasValue){var h=c.value;if(o(h,p))return u=h}return u=p}if(h=u,Ot(f,p))return h;var w=r(p);return o!==void 0&&o(h,w)?(f=p,h):(f=p,u=w)}var m=!1,f,u,x=n===void 0?null:n;return[function(){return i(t())},x===null?void 0:function(){return i(x())}]},[t,n,r,o]);var l=$t(e,a[0],a[1]);return _t(function(){c.hasValue=!0,c.value=l},[l]),Bt(l),l};qe.exports=Ke;var Ut=qe.exports;const Wt=ft(Ut),Xe={},{useDebugValue:Ht}=we,{useSyncExternalStoreWithSelector:Vt}=Wt;let je=!1;const Gt=e=>e;function qt(e,t=Gt,n){(Xe?"production":void 0)!=="production"&&n&&!je&&(je=!0);const r=Vt(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Ht(r),r}const Ee=e=>{const t=typeof e=="function"?Tt(e):e,n=(r,o)=>qt(t,r,o);return Object.assign(n,t),n},Kt=e=>e?Ee(e):Ee,_="";function U(e){return{Authorization:`Bearer ${e}`}}async function Jt(e){try{const t=await fetch(`${_}/api/settings/font-size`,{headers:U(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function Yt(e,t){try{await fetch(`${_}/api/settings/font-size`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function Xt(e){try{const t=await fetch(`${_}/api/settings/tabs-layout`,{headers:U(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function Zt(e,t){try{await fetch(`${_}/api/settings/tabs-layout`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function Re(e,t){try{const n=`${_}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const le="ai-cli-online-tabs",ze="ai-cli-online-layout",Le="ai-cli-online-session-names";function ce(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let c=0;c<e.children.length;c++){const l=ce(e.children[c],t);l!==null&&(n.push(l),r.push(e.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,l)=>c+l,0),a=r.map(c=>c/o*100);return{...e,children:n,sizes:a}}function Ze(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(a=>Ze(a,t,n,r,o))}}function Qe(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Qe(r,t,n))}}function xe(e){return e.tabs.find(t=>t.id===e.activeTabId)}function X(e,t,n){return e.map(r=>r.id===t?n(r):r)}function V(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(le,JSON.stringify(t))}catch{}Qt(t)}let se=null,ie=null,Z=null,re=null;function Qt(e){re=e,Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,re=null;const t=T.getState().token;t&&Zt(t,e)},2e3)}function en(e){se&&clearTimeout(se),se=setTimeout(()=>{se=null,V(e)},500)}function tn(){try{const e=localStorage.getItem(le);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(ze);if(e){const t=JSON.parse(e);let n="Default";try{const a=localStorage.getItem(Le);if(a){const c=JSON.parse(a),l=Object.values(c)[0];l&&(n=l)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(le,JSON.stringify(o))}catch{}return localStorage.removeItem(ze),localStorage.removeItem(Le),o}}catch{}return null}function B(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function nn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.tabs){if(c.status!=="open"){const m=c.terminalIds.filter(f=>n.has(f));if(m.length>0){let f=c.layout;for(const u of c.terminalIds)!n.has(u)&&f&&(f=ce(f,u));r.push({...c,terminalIds:m,layout:f})}continue}const l=c.terminalIds.filter(m=>n.has(m));if(l.length===0)continue;let i=c.layout;for(const m of c.terminalIds)!n.has(m)&&i&&(i=ce(i,m));r.push({...c,terminalIds:l,layout:i})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(l=>l.status==="open");o=(c==null?void 0:c.id)||""}return{...e,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var t,n;const e=(n=(t=T==null?void 0:T.getState)==null?void 0:t.call(T))==null?void 0:n.token;if(e)if(re)Z&&(clearTimeout(Z),Z=null),Re(e,re),re=null;else{const r=T.getState();r.tabs.length>0&&Re(e,B(r))}});function De(e,t){const n=e.tabs.find(m=>m.terminalIds.includes(t));if(!n){const{[t]:m,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(m=>m!==t),o=n.layout?ce(n.layout,t):null,a=X(e.tabs,n.id,m=>({...m,terminalIds:r,layout:o})),{[t]:c,...l}=e.terminalsMap,i={terminalsMap:l,tabs:a};return n.id===e.activeTabId&&(i.terminalIds=r,i.layout=o),i}const T=Kt((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Jt(n).then(o=>{t().token===n&&e({fontSize:o})});const r=tn();if(r&&r.tabs.length>0){const o={};for(const l of r.tabs)if(l.status==="open")for(const i of l.terminalIds)o[i]={id:i,connected:!1,sessionResumed:!1,error:null};const a=r.tabs.find(l=>l.id===r.activeTabId&&l.status==="open")||r.tabs.find(l=>l.status==="open"),c=(a==null?void 0:a.id)||"";e({token:n,tabsLoading:!0,terminalsMap:o,tabs:r.tabs,activeTabId:c,nextId:r.nextId,nextSplitId:r.nextSplitId,nextTabId:r.nextTabId,terminalIds:(a==null?void 0:a.terminalIds)||[],layout:(a==null?void 0:a.layout)||null})}else e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});rn(n,r);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(le),e({token:n,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:n=>{const r=t(),o=`tab${r.nextTabId}`,a=`t${r.nextId}`,c={id:a,connected:!1,sessionResumed:!1,error:null},l={type:"leaf",terminalId:a},i={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[a],layout:l,createdAt:Date.now()};return e({tabs:[...r.tabs,i],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[a]:c},terminalIds:i.terminalIds,layout:i.layout}),V(B(t())),o},switchTab:n=>{const o=t().tabs.find(a=>a.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),V(B(t())))},closeTab:n=>{const r=t(),o=r.tabs.find(u=>u.id===n);if(!o||o.status!=="open"||r.tabs.filter(u=>u.status==="open").length<=1)return;const c={...r.terminalsMap};for(const u of o.terminalIds)delete c[u];const l=X(r.tabs,n,u=>({...u,status:"closed"}));let i=r.activeTabId,m=r.terminalIds,f=r.layout;if(r.activeTabId===n){const u=r.tabs.findIndex(h=>h.id===n),x=l.filter(h=>h.status==="open"),p=x.find(h=>l.findIndex(C=>C.id===h.id)>u)||x[x.length-1];p&&(i=p.id,m=p.terminalIds,f=p.layout)}e({tabs:l,activeTabId:i,terminalsMap:c,terminalIds:m,layout:f}),V(B(t()))},reopenTab:n=>{const r=t(),o=r.tabs.find(l=>l.id===n);if(!o||o.status!=="closed")return;const a={...r.terminalsMap};for(const l of o.terminalIds)a[l]={id:l,connected:!1,sessionResumed:!1,error:null};const c=X(r.tabs,n,l=>({...l,status:"open"}));e({tabs:c,activeTabId:n,terminalsMap:a,terminalIds:o.terminalIds,layout:o.layout}),V(B(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(p=>p.id===n);if(!o)return;const a=r.token;a&&await Promise.all(o.terminalIds.map(p=>fetch(`${_}/api/sessions/${encodeURIComponent(p)}`,{method:"DELETE",headers:U(a)}).catch(()=>{})));const c=t(),l=c.tabs.find(p=>p.id===n);if(!l)return;const i={...c.terminalsMap};for(const p of l.terminalIds)delete i[p];const m=c.tabs.filter(p=>p.id!==n);let f=c.activeTabId,u=c.terminalIds,x=c.layout;if(c.activeTabId===n){const p=m.find(h=>h.status==="open");p?(f=p.id,u=p.terminalIds,x=p.layout):(f="",u=[],x=null)}e({tabs:m,activeTabId:f,terminalsMap:i,terminalIds:u,layout:x}),V(B(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=X(t().tabs,n,a=>({...a,name:r}));e({tabs:o}),V(B(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const a=xe(o);if(!a){const R=`tab${o.nextTabId}`,E=r||`t${o.nextId}`;let D=o.nextId;const k=E.match(/^t(\d+)$/);k&&(D=Math.max(D,parseInt(k[1],10)+1));const b=r?D:D+1,S={id:E,connected:!1,sessionResumed:!1,error:null},N={type:"leaf",terminalId:E},$={id:R,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[E],layout:N,createdAt:Date.now()};return e({tabs:[...o.tabs,$],activeTabId:R,nextTabId:o.nextTabId+1,nextId:b,terminalsMap:{...o.terminalsMap,[E]:S},terminalIds:[E],layout:N}),V(B(t())),E}const{nextId:c,nextSplitId:l,terminalsMap:i}=o,{terminalIds:m,layout:f}=a,u=r||`t${c}`;let x=c;const p=u.match(/^t(\d+)$/);p&&(x=Math.max(x,parseInt(p[1],10)+1));const h={id:u,connected:!1,sessionResumed:!1,error:null},w={type:"leaf",terminalId:u};let C,v=l;if(!f)C=w;else if(f.type==="leaf"){const R=n||"horizontal";C={id:`s${v}`,type:"split",direction:R,children:[f,w],sizes:[50,50]},v++}else if(f.direction===(n||"horizontal")){const E=100/(f.children.length+1),D=(100-E)/100,k=[...f.sizes.map(b=>b*D),E];C={...f,children:[...f.children,w],sizes:k}}else{const R=n||"horizontal";C={id:`s${v}`,type:"split",direction:R,children:[f,w],sizes:[50,50]},v++}const L=[...m,u],j=r?x:x+1,y=X(o.tabs,a.id,R=>({...R,terminalIds:L,layout:C}));return e({terminalsMap:{...i,[u]:h},terminalIds:L,layout:C,tabs:y,nextId:j,nextSplitId:v}),V(B(t())),u},splitTerminal:(n,r)=>{const o=t(),a=xe(o);if(!a||!a.layout)return"";const{nextId:c,nextSplitId:l,terminalsMap:i}=o,m=`t${c}`,f={id:m,connected:!1,sessionResumed:!1,error:null},u={type:"leaf",terminalId:m},x=`s${l}`,p=Ze(a.layout,n,r,u,x),h=[...a.terminalIds,m],w=c+1,C=l+1,v=X(o.tabs,a.id,L=>({...L,terminalIds:h,layout:p}));return e({terminalsMap:{...i,[m]:f},terminalIds:h,layout:p,tabs:v,nextId:w,nextSplitId:C}),V(B(t())),m},removeTerminal:n=>{const r=De(t(),n);r&&(e(r),V(B(t())))},setTerminalConnected:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const a=o.terminalsMap[n];return!a||a.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...a,error:r}}}})},setSplitSizes:(n,r)=>{const o=t(),a=xe(o);if(!a||!a.layout)return;const c=Qe(a.layout,n,r),l=X(o.tabs,a.id,i=>({...i,layout:c}));e({layout:c,tabs:l}),en(B(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null;const o=t().token;o&&Yt(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${_}/api/sessions`,{headers:U(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}},killServerSession:async n=>{const r=t().token;if(!r)return;try{await fetch(`${_}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:U(r)})}catch{}const o=De(t(),n);o&&(e(o),V(B(t()))),setTimeout(()=>t().fetchSessions(),500)}}));async function rn(e,t){var o;const{setState:n,getState:r}=T;try{const[a,c]=await Promise.all([Xt(e),fetch(`${_}/api/sessions`,{headers:U(e)}).then(p=>p.ok?p.json():[]).catch(()=>[])]);if(r().token!==e)return;const l=a&&((o=a.tabs)==null?void 0:o.length)>0?a:t;if(!l||l.tabs.length===0){n({tabsLoading:!1});return}const i=nn(l,c);if(!i){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:[],layout:null});return}const m=r().terminalsMap,f={};for(const p of i.tabs)if(p.status==="open")for(const h of p.terminalIds)f[h]=m[h]||{id:h,connected:!1,sessionResumed:!1,error:null};const u=i.tabs.find(p=>p.id===i.activeTabId&&p.status==="open")||i.tabs.find(p=>p.status==="open"),x=(u==null?void 0:u.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:i.tabs,activeTabId:x,nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:(u==null?void 0:u.terminalIds)||[],layout:(u==null?void 0:u.layout)||null}),V(B(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function on(){const[e,t]=d.useState(""),n=T(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, #1a1b26 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"#24283b",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid #292e42"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, #7aa2f7 0%, #bb9af7 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"#1a1b26",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"#c0caf5",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"#565f89",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"#7aa2f7",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"#1a1b26",color:"#c0caf5",border:"1px solid #292e42",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:e.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#414868",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"#1a1b26",padding:"2px 6px",borderRadius:"4px",border:"1px solid #292e42",fontSize:"11px"},children:"server/.env"})]})})]})})}const sn=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,ae=500,an=8e3,ln=1e4,Ne=4e3,cn=5e3,dn=5,un=64*1024,fn=1,Me=2,pn=3,mn=4,hn=new TextDecoder,xn=new TextEncoder;function Ae(e,t){const n=xn.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function bn(e,t,n){const r=d.useRef(null),o=d.useRef(ae),a=d.useRef(null),c=d.useRef(null),l=d.useRef(null),i=d.useRef(null),m=d.useRef(!1),f=d.useRef(n),u=d.useRef(!1),x=d.useRef(0),p=d.useRef(!0),h=d.useRef(!navigator.onLine),w=d.useRef(""),C=d.useRef(null),v=d.useRef("");f.current=n;const L=d.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),a.current&&(clearTimeout(a.current),a.current=null),i.current&&(clearTimeout(i.current),i.current=null),C.current&&(clearTimeout(C.current),C.current=null)},[]),j=d.useCallback(()=>{const{token:D,setTerminalError:k}=T.getState();if(!D||m.current)return;if(r.current){const $=r.current.readyState;if($===WebSocket.OPEN||$===WebSocket.CONNECTING)return}u.current=!1;const b=`${sn}?sessionId=${encodeURIComponent(t)}`,S=new WebSocket(b);S.binaryType="arraybuffer",i.current=window.setTimeout(()=>{S.readyState===WebSocket.CONNECTING&&S.close()},cn);const N=()=>{S.readyState===WebSocket.OPEN&&(x.current=performance.now(),S.send(JSON.stringify({type:"ping"})),l.current=window.setTimeout(()=>{x.current>0&&(x.current=0,S.close())},Ne))};S.onopen=()=>{i.current&&(clearTimeout(i.current),i.current=null),S.send(JSON.stringify({type:"auth",token:D})),k(t,null),o.current=ae,p.current=!0},S.onclose=$=>{const{setTerminalConnected:W,setTerminalError:P,setToken:z}=T.getState();if(W(t,!1),L(),u.current)return;if($.code===4001){m.current=!0,P(t,"Authentication failed"),z(null),localStorage.removeItem("ai-cli-online-token");return}if($.code===4002)return;if($.code===4005){P(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(p.current){p.current=!1,a.current=window.setTimeout(()=>j(),50);return}const M=o.current;o.current=Math.min(M*2,an);const A=Math.round(M*(.5+Math.random()));a.current=window.setTimeout(()=>{j()},A)},S.onerror=()=>{},S.onmessage=$=>{var W;try{const P=e.current;if($.data instanceof ArrayBuffer){const M=new Uint8Array($.data);if(M.length<1)return;const A=M[0],G=M.subarray(1);switch(A){case fn:P==null||P.write(G);break;case pn:P==null||P.write(G);break;case mn:{(W=f.current)==null||W.call(f,hn.decode(G));break}}return}const z=JSON.parse($.data);switch(z.type){case"connected":{const M=T.getState();M.setTerminalConnected(t,!0),M.setTerminalResumed(t,z.resumed);const A=e.current;A&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:A.cols,rows:A.rows})),v.current&&(S.send(Ae(Me,v.current)),v.current=""),N(),c.current=window.setInterval(N,ln);break}case"error":T.getState().setTerminalError(t,z.error);break;case"pong":{if(l.current&&(clearTimeout(l.current),l.current=null),x.current>0){const M=Math.round(performance.now()-x.current),A=T.getState();(A.terminalIds.length===0||A.terminalIds[0]===t)&&A.setLatency(M),x.current=0}break}}}catch{}},r.current=S},[t,e,L]),y=d.useCallback(D=>{const k=r.current;if(!k||k.readyState!==WebSocket.OPEN){v.current.length<un&&(v.current+=D);return}w.current+=D,C.current||(C.current=window.setTimeout(()=>{const b=w.current;w.current="",C.current=null,b&&k.readyState===WebSocket.OPEN&&k.send(Ae(Me,b))},dn))},[]),R=d.useCallback((D,k)=>{var b;((b=r.current)==null?void 0:b.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:D,rows:k}))},[]),E=d.useCallback(()=>{var D;((D=r.current)==null?void 0:D.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]);return d.useEffect(()=>{T.getState().token&&(m.current=!1,j());const k=()=>{h.current=!1,o.current=ae,p.current=!0;const N=r.current;(!N||N.readyState===WebSocket.CLOSED||N.readyState===WebSocket.CLOSING)&&j()},b=()=>{h.current=!0},S=()=>{if(document.visibilityState!=="visible")return;const N=r.current;if(!N||N.readyState!==WebSocket.OPEN){!h.current&&!u.current&&(o.current=ae,p.current=!0,j());return}x.current=performance.now(),N.send(JSON.stringify({type:"ping"})),l.current&&clearTimeout(l.current),l.current=window.setTimeout(()=>{x.current>0&&(x.current=0,N.close())},Ne)};return window.addEventListener("online",k),window.addEventListener("offline",b),document.addEventListener("visibilitychange",S),()=>{u.current=!0,L(),window.removeEventListener("online",k),window.removeEventListener("offline",b),document.removeEventListener("visibilitychange",S),r.current&&(r.current.close(),r.current=null)}},[j,L,t]),{sendInput:y,sendResize:R,requestScrollback:E}}const et={background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",selectionBackground:"#33467c",black:"#15161e",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#414868",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},tt="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",yn=d.forwardRef(function({sessionId:t},n){const r=d.useRef(null),o=d.useRef(null),a=d.useRef(null),[c,l]=d.useState(!1),[i,m]=d.useState(""),f=T(v=>v.fontSize),u=d.useCallback(v=>{m(v),l(!0)},[]),{sendInput:x,sendResize:p,requestScrollback:h}=bn(o,t,u);d.useImperativeHandle(n,()=>({sendInput:x}),[x]);const w=d.useRef(x),C=d.useRef(p);return w.current=x,C.current=p,d.useEffect(()=>{if(!r.current)return;let v=!1,L=null,j=null,y=null,R=null;if(v||!r.current)return;const E=new Ue({cursorBlink:!0,scrollback:1e4,fontSize:T.getState().fontSize,fontFamily:tt,theme:et,allowProposedApi:!0}),D=new We;E.loadAddon(D),E.loadAddon(new pt((S,N)=>{window.open(N,"_blank","noopener,noreferrer")})),E.open(r.current);try{const S=new He;S.onContextLoss(()=>{S.dispose()}),E.loadAddon(S)}catch{}o.current=E,a.current=D;const k=()=>{try{const S=r.current;if(S&&S.clientWidth>0&&S.clientHeight>0)return D.fit(),C.current(E.cols,E.rows),!0}catch{}return!1};requestAnimationFrame(()=>k());let b=0;return L=setInterval(()=>{b++,(k()||b>=10)&&(clearInterval(L),L=null)},100),document.fonts.ready.then(()=>{if(!v)try{D.fit(),C.current(E.cols,E.rows)}catch{}}),E.onData(S=>{w.current(S)}),R=new ResizeObserver(()=>{j||(j=requestAnimationFrame(()=>{j=null;try{D.fit(),y&&clearTimeout(y),y=setTimeout(()=>{y=null,C.current(E.cols,E.rows)},50)}catch{}}))}),R.observe(r.current),()=>{v=!0,L&&clearInterval(L),j&&cancelAnimationFrame(j),y&&clearTimeout(y),R&&R.disconnect(),o.current&&(o.current.dispose(),o.current=null),a.current=null}},[t]),d.useEffect(()=>{const v=o.current,L=a.current;if(!(!v||!L)&&v.options.fontSize!==f){v.options.fontSize=f;try{L.fit()}catch{}C.current(v.cols,v.rows)}},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"#1a1b26",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:v=>{v.currentTarget.blur(),c?(l(!1),m("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize:12,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:v=>{v.currentTarget.style.opacity="1"},onMouseLeave:v=>{v.currentTarget.style.opacity="0.8"},children:c?"✕":"↑"}),c&&s.jsx(gn,{data:i,onClose:()=>{l(!1),m("")}})]})});function gn({data:e,onClose:t}){const n=d.useRef(null),r=d.useRef(t);r.current=t;const o=T(i=>i.fontSize),a=d.useRef(null),c=d.useRef(null);d.useEffect(()=>{if(!n.current)return;const i=new Ue({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:tt,theme:et});a.current=i;const m=new We;c.current=m,i.loadAddon(m),i.open(n.current);try{const w=new He;w.onContextLoss(()=>w.dispose()),i.loadAddon(w)}catch{}i.attachCustomKeyEventHandler(w=>(w.key==="Escape"&&r.current(),!1)),i.write(e);let f=null;const u=()=>{const w=n.current;if(!w||w.clientWidth<=0||w.clientHeight<=0)return!1;try{return m.fit(),i.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!u()){let w=0;f=setInterval(()=>{w++,(u()||w>=30)&&(clearInterval(f),f=null)},50)}});let x=null;const p=new ResizeObserver(()=>{x||(x=requestAnimationFrame(()=>{x=null,u()}))});p.observe(n.current);const h=w=>{w.key==="Escape"&&r.current()};return document.addEventListener("keydown",h),()=>{f&&clearInterval(f),x&&cancelAnimationFrame(x),document.removeEventListener("keydown",h),p.disconnect(),i.dispose(),a.current=null,c.current=null}},[e]),d.useEffect(()=>{var i;if(a.current){a.current.options.fontSize=o;try{(i=c.current)==null||i.fit()}catch{}}},[o]);const l=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26"},children:[s.jsx("div",{style:{height:l,boxSizing:"border-box",padding:"0 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",display:"flex",alignItems:"center"},children:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{position:"absolute",top:l,left:0,right:0,bottom:0,overflow:"hidden"}})]})}async function oe(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:U(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function wn(e,t,n,r){return new Promise((o,a)=>{const c=new FormData;for(const i of n)c.append("files",i);const l=new XMLHttpRequest;l.open("POST",`${_}/api/sessions/${encodeURIComponent(t)}/upload`),l.setRequestHeader("Authorization",`Bearer ${e}`),l.upload.addEventListener("progress",i=>{i.lengthComputable&&r&&r(Math.round(i.loaded/i.total*100))}),l.addEventListener("load",()=>{l.status>=200&&l.status<300?o():a(new Error(`Upload failed: ${l.status}`))}),l.addEventListener("error",()=>a(new Error("Upload network error"))),l.addEventListener("abort",()=>a(new Error("Upload aborted"))),l.send(c)})}async function vn(e,t){const n=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:U(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function Sn(e,t,n){const r=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:U(e)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),a=URL.createObjectURL(o),c=document.createElement("a");c.href=a,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(a)}function ve({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=T(j=>j.token),[a,c]=d.useState(""),[l,i]=d.useState([]),[m,f]=d.useState(!0),[u,x]=d.useState(null),p=d.useRef(""),h=d.useCallback(async j=>{if(o){f(!0),x(null);try{const y=await oe(o,e,j);j||(p.current=y.cwd),c(y.cwd),i(n?n(y.files):y.files)}catch(y){x(y instanceof Error?y.message:"Failed to load files")}finally{f(!1)}}},[o,e,n]);d.useEffect(()=>{h()},[h]),d.useEffect(()=>{if(!r||!o)return;let j=!1;const y=setInterval(async()=>{if(!j)try{const R=await vn(o,e);if(j)return;if(R!==p.current){p.current=R;const E=await oe(o,e);if(j)return;c(E.cwd),i(n?n(E.files):E.files)}}catch{}},r);return()=>{j=!0,clearInterval(y)}},[r,o,e,n]);const w=d.useRef(t);w.current=t,d.useEffect(()=>{const j=y=>{y.key==="Escape"&&w.current()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[]);const C=d.useCallback(j=>{h(a+"/"+j)},[h,a]),v=d.useCallback(()=>{const j=a.replace(/\/[^/]+$/,"")||"/";h(j)},[h,a]),L=d.useCallback(()=>{h(a)},[h,a]);return{cwd:a,files:l,loading:m,error:u,setError:x,handleNavigate:C,handleGoUp:v,handleRefresh:L}}function Tn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function nt(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Se({cwd:e,onGoUp:t,onRefresh:n,onClose:r}){return s.jsxs("div",{style:{padding:"6px 12px",background:"#24283b",borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[s.jsx("button",{onClick:t,style:{background:"none",border:"1px solid #414868",color:"#7aa2f7",borderRadius:3,padding:"1px 8px",fontSize:12,cursor:"pointer",flexShrink:0},title:"Go to parent directory",children:".."}),s.jsx("span",{style:{color:"#7aa2f7",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e||"..."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[s.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Refresh",children:"↻"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Close (ESC)",children:"✕"})]})]})}function Te({loading:e,error:t,empty:n,emptyText:r="Empty directory"}){return e?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):t?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:t}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function kn({sessionId:e,onClose:t}){const n=T(h=>h.token),{cwd:r,files:o,loading:a,error:c,setError:l,handleNavigate:i,handleGoUp:m,handleRefresh:f}=ve({sessionId:e,onClose:t}),[u,x]=d.useState(null),p=async h=>{if(n){x(h);try{await Sn(n,e,r+"/"+h)}catch(w){l(w instanceof Error?w.message:"Download failed")}finally{x(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Se,{cwd:r,onGoUp:m,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{loading:a,error:c,empty:o.length===0,emptyText:"Empty directory"}),!a&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&i(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:w=>{w.stopPropagation(),p(h.name)},disabled:u===h.name,style:{background:"none",border:"1px solid #414868",color:u===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:u===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:u===h.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:h.type==="directory"?"#7aa2f7":"#565f89"},children:h.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:h.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:h.type==="file"?Tn(h.size):""})]},h.name))]})]})}function In({content:e}){const t=T(r=>r.fontSize),n=d.useMemo(()=>{if(!e)return"";const r=mt.parse(e,{async:!1});return ht.sanitize(r,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[e]);return e?s.jsx("div",{className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${t}px`},dangerouslySetInnerHTML:{__html:n}}):s.jsx("div",{className:"md-preview",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#414868",fontStyle:"italic",fontSize:"13px"},children:"Waiting for plan output..."})}async function Cn(e,t){const n=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:U(e)});return n.ok?(await n.json()).content??"":""}async function Oe(e,t,n){await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...U(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const $e=[{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"}],jn=d.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},a){const c=T(g=>g.fontSize),[l,i]=d.useState(""),m=d.useRef(null),f=d.useRef(),u=d.useRef(!1),[x,p]=d.useState(!1),[h,w]=d.useState(""),[C,v]=d.useState(0),[L,j]=d.useState(!1),[y,R]=d.useState(""),[E,D]=d.useState(""),[k,b]=d.useState(0),[S,N]=d.useState([]),[$,W]=d.useState(!1),P=d.useRef(""),z=d.useRef(null),M=d.useMemo(()=>{if(!h)return $e;const g=h.toLowerCase();return $e.filter(I=>I.cmd.toLowerCase().includes(g)||I.desc.toLowerCase().includes(g))},[h]),A=d.useMemo(()=>{let g=S;if(y){const I=y.toLowerCase();g=g.filter(O=>O.name.toLowerCase().includes(I))}return[...g].sort((I,O)=>I.type==="directory"&&O.type!=="directory"?-1:I.type!=="directory"&&O.type==="directory"?1:I.name.localeCompare(O.name))},[S,y]);d.useEffect(()=>{let g=!1;return Cn(o,r).then(I=>{!g&&I&&i(I),u.current=!0}).catch(()=>{u.current=!0}),()=>{g=!0}},[o,r]),d.useEffect(()=>{if(u.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{Oe(o,r,l).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[l,o,r]),d.useEffect(()=>{var g;(g=m.current)==null||g.focus()},[]),d.useEffect(()=>{if(!L)return;let g=!1;return W(!0),(async()=>{try{if(E){if(!P.current){const F=await oe(o,r);if(g)return;P.current=F.cwd}const I=`${P.current}/${E.replace(/\/$/,"")}`,O=await oe(o,r,I);if(g)return;N(O.files)}else{const I=await oe(o,r);if(g)return;P.current=I.cwd,N(I.files)}W(!1)}catch{if(g)return;N([]),W(!1)}})(),()=>{g=!0}},[L,E,o,r]),d.useEffect(()=>{if(!L||!z.current)return;const g=z.current.querySelector(".file-item--active");g==null||g.scrollIntoView({block:"nearest"})},[k,L]);const G=d.useCallback(()=>{const g=l.trim();g&&(t(g),i(""),Oe(o,r,"").catch(()=>{}))},[l,t,o,r]);d.useImperativeHandle(a,()=>({send:G}),[G]),d.useEffect(()=>{n==null||n(l.trim().length>0)},[l,n]);const fe=d.useCallback(g=>{const I=m.current;if(!I)return;const O=I.selectionStart,F=l.slice(0,O),J=l.slice(O),K=F.lastIndexOf(`
26
- `)+1,q=F.slice(K).match(/\/[a-zA-Z-]*$/);if(q){const H=K+(q.index??0),ee=g+" ",me=l.slice(0,H)+ee+J;i(me);const lt=H+ee.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=lt,I.focus()})}else{const H=F+g+J;i(H);const ee=O+g.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=ee,I.focus()})}p(!1),w(""),v(0)},[l]),pe=d.useCallback(g=>{const I=m.current;if(!I)return;const O=I.selectionStart,F=l.slice(0,O),J=l.slice(O),Q=F.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!Q)return;const K=F.length-Q[0].length;if(g.type==="directory"){const Y="@"+E+g.name+"/",q=l.slice(0,K)+Y+J;i(q);const H=K+Y.length;D(E+g.name+"/"),R(""),b(0),requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=H,I.focus()})}else{const Y=g.name+" ",q=l.slice(0,K)+Y+J;i(q);const H=K+Y.length;j(!1),R(""),D(""),b(0),N([]),P.current="",requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=H,I.focus()})}},[l,E]),it=d.useCallback(g=>{const I=g.target.value;i(I);const O=g.target.selectionStart,F=I.slice(0,O),J=F.lastIndexOf(`
27
- `),K=F.slice(J+1).match(/^\/([a-zA-Z-]*)$/);if(K)p(!0),w(K[1]),v(0),j(!1);else{p(!1);const Y=F.match(/@([a-zA-Z0-9_.\-/]*)$/);if(Y){const q=Y[1],H=q.lastIndexOf("/"),ee=H>=0?q.slice(0,H+1):"",me=H>=0?q.slice(H+1):q;R(me),b(0),D(ee),j(!0)}else j(!1)}},[]),at=d.useCallback(g=>{if(x&&M.length>0){if(g.key==="ArrowDown"){g.preventDefault(),v(I=>(I+1)%M.length);return}if(g.key==="ArrowUp"){g.preventDefault(),v(I=>(I-1+M.length)%M.length);return}if(g.key==="Enter"||g.key==="Tab"){g.preventDefault(),fe(M[C].cmd);return}if(g.key==="Escape"){g.preventDefault(),p(!1);return}}if(L&&A.length>0){if(g.key==="ArrowDown"){g.preventDefault(),b(I=>(I+1)%A.length);return}if(g.key==="ArrowUp"){g.preventDefault(),b(I=>(I-1+A.length)%A.length);return}if(g.key==="Tab"||g.key==="Enter"){g.preventDefault(),pe(A[k]);return}if(g.key==="Escape"){g.preventDefault(),j(!1);return}}if(g.key==="Tab"){g.preventDefault();const I=m.current;if(I){const O=I.selectionStart,F=I.selectionEnd,J=l.slice(0,O)+" "+l.slice(F);i(J);const Q=O+2;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Q})}return}g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),G())},[G,x,M,C,fe,l,L,A,k,pe]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[x&&M.length>0&&s.jsx("div",{className:"slash-dropdown",children:M.map((g,I)=>s.jsxs("div",{className:`slash-item${I===C?" slash-item--active":""}`,onMouseDown:O=>{O.preventDefault(),fe(g.cmd)},onMouseEnter:()=>v(I),children:[s.jsx("span",{className:"slash-cmd",children:g.cmd}),s.jsx("span",{className:"slash-desc",children:g.desc})]},g.cmd))}),L&&($||A.length>0)&&s.jsx("div",{className:"file-dropdown",ref:z,children:$?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):A.map((g,I)=>s.jsxs("div",{className:`file-item${I===k?" file-item--active":""}`,onMouseDown:O=>{O.preventDefault(),pe(g)},onMouseEnter:()=>b(I),children:[s.jsx("span",{className:"file-icon",children:g.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:g.name})]},g.name))}),s.jsx("textarea",{ref:m,className:"md-editor-textarea",value:l,onChange:it,onKeyDown:at,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function En(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Rn(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function zn({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:a,error:c,handleNavigate:l,handleGoUp:i,handleRefresh:m}=ve({sessionId:e,onClose:n}),f=u=>{t(r+"/"+u)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(Se,{cwd:r,onGoUp:i,onRefresh:m,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{loading:a,error:c,empty:o.length===0,emptyText:"No files found"}),!a&&!c&&o.map(u=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent"},onClick:()=>{u.type==="directory"?l(u.name):f(u.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:u.type==="directory"?"#7aa2f7":"#565f89"},children:Rn(u.name,u.type)}),s.jsx("span",{style:{flex:1,color:u.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:u.name}),u.type==="file"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:En(u.size)}),s.jsx("span",{style:{fontSize:10,color:"#565f89",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:u.name.slice(u.name.lastIndexOf(".")).toLowerCase()})]})]},u.name))]})]})}const Ln="modulepreload",Dn=function(e){return"/"+e},Pe={},Nn=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(i=>{if(i=Dn(i),i in Pe)return;Pe[i]=!0;const m=i.endsWith(".css"),f=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${i}"]${f}`))return;const u=document.createElement("link");if(u.rel=m?"stylesheet":Ln,m||(u.as="script"),u.crossOrigin="",u.href=i,l&&u.setAttribute("nonce",l),document.head.appendChild(u),m)return new Promise((x,p)=>{u.addEventListener("load",x),u.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${i}`)))})}))}function a(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return o.then(c=>{for(const l of c||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})};let ge=null,be=null;function Mn(){return be||(be=Nn(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(ge=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),be}function An({data:e,scrollRef:t}){const n=d.useRef(null),[r,o]=d.useState(null),[a,c]=d.useState(!0),l=d.useRef(0),i=m=>{n.current=m,t==null||t(m)};return d.useEffect(()=>{if(!e)return;const m=++l.current;return c(!0),o(null),(async()=>{try{if(await Mn(),!ge||m!==l.current)return;const f=atob(e),u=new Uint8Array(f.length);for(let w=0;w<f.length;w++)u[w]=f.charCodeAt(w);const x=await ge.getDocument({data:u}).promise;if(m!==l.current)return;const p=n.current;if(!p)return;for(;p.firstChild;)p.removeChild(p.firstChild);const h=p.clientWidth-24;for(let w=1;w<=x.numPages;w++){const C=await x.getPage(w);if(m!==l.current)return;const v=C.getViewport({scale:1}),L=Math.min(h/v.width,2),j=C.getViewport({scale:L}),y=document.createElement("canvas");y.width=j.width,y.height=j.height,y.style.display="block",y.style.margin="0 auto 8px",y.style.maxWidth="100%";const R=y.getContext("2d");if(R){if(await C.render({canvasContext:R,viewport:j,canvas:y}).promise,m!==l.current)return;p.appendChild(y)}}c(!1)}catch(f){if(m!==l.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{l.current++}},[e]),s.jsxs("div",{ref:i,className:"pdf-renderer",children:[a&&s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading PDF..."}),r&&s.jsxs("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:["PDF Error: ",r]})]})}async function _e(e,t,n,r){const o=new URLSearchParams({path:n});r&&o.set("since",String(r));const a=await fetch(`${_}/api/sessions/${encodeURIComponent(t)}/file-content?${o}`,{headers:U(e)});if(a.status===304)return null;if(!a.ok)throw new Error("Failed to fetch file content");return a.json()}function On(e=50,t=20,n=80){const[r,o]=d.useState(e),a=d.useRef(null),c=d.useCallback(l=>{l.preventDefault();const i=a.current;if(!i)return;const m=i.getBoundingClientRect(),f=m.width;document.body.classList.add("resizing-panes-h");let u=null;const x=h=>{u||(u=requestAnimationFrame(()=>{u=null;const w=h.clientX-m.left,C=Math.min(n,Math.max(t,w/f*100));o(C)}))},p=()=>{u&&cancelAnimationFrame(u),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",p)};document.addEventListener("mousemove",x),document.addEventListener("mouseup",p)},[t,n]);return{leftWidthPercent:r,containerRef:a,onDividerMouseDown:c}}const $n=3e3;function Pn(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":"text"}function Fe(e){return e.split("/").pop()||e}function _n(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Fn(e){if(e.type==="directory")return"📁";const t=e.name.slice(e.name.lastIndexOf(".")).toLowerCase();return t===".pdf"?"📕":t===".html"||t===".htm"?"🌐":t===".md"?"📝":"📄"}const Bn=3e3;function Un({sessionId:e,onSelect:t}){const n=d.useCallback(()=>{},[]),{cwd:r,files:o,loading:a,error:c,handleNavigate:l,handleGoUp:i,handleRefresh:m}=ve({sessionId:e,onClose:n,pollCwd:Bn});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(Se,{cwd:r,onGoUp:i,onRefresh:m,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(Te,{loading:a,error:c,empty:o.length===0,emptyText:"No files found"}),!a&&!c&&o.map(f=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:u=>{u.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent"},onClick:()=>{f.type==="directory"?l(f.name):t(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Fn(f)}),s.jsx("span",{style:{flex:1,color:f.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:f.name}),f.type==="file"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:_n(f.size)}),s.jsx("span",{style:{fontSize:10,color:"#565f89",background:"#24283b",padding:"1px 5px",borderRadius:3,marginLeft:6,flexShrink:0},children:f.name.slice(f.name.lastIndexOf(".")).toLowerCase()})]})]},f.name))]})]})}function Wn({sessionId:e,token:t,onClose:n,onSend:r}){const[o,a]=d.useState(null),[c,l]=d.useState(""),[i,m]=d.useState(null),f=d.useRef(0),[u,x]=d.useState(!1),[p,h]=d.useState(!1),[w,C]=d.useState(!1),{leftWidthPercent:v,containerRef:L,onDividerMouseDown:j}=On(50),y=d.useRef(null),[R,E]=d.useState(!1),D=d.useRef(new Map),k=d.useRef(null),b=d.useRef(null),S=d.useCallback(()=>{if(!o)return;const z=p?b.current:k.current;z&&D.current.set(o,z.scrollTop)},[o,p]),N=d.useCallback(z=>{const M=D.current.get(z);M!=null&&requestAnimationFrame(()=>{const A=p?b.current:k.current;A&&(A.scrollTop=M)})},[p]),$=d.useCallback(z=>{S();const M=Pn(z);a(z),m(M),l(""),f.current=0,x(!1),_e(t,e,z).then(A=>{A&&(l(A.content),f.current=A.mtime,requestAnimationFrame(()=>N(z)))}).catch(()=>{})},[t,e,S,N]);d.useEffect(()=>{if(!o)return;let z=!1;const A=setInterval(async()=>{if(!z)try{const G=await _e(t,e,o,f.current);if(z)return;G&&(l(G.content),f.current=G.mtime)}catch{}},$n);return()=>{z=!0,clearInterval(A)}},[t,e,o]);const W=d.useCallback(()=>{o&&navigator.clipboard.writeText(o).then(()=>{C(!0),setTimeout(()=>C(!1),1500)}).catch(()=>{})},[o]);d.useEffect(()=>{if(!p)return;const z=M=>{M.key==="Escape"&&(S(),h(!1))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[p,S]),d.useEffect(()=>{o&&N(o)},[p,o,N]);const P=z=>o?!c&&i!=="pdf"?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:"13px"},children:"Loading..."}):i==="md"?s.jsx("div",{ref:z,style:{height:"100%",overflow:"auto"},children:s.jsx(In,{content:c})}):i==="html"?s.jsx("div",{ref:z,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:c,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})}):i==="pdf"?s.jsx(An,{data:c,scrollRef:z}):s.jsx("div",{ref:z,style:{height:"100%",overflow:"auto"},children:s.jsx("pre",{style:{margin:0,padding:"12px",fontFamily:'"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',fontSize:"13px",color:"#a9b1d6",whiteSpace:"pre-wrap",wordBreak:"break-all",lineHeight:1.5},children:c})}):s.jsx(Un,{sessionId:e,onSelect:$});return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",height:"28px",flexShrink:0,backgroundColor:"#16161e",borderBottom:"1px solid #292e42"},children:[s.jsxs("div",{style:{width:`${v}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>x(z=>!z),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),o&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:W,title:w?"Copied!":`Click to copy: ${o}`,children:w?"Copied!":Fe(o)}),s.jsx("button",{className:"pane-btn",onClick:()=>{S(),h(!0)},title:"Expand document view",style:{fontSize:"12px"},children:"⛶"})]})]}),s.jsx("div",{style:{width:"4px",flexShrink:0}}),s.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>{var z;return(z=y.current)==null?void 0:z.send()},disabled:!R,title:"Send to terminal (Ctrl+Enter)",style:R?{color:"#9ece6a"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"10px",color:"#414868"},children:"Ctrl+Enter"})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:n,title:"Close Doc panel",children:"×"})]})]}),s.jsxs("div",{ref:L,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${v}%`,flexShrink:0},children:[P(z=>{k.current=z}),u&&s.jsx(zn,{sessionId:e,onSelect:$,onClose:()=>x(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:j}),s.jsx("div",{className:"plan-editor-wrap",children:s.jsx(jn,{ref:y,onSend:r,onContentChange:E,sessionId:e,token:t})})]}),p&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsx("span",{style:{fontSize:"12px",color:"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o?Fe(o):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{S(),h(!1)},title:"Close expanded view (ESC)",children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:P(z=>{b.current=z})})]})]})}const Hn=100,Vn=600,te=typeof window<"u"?window.matchMedia(`(max-width: ${Vn-1}px)`):null;function Gn(){const[e,t]=d.useState(()=>(te==null?void 0:te.matches)??!1);return d.useEffect(()=>{if(!te)return;const n=r=>t(r.matches);return te.addEventListener("change",n),()=>te.removeEventListener("change",n)},[]),e}const qn=d.memo(function({terminal:t,canClose:n}){const r=Gn(),o=T(k=>k.killServerSession),a=T(k=>k.splitTerminal),c=T(k=>k.token),l=d.useRef(null),i=d.useRef(null),[m,f]=d.useState(!1),[u,x]=d.useState(!1),[p,h]=d.useState(0),[w,C]=d.useState(!1),[v,L]=d.useState(50),j=d.useRef(null),y=async k=>{const b=k.target.files;if(!(!b||b.length===0||!c)){x(!0),h(0);try{await wn(c,t.id,b,S=>{h(S)})}catch(S){alert(`Upload failed: ${S instanceof Error?S.message:"Unknown error"}`)}finally{x(!1),h(0),l.current&&(l.current.value="")}}},R=d.useRef(),E=d.useCallback(k=>{if(i.current){const b=k.replace(/\r?\n/g," ").trimEnd();i.current.sendInput(b),R.current=window.setTimeout(()=>{var S;return(S=i.current)==null?void 0:S.sendInput("\r")},50)}},[]);d.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]);const D=d.useCallback(k=>{k.preventDefault();const b=j.current;if(!b)return;const S=b.getBoundingClientRect(),N=S.height;document.body.classList.add("resizing-panes-v");const $=P=>{const z=(P.clientY-S.top)/N*100,M=Math.min(80,Math.max(20,z));L(100-M)},W=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",$),document.addEventListener("mouseup",W)},[]);return s.jsxs("div",{ref:j,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"2px 8px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0,height:"24px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:t.connected?"#9ece6a":"#f7768e"}}),s.jsxs("span",{style:{fontSize:"11px",color:"#565f89"},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:l,type:"file",multiple:!0,style:{display:"none"},onChange:y}),s.jsx("button",{className:"pane-btn",onClick:()=>{var k;return(k=l.current)==null?void 0:k.click()},disabled:u,style:u?{color:"#e0af68"}:void 0,title:u?`Uploading ${p}%`:"Upload files","aria-label":"Upload files",children:u?`${p}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>f(k=>!k),style:m?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${w?" pane-btn--active":""}`,onClick:()=>C(k=>!k),title:"Toggle Document browser","aria-label":"Toggle Document browser",children:"Doc"}),s.jsx("button",{className:"pane-btn",onClick:()=>a(t.id,r?"vertical":"horizontal"),title:r?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>a(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"}),n&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>o(t.id),title:"Close terminal","aria-label":"Close terminal",children:"×"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(yn,{ref:i,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(26, 27, 38, 0.85)",zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"#565f89",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})}),m&&s.jsx(kn,{sessionId:t.id,onClose:()=>f(!1)})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:D}),s.jsx("div",{style:{height:`${v}%`,minHeight:Hn,flexShrink:0,overflow:"hidden"},children:s.jsx(Wn,{onSend:E,onClose:()=>C(!1),sessionId:t.id,token:c||""})})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:t.error})]})});class rt extends d.Component{constructor(){super(...arguments);ke(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){}render(){var n,r;return this.state.hasError?this.props.inline?s.jsxs("div",{style:{height:"100%",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"#c0caf5",fontFamily:"monospace",padding:"16px"},children:[s.jsx("div",{style:{fontSize:"14px",color:"#f7768e"},children:"Pane crashed"}),s.jsx("div",{style:{fontSize:"12px",color:"#565f89",textAlign:"center"},children:((n=this.state.error)==null?void 0:n.message)||"An unexpected error occurred"}),s.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"#292e42",border:"1px solid #414868",color:"#c0caf5",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):s.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"#c0caf5",fontFamily:"monospace"},children:[s.jsx("div",{style:{fontSize:"18px",color:"#f7768e"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"#565f89",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),s.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, #7aa2f7 0%, #bb9af7 100%)",border:"none",color:"#1a1b26",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const Kn=4,Be=10;function Jn(){const e=T(o=>o.layout),t=T(o=>o.terminalIds.length),n=T(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#1a1b26"},children:s.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed #292e42",color:"#565f89",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(ot,{node:e,canClose:r})})}const ot=d.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(Yn,{terminalId:t.terminalId,canClose:n}):s.jsx(Xn,{node:t,canClose:n})}),Yn=d.memo(function({terminalId:t,canClose:n}){const r=T(o=>o.terminalsMap[t]);return r?s.jsx(rt,{inline:!0,children:s.jsx(qn,{terminal:r,canClose:n})}):null}),Xn=d.memo(function({node:t,canClose:n}){const r=T(m=>m.setSplitSizes),o=d.useRef(null),a=t.direction==="horizontal",c=d.useRef(t.sizes);c.current=t.sizes;const l=d.useCallback((m,f)=>{f.preventDefault();const u=a?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const x=a?f.clientX:f.clientY,p=[...c.current],h=o.current,w=a?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let C=null;const v=j=>{C||(C=requestAnimationFrame(()=>{C=null;const E=((a?j.clientX:j.clientY)-x)/w*100,D=p[m]+E,k=p[m+1]-E;if(D>=Be&&k>=Be){const b=[...p];b[m]=D,b[m+1]=k,r(t.id,b)}}))},L=()=>{C&&cancelAnimationFrame(C),document.body.classList.remove(u),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",L)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",L)},[a,t.id,r]),i=[];return t.children.forEach((m,f)=>{const u=m.type==="leaf"?m.terminalId:m.id;i.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(ot,{node:m,canClose:n})},u)),f<t.children.length-1&&i.push(s.jsx("div",{onMouseDown:x=>l(f,x),style:{flex:`0 0 ${Kn}px`,cursor:a?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:a?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:i})});function Zn({tabId:e}){const t=T(b=>b.tabs.find(S=>S.id===e)),n=T(b=>b.activeTabId),r=T(b=>b.switchTab),o=T(b=>b.closeTab),a=T(b=>b.reopenTab),c=T(b=>b.deleteTab),l=T(b=>b.renameTab),i=T(b=>t?t.terminalIds.map(S=>{const N=b.terminalsMap[S];return N?{id:S,connected:N.connected}:{id:S,connected:!1}}):[]),[m,f]=d.useState(!1),[u,x]=d.useState(""),[p,h]=d.useState(!1),w=d.useRef(null);if(!t)return null;const C=n===e,v=t.status==="open",L=()=>{v&&r(e)},j=b=>{v&&(b.stopPropagation(),x(t.name),f(!0),setTimeout(()=>{var S;return(S=w.current)==null?void 0:S.focus()},0))},y=()=>{const b=u.trim();b&&l(e,b),f(!1)},R=b=>{b.stopPropagation(),a(e)},E=b=>{b.stopPropagation(),o(e)},D=async b=>{b.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},k=b=>{b.stopPropagation(),h(!p)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:v?"pointer":"default",borderLeft:C?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:C?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s",opacity:v?1:.5},onMouseEnter:b=>{v&&!C&&(b.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:b=>{C||(b.currentTarget.style.backgroundColor="transparent")},children:[v&&t.terminalIds.length>0&&s.jsx("button",{onClick:k,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:p?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[m?s.jsx("input",{ref:w,value:u,onChange:b=>x(b.target.value),onBlur:y,onKeyDown:b=>{b.key==="Enter"&&y(),b.key==="Escape"&&f(!1)},style:{width:"100%",background:"#1a1b26",border:"1px solid #7aa2f7",color:"#c0caf5",borderRadius:"3px",padding:"1px 4px",fontSize:"13px",outline:"none"}}):s.jsx("div",{onDoubleClick:j,style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:v?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",nt(Math.floor(t.createdAt/1e3))]})]}),v?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:E,style:{flexShrink:0},title:"Close tab",children:"×"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:R,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:D,title:"Delete tab",children:"×"})]})]}),v&&p&&i.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:i.map(b=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)"},title:`Connected: ${b.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:b.id}),s.jsx("span",{style:{marginLeft:"8px",color:b.connected?"#9ece6a":"#f7768e"},children:b.connected?"●":"○"})]},b.id))})]})}function Qn({sessionId:e,active:t,createdAt:n}){const r=T(l=>l.addTerminal),o=T(l=>l.killServerSession),a=()=>{r("horizontal",e)},c=l=>{l.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};return s.jsxs("div",{onClick:a,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"13px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:nt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function er(){const e=T(i=>i.sidebarOpen),t=T(i=>i.toggleSidebar),n=T(i=>i.fetchSessions),r=T(i=>e?i.serverSessions:[]),o=T(i=>e?i.tabs:[]),a=T(i=>i.terminalIds.length),c=new Set(o.flatMap(i=>i.terminalIds)),l=r.filter(i=>!c.has(i.sessionId));return d.useEffect(()=>{if(!e)return;n();let i=setInterval(n,5e3);const m=()=>{document.hidden?i&&(clearInterval(i),i=null):(n(),i||(i=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",m),()=>{i&&clearInterval(i),document.removeEventListener("visibilitychange",m)}},[e,n]),d.useEffect(()=>{if(!e)return;const i=setTimeout(n,800);return()=>clearTimeout(i)},[a,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:e?"1px solid #292e42":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("span",{style:{color:"#7aa2f7",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Sessions"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"#7aa2f7",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid #292e42"},children:"TABS"}),o.length===0?s.jsx("div",{style:{color:"#565f89",fontSize:"13px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(i=>s.jsx(Zn,{tabId:i.id},i.id))]}),l.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.jsx("div",{style:{padding:"8px 12px",color:"#e0af68",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid #292e42"},children:"ORPHANED SESSIONS"}),l.map(i=>s.jsx(Qn,{sessionId:i.sessionId,active:i.active,createdAt:i.createdAt},i.sessionId))]})]})]})}const st=we.memo(()=>{const e=T(y=>y.tabs),t=T(y=>y.activeTabId),n=T(y=>y.addTab),r=T(y=>y.switchTab),o=T(y=>y.closeTab),a=T(y=>y.renameTab),[c,l]=d.useState(null),[i,m]=d.useState(""),f=d.useRef(null),u=e.filter(y=>y.status==="open");d.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const x=y=>{l(y.id),m(y.name)},p=()=>{c&&i.trim()&&a(c,i.trim()),l(null),m("")},h=()=>{l(null),m("")},w=y=>{y.key==="Enter"?p():y.key==="Escape"&&h()},C=y=>{c||r(y)},v=(y,R)=>{y.stopPropagation(),o(R)},L=(y,R)=>{y.button===1&&(y.preventDefault(),o(R))},j=u.length>1;return s.jsxs("div",{className:"tab-bar",children:[u.map(y=>{const R=y.id===t,E=c===y.id,D=y.terminalIds.length;return s.jsx("div",{className:`tab-item ${R?"tab-item--active":""}`,onClick:()=>C(y.id),onDoubleClick:()=>x(y),onMouseDown:k=>L(k,y.id),children:E?s.jsx("input",{ref:f,type:"text",value:i,onChange:k=>m(k.target.value),onBlur:p,onKeyDown:w,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[y.name," ",D>0&&`(${D})`]}),j&&s.jsx("button",{className:"tab-item__close",onClick:k=>v(k,y.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},y.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});st.displayName="TabBar";function tr(){return localStorage.getItem("ai-cli-online-token")}function nr(){const e=T(i=>i.token),t=T(i=>i.setToken),n=T(i=>i.tabs),r=T(i=>i.addTab),o=T(i=>i.toggleSidebar),a=T(i=>i.fontSize),c=T(i=>i.setFontSize),l=T(i=>i.tabsLoading);return d.useEffect(()=>{const i=tr();i&&!e&&t(i)},[]),d.useEffect(()=>{e&&!l&&n.filter(i=>i.status==="open").length===0&&r("Default")},[e,l]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"#1a1b26"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"#7aa2f7",letterSpacing:"0.5px"},children:"AI-Cli Online"})}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>c(a-1),disabled:a<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),s.jsx("span",{style:{fontSize:"11px",color:"#a9b1d6",minWidth:"20px",textAlign:"center"},children:a}),s.jsx("button",{className:"header-btn",onClick:()=>c(a+1),disabled:a>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(or,{}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Sessions Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Jn,{})}),s.jsx(er,{})]}),s.jsx(st,{})]}):s.jsx(on,{})}const rr=[1,2,3,4];function or(){const e=T(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="#9ece6a",n=4):e<150?(t="#e0af68",n=3):e<300?(t="#ff9e64",n=2):(t="#f7768e",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[rr.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}ye.createRoot(document.getElementById("root")).render(s.jsx(we.StrictMode,{children:s.jsx(rt,{children:s.jsx(nr,{})})}));