ai-cli-online 2.3.2 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,11 +17,14 @@ Ideal for **unstable networks** where SSH drops frequently, or as a **local stat
17
17
  ## Features
18
18
 
19
19
  - **Full Web Terminal** — xterm.js with WebGL rendering, binary protocol for ultra-low latency
20
- - **Session Persistence** — tmux keeps processes alive through disconnects; reconnect and resume instantly
20
+ - **Session Persistence** — tmux keeps processes alive through disconnects; fixed socket path ensures auto-reconnect even after server restarts
21
21
  - **Multi-Tab** — independent terminal groups with layout persistence across browser refreshes
22
22
  - **Split Panes** — horizontal / vertical splits, arbitrarily nested
23
23
  - **Document Browser** — view Markdown, HTML, and PDF files alongside your terminal; file picker shows file sizes
24
- - **Editor Panel** — multi-line editing with server-side draft persistence (SQLite)
24
+ - **Mermaid Diagrams** — Gantt charts, flowcharts, and other Mermaid diagrams render inline with dark theme; CDN fallback for reliability
25
+ - **Plan Annotations** — add, edit, and delete inline annotations on document content with persistent storage
26
+ - **Editor Panel** — multi-line editing with server-side draft persistence (SQLite), undo stack, and slash commands (`/history`, etc.)
27
+ - **Copy & Paste** — mouse selection auto-copies to clipboard; right-click pastes into terminal
25
28
  - **File Transfer** — upload files to CWD, browse and download via REST API
26
29
  - **Scroll History** — capture-pane scrollback viewer with ANSI color preservation
27
30
  - **Session Management** — sidebar to restore, delete, rename sessions, and close individual terminals (with confirmation)
package/README.zh-CN.md CHANGED
@@ -17,11 +17,14 @@
17
17
  ## 功能特性
18
18
 
19
19
  - **完整 Web 终端** — xterm.js + WebGL 渲染,二进制协议实现超低延迟
20
- - **会话持久化** — tmux 保证断网后进程存活,重连即恢复
20
+ - **会话持久化** — tmux 保证断网后进程存活;固定 socket 路径,服务重启后自动重连
21
21
  - **Tab 多标签页** — 独立终端分组,布局跨刷新持久化
22
22
  - **分屏布局** — 水平/垂直任意嵌套分割
23
23
  - **文档浏览器** — 终端旁查看 Markdown / HTML / PDF 文件
24
- - **编辑器面板**多行编辑 + 草稿服务端持久化 (SQLite)
24
+ - **Mermaid 图表** 甘特图、流程图等 Mermaid 图表暗色主题内联渲染,CDN 双源容错
25
+ - **Plan 批注** — 文档内容内联批注,支持新增/编辑/删除,持久化存储
26
+ - **编辑器面板** — 多行编辑 + 草稿服务端持久化 (SQLite) + undo 撤销栈 + 斜杠命令(`/history` 等)
27
+ - **复制粘贴** — 鼠标选中自动复制到剪贴板,右键粘贴到终端
25
28
  - **文件传输** — 上传文件到 CWD,浏览/下载通过 REST API
26
29
  - **滚动历史** — capture-pane 回看,保留 ANSI 颜色
27
30
  - **会话管理** — 侧边栏管理 session(恢复/删除/重命名)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online",
3
- "version": "2.3.2",
3
+ "version": "2.4.1",
4
4
  "description": "AI-Cli Online - Web Terminal for Claude Code via xterm.js + tmux",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -8,7 +8,7 @@ import rateLimit from 'express-rate-limit';
8
8
  import multer from 'multer';
9
9
  import { config } from 'dotenv';
10
10
  import { existsSync, readFileSync, createReadStream } from 'fs';
11
- import { copyFile, unlink, stat, mkdir, readFile } from 'fs/promises';
11
+ import { copyFile, unlink, stat, mkdir, readFile, writeFile } from 'fs/promises';
12
12
  import { join, dirname, basename, extname } from 'path';
13
13
  import { fileURLToPath } from 'url';
14
14
  import { createHash } from 'crypto';
@@ -56,7 +56,7 @@ async function main() {
56
56
  contentSecurityPolicy: {
57
57
  directives: {
58
58
  defaultSrc: ["'self'"],
59
- scriptSrc: ["'self'"],
59
+ scriptSrc: ["'self'", "https://cdn.jsdelivr.net", "https://unpkg.com"],
60
60
  styleSrc: ["'self'", "'unsafe-inline'"],
61
61
  imgSrc: ["'self'", "https:", "data:"],
62
62
  connectSrc: ["'self'", "wss:", "ws:"],
@@ -302,6 +302,33 @@ async function main() {
302
302
  res.json({ command: '' });
303
303
  }
304
304
  });
305
+ // --- Touch (create empty file) API ---
306
+ app.post('/api/sessions/:sessionId/touch', async (req, res) => {
307
+ const sessionName = resolveSession(req, res);
308
+ if (!sessionName)
309
+ return;
310
+ try {
311
+ const { name } = req.body;
312
+ if (!name || typeof name !== 'string' || name.includes('/') || name.includes('..')) {
313
+ res.status(400).json({ error: 'Invalid filename' });
314
+ return;
315
+ }
316
+ const cwd = await getCwd(sessionName);
317
+ const fullPath = join(cwd, name);
318
+ await writeFile(fullPath, '', { flag: 'wx' }); // create exclusively
319
+ res.json({ ok: true, path: fullPath });
320
+ }
321
+ catch (err) {
322
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'EEXIST') {
323
+ const cwd = await getCwd(sessionName).catch(() => '');
324
+ res.json({ ok: true, existed: true, path: cwd ? join(cwd, String(req.body.name)) : '' });
325
+ }
326
+ else {
327
+ console.error(`[api:touch] ${sessionName}:`, err);
328
+ res.status(500).json({ error: 'Failed to create file' });
329
+ }
330
+ }
331
+ });
305
332
  // --- Settings API ---
306
333
  /** Hash token for settings storage (same prefix as tmux session names) */
307
334
  function tokenHash(token) {
@@ -1,4 +1,5 @@
1
1
  import * as pty from 'node-pty';
2
+ import { TMUX_SOCKET_PATH } from './tmux.js';
2
3
  /**
3
4
  * Wraps node-pty to attach to a tmux session.
4
5
  * When the WebSocket disconnects, we kill only the PTY (detach from tmux),
@@ -21,7 +22,7 @@ export class PtySession {
21
22
  exitListeners = [];
22
23
  alive = true;
23
24
  constructor(sessionName, cols, rows) {
24
- this.proc = pty.spawn('tmux', ['attach-session', '-t', `=${sessionName}`], {
25
+ this.proc = pty.spawn('tmux', ['-S', TMUX_SOCKET_PATH, 'attach-session', '-t', `=${sessionName}`], {
25
26
  name: 'xterm-256color',
26
27
  cols,
27
28
  rows,
@@ -1,3 +1,4 @@
1
+ export declare const TMUX_SOCKET_PATH: string;
1
2
  export interface TmuxSessionInfo {
2
3
  sessionName: string;
3
4
  sessionId: string;
@@ -1,11 +1,26 @@
1
1
  import { execFile as execFileCb, execFileSync } from 'child_process';
2
2
  import { promisify } from 'util';
3
3
  import { createHash } from 'crypto';
4
+ import { mkdirSync } from 'fs';
5
+ import { join } from 'path';
4
6
  const _execFile = promisify(execFileCb);
5
7
  const EXEC_TIMEOUT = 5000; // 5s safety timeout for all tmux calls
6
- /** execFile wrapper with default timeout to prevent indefinite hangs */
7
- function execFile(file, args, options) {
8
- return _execFile(file, args, { timeout: EXEC_TIMEOUT, ...options });
8
+ // ---------------------------------------------------------------------------
9
+ // Stable tmux socket path — survives PrivateTmp remounts across service restarts.
10
+ // With KillMode=process, the tmux server daemon outlives the Node.js process,
11
+ // and this fixed socket path ensures the restarted service reconnects to it.
12
+ // ---------------------------------------------------------------------------
13
+ const TMUX_SOCKET_DIR = join(process.env.HOME || '/home/ubuntu', '.tmux-sockets');
14
+ export const TMUX_SOCKET_PATH = join(TMUX_SOCKET_DIR, 'ai-cli-online');
15
+ try {
16
+ mkdirSync(TMUX_SOCKET_DIR, { recursive: true, mode: 0o700 });
17
+ }
18
+ catch {
19
+ /* directory may already exist */
20
+ }
21
+ /** execFile wrapper: all tmux commands use the fixed socket via -S */
22
+ function tmuxExec(args, options) {
23
+ return _execFile('tmux', ['-S', TMUX_SOCKET_PATH, ...args], { timeout: EXEC_TIMEOUT, ...options });
9
24
  }
10
25
  /**
11
26
  * Generate a tmux session name from an auth token.
@@ -30,7 +45,7 @@ export function buildSessionName(token, sessionId) {
30
45
  /** Check if a tmux session exists */
31
46
  export async function hasSession(name) {
32
47
  try {
33
- await execFile('tmux', ['has-session', '-t', `=${name}`]);
48
+ await tmuxExec(['has-session', '-t', `=${name}`]);
34
49
  return true;
35
50
  }
36
51
  catch {
@@ -40,7 +55,7 @@ export async function hasSession(name) {
40
55
  /** Configure tmux session options for web terminal usage.
41
56
  * Note: set-option does NOT support the = exact-match prefix, so use bare name. */
42
57
  export async function configureSession(name) {
43
- await execFile('tmux', [
58
+ await tmuxExec([
44
59
  'set-option', '-t', name, 'history-limit', '50000', ';',
45
60
  'set-option', '-t', name, 'status', 'off', ';',
46
61
  'set-option', '-t', name, 'mouse', 'off',
@@ -48,7 +63,7 @@ export async function configureSession(name) {
48
63
  }
49
64
  /** Create a new tmux session (detached) */
50
65
  export async function createSession(name, cols, rows, cwd) {
51
- await execFile('tmux', [
66
+ await tmuxExec([
52
67
  'new-session',
53
68
  '-d',
54
69
  '-s', name,
@@ -64,7 +79,7 @@ export async function createSession(name, cols, rows, cwd) {
64
79
  */
65
80
  export async function captureScrollback(name) {
66
81
  try {
67
- const { stdout } = await execFile('tmux', [
82
+ const { stdout } = await tmuxExec([
68
83
  'capture-pane',
69
84
  '-t', `=${name}:`,
70
85
  '-p',
@@ -81,7 +96,7 @@ export async function captureScrollback(name) {
81
96
  /** Resize tmux window to match terminal dimensions */
82
97
  export async function resizeSession(name, cols, rows) {
83
98
  try {
84
- await execFile('tmux', [
99
+ await tmuxExec([
85
100
  'resize-window',
86
101
  '-t', `=${name}`,
87
102
  '-x', String(cols),
@@ -95,7 +110,7 @@ export async function resizeSession(name, cols, rows) {
95
110
  /** Kill a tmux session */
96
111
  export async function killSession(name) {
97
112
  try {
98
- await execFile('tmux', ['kill-session', '-t', `=${name}`]);
113
+ await tmuxExec(['kill-session', '-t', `=${name}`]);
99
114
  console.log(`[tmux] Killed session: ${name}`);
100
115
  }
101
116
  catch {
@@ -106,7 +121,7 @@ export async function killSession(name) {
106
121
  export async function listSessions(token) {
107
122
  const prefix = tokenToSessionName(token) + '-';
108
123
  try {
109
- const { stdout } = await execFile('tmux', [
124
+ const { stdout } = await tmuxExec([
110
125
  'list-sessions',
111
126
  '-F',
112
127
  '#{session_name}:#{session_created}',
@@ -136,7 +151,7 @@ export async function listSessions(token) {
136
151
  export async function cleanupStaleSessions(ttlHours) {
137
152
  const cutoff = Math.floor(Date.now() / 1000) - ttlHours * 3600;
138
153
  try {
139
- const { stdout } = await execFile('tmux', [
154
+ const { stdout } = await tmuxExec([
140
155
  'list-sessions',
141
156
  '-F',
142
157
  '#{session_name}:#{session_created}:#{session_attached}',
@@ -173,7 +188,7 @@ export async function cleanupStaleSessions(ttlHours) {
173
188
  /** 获取 tmux session 当前活动 pane 的工作目录 */
174
189
  export async function getCwd(sessionName) {
175
190
  // Use list-panes instead of display-message: display-message ignores the = exact-match prefix
176
- const { stdout } = await execFile('tmux', [
191
+ const { stdout } = await tmuxExec([
177
192
  'list-panes', '-t', `=${sessionName}`, '-F', '#{pane_current_path}',
178
193
  ], { encoding: 'utf-8' });
179
194
  return stdout.trim();
@@ -181,7 +196,7 @@ export async function getCwd(sessionName) {
181
196
  /** 获取 tmux pane 当前运行的命令名称 */
182
197
  export async function getPaneCommand(sessionName) {
183
198
  try {
184
- const { stdout } = await execFile('tmux', [
199
+ const { stdout } = await tmuxExec([
185
200
  'list-panes', '-t', `=${sessionName}`, '-F', '#{pane_current_command}',
186
201
  ], { encoding: 'utf-8' });
187
202
  return stdout.trim();
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-server",
3
- "version": "2.2.5",
3
+ "version": "2.4.0",
4
4
  "description": "CLI-Online Backend Server",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "@types/compression": "^1.8.1",
27
27
  "@types/express": "^4.17.21",
28
28
  "@types/multer": "^2.0.0",
29
- "@types/node": "^20.10.0",
29
+ "@types/node": "^20.19.33",
30
30
  "@types/ws": "^8.5.10",
31
31
  "tsx": "^4.7.0",
32
32
  "typescript": "^5.9.3"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-shared",
3
- "version": "2.2.5",
3
+ "version": "2.4.0",
4
4
  "description": "Shared types for CLI-Online",
5
5
  "type": "module",
6
6
  "main": "dist/types.js",
@@ -0,0 +1,33 @@
1
+ var on=Object.defineProperty;var sn=(e,t,n)=>t in e?on(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ct=(e,t,n)=>sn(e,typeof t!="symbol"?t+"":t,n);import{r as i,a as an,g as ln,R as nt}from"./react-vendor-BCIvbQoU.js";import{D as Dt,o as Ot,L as cn,x as At}from"./terminal-DnNpv9tw.js";import{d as rt,p as $t}from"./markdown-BERZKN_L.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();var Pt={exports:{}},$e={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var dn=i,un=Symbol.for("react.element"),fn=Symbol.for("react.fragment"),pn=Object.prototype.hasOwnProperty,mn=dn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,hn={key:!0,ref:!0,__self:!0,__source:!0};function _t(e,t,n){var r,o={},l=null,c=null;n!==void 0&&(l=""+n),t.key!==void 0&&(l=""+t.key),t.ref!==void 0&&(c=t.ref);for(r in t)pn.call(t,r)&&!hn.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:un,type:e,key:l,ref:c,props:o,_owner:mn.current}}$e.Fragment=fn;$e.jsx=_t;$e.jsxs=_t;Pt.exports=$e;var s=Pt.exports,qe={},dt=an;qe.createRoot=dt.createRoot,qe.hydrateRoot=dt.hydrateRoot;const xn={},ut=e=>{let t;const n=new Set,r=(f,m)=>{const p=typeof f=="function"?f(t):f;if(!Object.is(p,t)){const y=t;t=m??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(h=>h(t,y))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>u,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},u=t=e(r,o,a);return a},yn=e=>e?ut(e):ut;var Bt={exports:{}},Ft={},Ut={exports:{}},Wt={};/**
10
+ * @license React
11
+ * use-sync-external-store-shim.production.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var Ie=i;function bn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var gn=typeof Object.is=="function"?Object.is:bn,vn=Ie.useState,wn=Ie.useEffect,Sn=Ie.useLayoutEffect,kn=Ie.useDebugValue;function Cn(e,t){var n=t(),r=vn({inst:{value:n,getSnapshot:t}}),o=r[0].inst,l=r[1];return Sn(function(){o.value=n,o.getSnapshot=t,Fe(o)&&l({inst:o})},[e,n,t]),wn(function(){return Fe(o)&&l({inst:o}),e(function(){Fe(o)&&l({inst:o})})},[e]),kn(n),n}function Fe(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!gn(e,n)}catch{return!0}}function Tn(e,t){return t()}var In=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Tn:Cn;Wt.useSyncExternalStore=Ie.useSyncExternalStore!==void 0?Ie.useSyncExternalStore:In;Ut.exports=Wt;var En=Ut.exports;/**
18
+ * @license React
19
+ * use-sync-external-store-shim/with-selector.production.js
20
+ *
21
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
22
+ *
23
+ * This source code is licensed under the MIT license found in the
24
+ * LICENSE file in the root directory of this source tree.
25
+ */var Pe=i,jn=En;function Rn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var zn=typeof Object.is=="function"?Object.is:Rn,Nn=jn.useSyncExternalStore,Ln=Pe.useRef,Mn=Pe.useEffect,Dn=Pe.useMemo,On=Pe.useDebugValue;Ft.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var l=Ln(null);if(l.current===null){var c={hasValue:!1,value:null};l.current=c}else c=l.current;l=Dn(function(){function a(y){if(!u){if(u=!0,f=y,y=r(y),o!==void 0&&c.hasValue){var h=c.value;if(o(h,y))return m=h}return m=y}if(h=m,zn(f,y))return h;var g=r(y);return o!==void 0&&o(h,g)?(f=y,h):(f=y,m=g)}var u=!1,f,m,p=n===void 0?null:n;return[function(){return a(t())},p===null?void 0:function(){return a(p())}]},[t,n,r,o]);var d=Nn(e,l[0],l[1]);return Mn(function(){c.hasValue=!0,c.value=d},[d]),On(d),d};Bt.exports=Ft;var An=Bt.exports;const $n=ln(An),Ht={},{useDebugValue:Pn}=nt,{useSyncExternalStoreWithSelector:_n}=$n;let ft=!1;const Bn=e=>e;function Fn(e,t=Bn,n){(Ht?"production":void 0)!=="production"&&n&&!ft&&(ft=!0);const r=_n(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Pn(r),r}const pt=e=>{const t=typeof e=="function"?yn(e):e,n=(r,o)=>Fn(t,r,o);return Object.assign(n,t),n},Un=e=>e?pt(e):pt,Q="";function se(e){return{Authorization:`Bearer ${e}`}}async function Wn(e){try{const t=await fetch(`${Q}/api/settings/font-size`,{headers:se(e)});return t.ok?(await t.json()).fontSize:14}catch{return 14}}async function Hn(e,t){try{await fetch(`${Q}/api/settings/font-size`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({fontSize:t})})}catch{}}async function Kn(e){try{const t=await fetch(`${Q}/api/settings/tabs-layout`,{headers:se(e)});return t.ok?(await t.json()).layout:null}catch{return null}}async function Vn(e,t){try{await fetch(`${Q}/api/settings/tabs-layout`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({layout:t})})}catch{}}function mt(e,t){try{const n=`${Q}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const Oe="ai-cli-online-tabs",ht="ai-cli-online-layout",xt="ai-cli-online-session-names";function Ae(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let c=0;c<e.children.length;c++){const d=Ae(e.children[c],t);d!==null&&(n.push(d),r.push(e.sizes[c]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((c,d)=>c+d,0),l=r.map(c=>c/o*100);return{...e,children:n,sizes:l}}function Kt(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(l=>Kt(l,t,n,r,o))}}function Vt(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>Vt(r,t,n))}}function Ue(e){return e.tabs.find(t=>t.id===e.activeTabId)}function be(e,t,n){return e.map(r=>r.id===t?n(r):r)}function oe(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(Oe,JSON.stringify(t))}catch{}Gn(t)}let Le=null,Me=null,Se=null,Re=null;function Gn(e){Re=e,Se&&clearTimeout(Se),Se=setTimeout(()=>{Se=null,Re=null;const t=M.getState().token;t&&Vn(t,e)},2e3)}function Jn(e){Le&&clearTimeout(Le),Le=setTimeout(()=>{Le=null,oe(e)},500)}function Yn(){try{const e=localStorage.getItem(Oe);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(ht);if(e){const t=JSON.parse(e);let n="Default";try{const l=localStorage.getItem(xt);if(l){const c=JSON.parse(l),d=Object.values(c)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Oe,JSON.stringify(o))}catch{}return localStorage.removeItem(ht),localStorage.removeItem(xt),o}}catch{}return null}function te(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function qn(e,t){const n=new Set(t.map(c=>c.sessionId)),r=[];for(const c of e.tabs){if(c.status!=="open"){const u=c.terminalIds.filter(f=>n.has(f));if(u.length>0){let f=c.layout;for(const m of c.terminalIds)!n.has(m)&&f&&(f=Ae(f,m));r.push({...c,terminalIds:u,layout:f})}continue}const d=c.terminalIds.filter(u=>n.has(u));if(d.length===0)continue;let a=c.layout;for(const u of c.terminalIds)!n.has(u)&&a&&(a=Ae(a,u));r.push({...c,terminalIds:d,layout:a})}if(r.filter(c=>c.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(c=>c.id===o&&c.status==="open")){const c=r.find(d=>d.status==="open");o=(c==null?void 0:c.id)||""}return{...e,activeTabId:o,tabs:r}}typeof window<"u"&&window.addEventListener("beforeunload",()=>{var t,n;const e=(n=(t=M==null?void 0:M.getState)==null?void 0:t.call(M))==null?void 0:n.token;if(e)if(Re)Se&&(clearTimeout(Se),Se=null),mt(e,Re),Re=null;else{const r=M.getState();r.tabs.length>0&&mt(e,te(r))}});function yt(e,t){const n=e.tabs.find(u=>u.terminalIds.includes(t));if(!n){const{[t]:u,...f}=e.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(u=>u!==t),o=n.layout?Ae(n.layout,t):null,l=be(e.tabs,n.id,u=>({...u,terminalIds:r,layout:o})),{[t]:c,...d}=e.terminalsMap,a={terminalsMap:d,tabs:l};return n.id===e.activeTabId&&(a.terminalIds=r,a.layout=o),a}const M=Un((e,t)=>({token:null,tabsLoading:!1,setToken:n=>{var r;if(n){try{localStorage.setItem("ai-cli-online-token",n)}catch{}Wn(n).then(l=>{t().token===n&&e({fontSize:l})});const o=Yn();if(o&&o.tabs.length>0){const l={};for(const a of o.tabs)if(a.status==="open")for(const u of a.terminalIds)l[u]={id:u,connected:!1,sessionResumed:!1,error:null,panelMode:((r=a.panelModes)==null?void 0:r[u])||"none"};const c=o.tabs.find(a=>a.id===o.activeTabId&&a.status==="open")||o.tabs.find(a=>a.status==="open"),d=(c==null?void 0:c.id)||"";e({token:n,tabsLoading:!0,terminalsMap:l,tabs:o.tabs,activeTabId:d,nextId:o.nextId,nextSplitId:o.nextSplitId,nextTabId:o.nextTabId,terminalIds:(c==null?void 0:c.terminalIds)||[],layout:(c==null?void 0:c.layout)||null})}else e({token:n,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Xn(n,o);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem(Oe),e({token:n,tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null})},terminalsMap:{},terminalIds:[],layout:null,nextId:1,nextSplitId:1,tabs:[],activeTabId:"",nextTabId:1,addTab:n=>{const r=t(),o=`tab${r.nextTabId}`,l=`t${r.nextId}`,c={id:l,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},d={type:"leaf",terminalId:l},a={id:o,name:n||`Tab ${r.nextTabId}`,status:"open",terminalIds:[l],layout:d,createdAt:Date.now()};return e({tabs:[...r.tabs,a],activeTabId:o,nextTabId:r.nextTabId+1,nextId:r.nextId+1,terminalsMap:{...r.terminalsMap,[l]:c},terminalIds:a.terminalIds,layout:a.layout}),oe(te(t())),o},switchTab:n=>{const o=t().tabs.find(l=>l.id===n);!o||o.status!=="open"||(e({activeTabId:n,terminalIds:o.terminalIds,layout:o.layout}),oe(te(t())))},closeTab:n=>{const r=t(),o=r.tabs.find(m=>m.id===n);if(!o||o.status!=="open"||r.tabs.filter(m=>m.status==="open").length<=1)return;const c={...r.terminalsMap};for(const m of o.terminalIds)delete c[m];const d=be(r.tabs,n,m=>({...m,status:"closed"}));let a=r.activeTabId,u=r.terminalIds,f=r.layout;if(r.activeTabId===n){const m=r.tabs.findIndex(h=>h.id===n),p=d.filter(h=>h.status==="open"),y=p.find(h=>d.findIndex(k=>k.id===h.id)>m)||p[p.length-1];y&&(a=y.id,u=y.terminalIds,f=y.layout)}e({tabs:d,activeTabId:a,terminalsMap:c,terminalIds:u,layout:f}),oe(te(t()))},reopenTab:n=>{var d;const r=t(),o=r.tabs.find(a=>a.id===n);if(!o||o.status!=="closed")return;const l={...r.terminalsMap};for(const a of o.terminalIds)l[a]={id:a,connected:!1,sessionResumed:!1,error:null,panelMode:((d=o.panelModes)==null?void 0:d[a])||"none"};const c=be(r.tabs,n,a=>({...a,status:"open"}));e({tabs:c,activeTabId:n,terminalsMap:l,terminalIds:o.terminalIds,layout:o.layout}),oe(te(t()))},deleteTab:async n=>{const r=t(),o=r.tabs.find(y=>y.id===n);if(!o)return;const l=r.token;l&&await Promise.all(o.terminalIds.map(y=>fetch(`${Q}/api/sessions/${encodeURIComponent(y)}`,{method:"DELETE",headers:se(l)}).catch(()=>{})));const c=t(),d=c.tabs.find(y=>y.id===n);if(!d)return;const a={...c.terminalsMap};for(const y of d.terminalIds)delete a[y];const u=c.tabs.filter(y=>y.id!==n);let f=c.activeTabId,m=c.terminalIds,p=c.layout;if(c.activeTabId===n){const y=u.find(h=>h.status==="open");y?(f=y.id,m=y.terminalIds,p=y.layout):(f="",m=[],p=null)}e({tabs:u,activeTabId:f,terminalsMap:a,terminalIds:m,layout:p}),oe(te(t())),setTimeout(()=>t().fetchSessions(),500)},renameTab:(n,r)=>{const o=be(t().tabs,n,l=>({...l,name:r}));e({tabs:o}),oe(te(t()))},addTerminal:(n,r)=>{const o=t();if(r&&o.terminalsMap[r])return r;const l=Ue(o);if(!l){const O=`tab${o.nextTabId}`,D=r||`t${o.nextId}`;let R=o.nextId;const j=D.match(/^t(\d+)$/);j&&(R=Math.max(R,parseInt(j[1],10)+1));const v=r?R:R+1,x={id:D,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},z={type:"leaf",terminalId:D},A={id:O,name:`Tab ${o.nextTabId}`,status:"open",terminalIds:[D],layout:z,createdAt:Date.now()};return e({tabs:[...o.tabs,A],activeTabId:O,nextTabId:o.nextTabId+1,nextId:v,terminalsMap:{...o.terminalsMap,[D]:x},terminalIds:[D],layout:z}),oe(te(t())),D}const{nextId:c,nextSplitId:d,terminalsMap:a}=o,{terminalIds:u,layout:f}=l,m=r||`t${c}`;let p=c;const y=m.match(/^t(\d+)$/);y&&(p=Math.max(p,parseInt(y[1],10)+1));const h={id:m,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},g={type:"leaf",terminalId:m};let k,T=d;if(!f)k=g;else if(f.type==="leaf"){const O=n||"horizontal";k={id:`s${T}`,type:"split",direction:O,children:[f,g],sizes:[50,50]},T++}else if(f.direction===(n||"horizontal")){const D=100/(f.children.length+1),R=(100-D)/100,j=[...f.sizes.map(v=>v*R),D];k={...f,children:[...f.children,g],sizes:j}}else{const O=n||"horizontal";k={id:`s${T}`,type:"split",direction:O,children:[f,g],sizes:[50,50]},T++}const C=[...u,m],S=r?p:p+1,w=be(o.tabs,l.id,O=>({...O,terminalIds:C,layout:k}));return e({terminalsMap:{...a,[m]:h},terminalIds:C,layout:k,tabs:w,nextId:S,nextSplitId:T}),oe(te(t())),m},splitTerminal:(n,r)=>{const o=t(),l=Ue(o);if(!l||!l.layout)return"";const{nextId:c,nextSplitId:d,terminalsMap:a}=o,u=`t${c}`,f={id:u,connected:!1,sessionResumed:!1,error:null,panelMode:"none"},m={type:"leaf",terminalId:u},p=`s${d}`,y=Kt(l.layout,n,r,m,p),h=[...l.terminalIds,u],g=c+1,k=d+1,T=be(o.tabs,l.id,C=>({...C,terminalIds:h,layout:y}));return e({terminalsMap:{...a,[u]:f},terminalIds:h,layout:y,tabs:T,nextId:g,nextSplitId:k}),oe(te(t())),u},removeTerminal:n=>{const r=yt(t(),n);r&&(e(r),oe(te(t())))},setTerminalConnected:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.connected===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,connected:r}}}})},setTerminalResumed:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.sessionResumed===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,sessionResumed:r}}}})},setTerminalError:(n,r)=>{e(o=>{const l=o.terminalsMap[n];return!l||l.error===r?o:{terminalsMap:{...o.terminalsMap,[n]:{...l,error:r}}}})},setTerminalPanelMode:(n,r)=>{const o=t(),l=o.terminalsMap[n];if(!l||l.panelMode===r)return;const c={...o.terminalsMap,[n]:{...l,panelMode:r}},d=o.tabs.find(u=>u.terminalIds.includes(n));let a=o.tabs;if(d){const u={...d.panelModes,[n]:r};a=be(o.tabs,d.id,f=>({...f,panelModes:u}))}e({terminalsMap:c,tabs:a}),oe(te(t()))},setSplitSizes:(n,r)=>{const o=t(),l=Ue(o);if(!l||!l.layout)return;const c=Vt(l.layout,n,r),d=be(o.tabs,l.id,a=>({...a,layout:c}));e({layout:c,tabs:d}),Jn(te(t()))},fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),Me&&clearTimeout(Me),Me=setTimeout(()=>{Me=null;const o=t().token;o&&Hn(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${Q}/api/sessions`,{headers:se(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}},killServerSession:async n=>{const r=t().token;if(!r)return;try{await fetch(`${Q}/api/sessions/${encodeURIComponent(n)}`,{method:"DELETE",headers:se(r)})}catch{}const o=yt(t(),n);o&&(e(o),oe(te(t()))),setTimeout(()=>t().fetchSessions(),500)}}));async function Xn(e,t){var o,l;const{setState:n,getState:r}=M;try{const[c,d]=await Promise.all([Kn(e),fetch(`${Q}/api/sessions`,{headers:se(e)}).then(h=>h.ok?h.json():[]).catch(()=>[])]);if(r().token!==e)return;const a=c&&((o=c.tabs)==null?void 0:o.length)>0?c:t;if(!a||a.tabs.length===0){n({tabsLoading:!1});return}const u=qn(a,d);if(!u){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:a.nextId,nextSplitId:a.nextSplitId,nextTabId:a.nextTabId,terminalIds:[],layout:null});return}const f=r().terminalsMap,m={};for(const h of u.tabs)if(h.status==="open")for(const g of h.terminalIds)m[g]=f[g]||{id:g,connected:!1,sessionResumed:!1,error:null,panelMode:((l=h.panelModes)==null?void 0:l[g])||"none"};const p=u.tabs.find(h=>h.id===u.activeTabId&&h.status==="open")||u.tabs.find(h=>h.status==="open"),y=(p==null?void 0:p.id)||"";n({tabsLoading:!1,terminalsMap:m,tabs:u.tabs,activeTabId:y,nextId:u.nextId,nextSplitId:u.nextSplitId,nextTabId:u.nextTabId,terminalIds:(p==null?void 0:p.terminalIds)||[],layout:(p==null?void 0:p.layout)||null}),oe(te(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function Zn(){const[e,t]=i.useState(""),n=M(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, #1a1b26 70%)"},children:s.jsxs("div",{className:"login-card",style:{backgroundColor:"#24283b",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid #292e42"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, #7aa2f7 0%, #bb9af7 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"#1a1b26",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"#c0caf5",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"#565f89",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"#7aa2f7",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"#1a1b26",color:"#c0caf5",border:"1px solid #292e42",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, #7aa2f7 0%, #7dcfff 100%)":"#292e42",color:e.trim()?"#1a1b26":"#565f89",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"#414868",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"#1a1b26",padding:"2px 6px",borderRadius:"4px",border:"1px solid #292e42",fontSize:"11px"},children:"server/.env"})]})})]})})}const _e=new Map;function Qn(e,t,n){_e.set(e,{onChunk:t,onControl:n})}function er(e){_e.delete(e)}function tr(e,t){var n;(n=_e.get(e))==null||n.onChunk(t)}function nr(e,t){var n;(n=_e.get(e))==null||n.onControl(t)}const rr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,De=500,or=8e3,sr=1e4,bt=4e3,ir=5e3,ar=10,lr=64*1024,cr=1,gt=2,dr=3,ur=4,fr=5,pr=new TextDecoder,mr=new TextEncoder;function vt(e,t){const n=mr.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function hr(e,t,n){const r=i.useRef(null),o=i.useRef(De),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),a=i.useRef(null),u=i.useRef(!1),f=i.useRef(n),m=i.useRef(!1),p=i.useRef(0),y=i.useRef(!0),h=i.useRef(!navigator.onLine),g=i.useRef(""),k=i.useRef(null),T=i.useRef("");f.current=n;const C=i.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null),d.current&&(clearTimeout(d.current),d.current=null),l.current&&(clearTimeout(l.current),l.current=null),a.current&&(clearTimeout(a.current),a.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),S=i.useCallback(()=>{const{token:v,setTerminalError:x}=M.getState();if(!v||u.current)return;if(r.current){const L=r.current.readyState;if(L===WebSocket.OPEN||L===WebSocket.CONNECTING)return}m.current=!1;const z=`${rr}?sessionId=${encodeURIComponent(t)}`,A=new WebSocket(z);A.binaryType="arraybuffer",a.current=window.setTimeout(()=>{A.readyState===WebSocket.CONNECTING&&A.close()},ir);const P=()=>{A.readyState===WebSocket.OPEN&&(p.current=performance.now(),A.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{p.current>0&&(p.current=0,A.close())},bt))};A.onopen=()=>{a.current&&(clearTimeout(a.current),a.current=null),A.send(JSON.stringify({type:"auth",token:v})),x(t,null),o.current=De,y.current=!0},A.onclose=L=>{const{setTerminalConnected:F,setTerminalError:H,setToken:G}=M.getState();if(F(t,!1),C(),m.current)return;if(L.code===4001){u.current=!0,H(t,"Authentication failed"),G(null),localStorage.removeItem("ai-cli-online-token");return}if(L.code===4002)return;if(L.code===4005){H(t,"Connection limit reached");return}if(!navigator.onLine){h.current=!0;return}if(y.current){y.current=!1,l.current=window.setTimeout(()=>S(),50);return}const J=o.current;o.current=Math.min(J*2,or);const V=Math.round(J*(.5+Math.random()));l.current=window.setTimeout(()=>{S()},V)},A.onerror=()=>{},A.onmessage=L=>{var F;try{const H=e.current;if(L.data instanceof ArrayBuffer){const J=new Uint8Array(L.data);if(J.length<1)return;const V=J[0],Y=J.subarray(1);switch(V){case cr:H==null||H.write(Y);break;case dr:H==null||H.write(Y);break;case ur:{(F=f.current)==null||F.call(f,pr.decode(Y));break}case fr:{tr(t,Y);break}}return}const G=JSON.parse(L.data);switch(G.type){case"connected":{const J=M.getState();J.setTerminalConnected(t,!0),J.setTerminalResumed(t,G.resumed);const V=e.current;V&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"resize",cols:V.cols,rows:V.rows})),T.current&&(A.send(vt(gt,T.current)),T.current=""),P(),c.current=window.setInterval(P,sr);break}case"error":M.getState().setTerminalError(t,G.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),p.current>0){const J=Math.round(performance.now()-p.current),V=M.getState();(V.terminalIds.length===0||V.terminalIds[0]===t)&&V.setLatency(J),p.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":nr(t,G);break}}catch{}},r.current=A},[t,e,C]),w=i.useCallback(v=>{const x=r.current;if(!x||x.readyState!==WebSocket.OPEN){T.current.length<lr&&(T.current+=v);return}g.current+=v,k.current||(k.current=window.setTimeout(()=>{const z=g.current;g.current="",k.current=null,z&&x.readyState===WebSocket.OPEN&&x.send(vt(gt,z))},ar))},[]),O=i.useCallback((v,x)=>{var z;((z=r.current)==null?void 0:z.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:v,rows:x}))},[]),D=i.useCallback(()=>{var v;((v=r.current)==null?void 0:v.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),R=i.useCallback(v=>{var x;((x=r.current)==null?void 0:x.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:v}))},[]),j=i.useCallback(()=>{var v;((v=r.current)==null?void 0:v.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return i.useEffect(()=>{M.getState().token&&(u.current=!1,S());const x=()=>{h.current=!1,o.current=De,y.current=!0;const P=r.current;(!P||P.readyState===WebSocket.CLOSED||P.readyState===WebSocket.CLOSING)&&S()},z=()=>{h.current=!0},A=()=>{if(document.visibilityState!=="visible")return;const P=r.current;if(!P||P.readyState!==WebSocket.OPEN){!h.current&&!m.current&&(o.current=De,y.current=!0,S());return}p.current=performance.now(),P.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{p.current>0&&(p.current=0,P.close())},bt)};return window.addEventListener("online",x),window.addEventListener("offline",z),document.addEventListener("visibilitychange",A),()=>{m.current=!0,C(),window.removeEventListener("online",x),window.removeEventListener("offline",z),document.removeEventListener("visibilitychange",A),r.current&&(r.current.close(),r.current=null)}},[S,C,t]),{sendInput:w,sendResize:O,requestScrollback:D,requestFileStream:R,cancelFileStream:j}}const Gt={background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",selectionBackground:"#33467c",black:"#15161e",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#414868",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},Jt="'JetBrains Mono', Menlo, Monaco, 'Courier New', monospace",xr=i.forwardRef(function({sessionId:t},n){const r=i.useRef(null),o=i.useRef(null),l=i.useRef(null),[c,d]=i.useState(!1),[a,u]=i.useState(""),f=M(S=>S.fontSize),m=i.useCallback(S=>{u(S),d(!0)},[]),{sendInput:p,sendResize:y,requestScrollback:h,requestFileStream:g,cancelFileStream:k}=hr(o,t,m);i.useImperativeHandle(n,()=>({sendInput:p,requestFileStream:g,cancelFileStream:k}),[p,g,k]);const T=i.useRef(p),C=i.useRef(y);return T.current=p,C.current=y,i.useEffect(()=>{if(!r.current)return;let S=!1,w=null,O=null,D=null,R=null;if(S||!r.current)return;const j=new Dt({cursorBlink:!0,scrollback:1e4,fontSize:M.getState().fontSize,fontFamily:Jt,theme:Gt,allowProposedApi:!0}),v=new Ot;j.loadAddon(v),j.loadAddon(new cn((L,F)=>{window.open(F,"_blank","noopener,noreferrer")})),j.open(r.current);try{const L=new At;L.onContextLoss(()=>{L.dispose()}),j.loadAddon(L)}catch{}o.current=j,l.current=v,j.onSelectionChange(()=>{const L=j.getSelection();L&&navigator.clipboard.writeText(L).catch(()=>{})});const x=j.element,z=L=>{L.preventDefault(),navigator.clipboard.readText().then(F=>{F&&T.current(F)}).catch(()=>{})};x&&x.addEventListener("contextmenu",z);const A=()=>{try{const L=r.current;if(L&&L.clientWidth>0&&L.clientHeight>0)return v.fit(),C.current(j.cols,j.rows),!0}catch{}return!1};requestAnimationFrame(()=>A());let P=0;return w=setInterval(()=>{P++,(A()||P>=10)&&(clearInterval(w),w=null)},100),document.fonts.ready.then(()=>{if(!S)try{v.fit(),C.current(j.cols,j.rows)}catch{}}),j.onData(L=>{T.current(L)}),R=new ResizeObserver(()=>{O||(O=requestAnimationFrame(()=>{O=null;try{v.fit(),D&&clearTimeout(D),D=setTimeout(()=>{D=null,C.current(j.cols,j.rows)},50)}catch{}}))}),R.observe(r.current),()=>{S=!0,w&&clearInterval(w),O&&cancelAnimationFrame(O),D&&clearTimeout(D),R&&R.disconnect(),x&&x.removeEventListener("contextmenu",z),o.current&&(o.current.dispose(),o.current=null),l.current=null}},[t]),i.useEffect(()=>{const S=o.current,w=l.current;if(!(!S||!w)&&S.options.fontSize!==f){S.options.fontSize=f;try{w.fit()}catch{}C.current(S.cols,S.rows)}},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"#1a1b26",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:S=>{S.currentTarget.blur(),c?(d(!1),u("")):h()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:c?"#7aa2f7":"rgba(65, 72, 104, 0.7)",color:"#c0caf5",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:S=>{S.currentTarget.style.opacity="1"},onMouseLeave:S=>{S.currentTarget.style.opacity="0.8"},children:c?"✕":s.jsx("span",{style:{fontSize:16},children:"👁"})}),c&&s.jsx(yr,{data:a,onClose:()=>{d(!1),u("")}})]})});function yr({data:e,onClose:t}){const n=i.useRef(null),r=i.useRef(t);r.current=t;const o=M(a=>a.fontSize),l=i.useRef(null),c=i.useRef(null);i.useEffect(()=>{if(!n.current)return;const a=new Dt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:Jt,theme:Gt});l.current=a;const u=new Ot;c.current=u,a.loadAddon(u),a.open(n.current);try{const g=new At;g.onContextLoss(()=>g.dispose()),a.loadAddon(g)}catch{}a.onSelectionChange(()=>{const g=a.getSelection();g&&navigator.clipboard.writeText(g).catch(()=>{})}),a.attachCustomKeyEventHandler(g=>(g.key==="Escape"&&r.current(),!1)),a.write(e);let f=null;const m=()=>{const g=n.current;if(!g||g.clientWidth<=0||g.clientHeight<=0)return!1;try{return u.fit(),a.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!m()){let g=0;f=setInterval(()=>{g++,(m()||g>=30)&&(clearInterval(f),f=null)},50)}});let p=null;const y=new ResizeObserver(()=>{p||(p=requestAnimationFrame(()=>{p=null,m()}))});y.observe(n.current);const h=g=>{g.key==="Escape"&&r.current()};return document.addEventListener("keydown",h),()=>{f&&clearInterval(f),p&&cancelAnimationFrame(p),document.removeEventListener("keydown",h),y.disconnect(),a.dispose(),l.current=null,c.current=null}},[e]),i.useEffect(()=>{var a;if(l.current){l.current.options.fontSize=o;try{(a=c.current)==null||a.fit()}catch{}}},[o]);const d=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26"},children:[s.jsx("div",{style:{height:d,boxSizing:"border-box",padding:"0 12px",background:"#24283b",color:"#7aa2f7",fontSize:12,borderBottom:"1px solid #414868",display:"flex",alignItems:"center"},children:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{position:"absolute",top:d,left:0,right:0,bottom:0,overflow:"hidden"}})]})}async function Te(e,t,n){const r=n?`?path=${encodeURIComponent(n)}`:"",o=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/files${r}`,{headers:se(e)});if(!o.ok)throw new Error("Failed to list files");return o.json()}function br(e,t,n,r){return new Promise((o,l)=>{const c=new FormData;for(const a of n)c.append("files",a);const d=new XMLHttpRequest;d.open("POST",`${Q}/api/sessions/${encodeURIComponent(t)}/upload`),d.setRequestHeader("Authorization",`Bearer ${e}`),d.upload.addEventListener("progress",a=>{a.lengthComputable&&r&&r(Math.round(a.loaded/a.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?o():l(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>l(new Error("Upload network error"))),d.addEventListener("abort",()=>l(new Error("Upload aborted"))),d.send(c)})}async function gr(e,t){const n=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/cwd`,{headers:se(e)});if(!n.ok)throw new Error("Failed to fetch cwd");return(await n.json()).cwd}async function vr(e,t,n){const r=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/touch`,{method:"POST",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error("Failed to create file");return r.json()}async function wr(e,t,n){const r=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/download?path=${encodeURIComponent(n)}`,{headers:se(e)});if(!r.ok)throw new Error("Download failed");const o=await r.blob(),l=URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=n.split("/").pop()||"download",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l)}function ot({sessionId:e,onClose:t,filter:n,pollCwd:r}){const o=M(S=>S.token),[l,c]=i.useState(""),[d,a]=i.useState([]),[u,f]=i.useState(!0),[m,p]=i.useState(null),y=i.useRef(""),h=i.useCallback(async S=>{if(o){f(!0),p(null);try{const w=await Te(o,e,S);S||(y.current=w.cwd),c(w.cwd),a(n?n(w.files):w.files)}catch(w){p(w instanceof Error?w.message:"Failed to load files")}finally{f(!1)}}},[o,e,n]);i.useEffect(()=>{h()},[h]),i.useEffect(()=>{if(!r||!o)return;let S=!1;const w=setInterval(async()=>{if(!S)try{const O=await gr(o,e);if(S)return;if(O!==y.current){y.current=O;const D=await Te(o,e);if(S)return;c(D.cwd),a(n?n(D.files):D.files)}}catch{}},r);return()=>{S=!0,clearInterval(w)}},[r,o,e,n]);const g=i.useRef(t);g.current=t,i.useEffect(()=>{const S=w=>{w.key==="Escape"&&g.current()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[]);const k=i.useCallback(S=>{h(l+"/"+S)},[h,l]),T=i.useCallback(()=>{const S=l.replace(/\/[^/]+$/,"")||"/";h(S)},[h,l]),C=i.useCallback(()=>{h(l)},[h,l]);return{cwd:l,files:d,loading:u,error:m,setError:p,handleNavigate:k,handleGoUp:T,handleRefresh:C}}function st(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Yt(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function qt(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function it({cwd:e,onGoUp:t,onRefresh:n,onClose:r}){return s.jsxs("div",{style:{padding:"6px 12px",background:"#24283b",borderBottom:"1px solid #414868",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[s.jsx("button",{onClick:t,style:{background:"none",border:"1px solid #414868",color:"#7aa2f7",borderRadius:3,padding:"1px 8px",fontSize:12,cursor:"pointer",flexShrink:0},title:"Go to parent directory",children:".."}),s.jsx("span",{style:{color:"#7aa2f7",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e||"..."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[s.jsx("button",{onClick:n,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Refresh",children:"↻"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:"#565f89",fontSize:14,cursor:"pointer",padding:"0 4px"},title:"Close (ESC)",children:"✕"})]})]})}function at({loading:e,error:t,empty:n,emptyText:r="Empty directory"}){return e?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading..."}):t?s.jsx("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:t}):n?s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:r}):null}function Sr({sessionId:e,onClose:t}){const n=M(h=>h.token),{cwd:r,files:o,loading:l,error:c,setError:d,handleNavigate:a,handleGoUp:u,handleRefresh:f}=ot({sessionId:e,onClose:t}),[m,p]=i.useState(null),y=async h=>{if(n){p(h);try{await wr(n,e,r+"/"+h)}catch(g){d(g instanceof Error?g.message:"Download failed")}finally{p(null)}}};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(it,{cwd:r,onGoUp:u,onRefresh:f,onClose:t}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(at,{loading:l,error:c,empty:o.length===0,emptyText:"Empty directory"}),!l&&!c&&o.map(h=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:h.type==="directory"?"pointer":"default",borderBottom:"1px solid #1e2030"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent"},onClick:()=>{h.type==="directory"&&a(h.name)},children:[h.type==="file"?s.jsx("button",{onClick:g=>{g.stopPropagation(),y(h.name)},disabled:m===h.name,style:{background:"none",border:"1px solid #414868",color:m===h.name?"#565f89":"#9ece6a",borderRadius:3,padding:"1px 8px",fontSize:11,cursor:m===h.name?"wait":"pointer",flexShrink:0,marginRight:6},children:m===h.name?"...":"↓"}):s.jsx("span",{style:{width:26,flexShrink:0,marginRight:6}}),s.jsx("span",{style:{width:20,flexShrink:0,color:h.type==="directory"?"#7aa2f7":"#565f89"},children:h.type==="directory"?"📁":"📄"}),s.jsx("span",{style:{flex:1,color:h.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.name}),s.jsx("span",{style:{width:80,textAlign:"right",color:"#565f89",fontSize:11,flexShrink:0},children:h.type==="file"?st(h.size):""})]},h.name))]})]})}let Ee=null;const kr=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"];function Cr(e){return e.initialize({startOnLoad:!1,theme:"dark",themeVariables:{primaryColor:"#7aa2f7",primaryTextColor:"#c0caf5",primaryBorderColor:"#414868",lineColor:"#565f89",secondaryColor:"#bb9af7",tertiaryColor:"#24283b",background:"#1a1b26",mainBkg:"#24283b",nodeBorder:"#414868",clusterBkg:"#1e2030",titleColor:"#c0caf5",edgeLabelBackground:"#1e2030",gridColor:"#292e42",doneTaskBkgColor:"#9ece6a",doneTaskBorderColor:"#73a942",activeTaskBkgColor:"#7aa2f7",activeTaskBorderColor:"#5d87d6",critBkgColor:"#f7768e",critBorderColor:"#d35d72",taskBkgColor:"#414868",taskBorderColor:"#565f89",taskTextColor:"#c0caf5",taskTextDarkColor:"#1a1b26",sectionBkgColor:"#1e2030",sectionBkgColor2:"#24283b",altSectionBkgColor:"#1e2030",todayLineColor:"#e0af68"},gantt:{titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800}}),e}function Tr(){return Ee||(Ee=(async()=>{for(const e of kr)try{const t=await import(e);return Cr(t.default)}catch{}throw Ee=null,new Error("All mermaid CDN sources failed")})(),Ee)}let Ir=0;function Xt(e,t){i.useEffect(()=>{const n=e.current;if(!n)return;const r=n.querySelectorAll("code.language-mermaid, code.language-gantt");if(r.length===0)return;let o=!1;return(async()=>{let l;try{l=await Tr()}catch{if(o)return;for(const d of r){const a=d.parentElement;if(!a||a.tagName!=="PRE")continue;a.classList.add("mermaid-error");const u=document.createElement("div");u.className="mermaid-error__msg",u.textContent="Failed to load Mermaid library",a.appendChild(u)}return}if(!o)for(const c of r){if(o)break;const d=c.parentElement;if(!d||d.tagName!=="PRE")continue;const a=c.textContent||"";if(!a.trim())continue;const u=`mermaid-${++Ir}`;try{const{svg:f}=await l.render(u,a);if(o)break;const m=document.createElement("div");m.className="mermaid-diagram",m.innerHTML=f,d.replaceWith(m)}catch{if(o)break;d.classList.add("mermaid-error");const f=document.createElement("div");f.className="mermaid-error__msg",f.textContent="Mermaid syntax error",d.appendChild(f)}}})(),()=>{o=!0}},[t])}function Er({content:e}){const t=M(o=>o.fontSize),n=i.useRef(null),r=i.useMemo(()=>{if(!e)return"";const o=rt.parse(e,{async:!1});return $t.sanitize(o,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})},[e]);return Xt(n,r),e?s.jsx("div",{ref:n,className:"md-preview",style:{height:"100%",overflowY:"auto",userSelect:"text",padding:"12px 16px",fontSize:`${t}px`},dangerouslySetInnerHTML:{__html:r}}):s.jsx("div",{className:"md-preview",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#414868",fontStyle:"italic",fontSize:"13px"},children:"Waiting for plan output..."})}async function jr(e,t){const n=await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/draft`,{headers:se(e)});return n.ok?(await n.json()).content??"":""}async function wt(e,t,n){await fetch(`${Q}/api/sessions/${encodeURIComponent(t)}/draft`,{method:"PUT",headers:{...se(e),"Content-Type":"application/json"},body:JSON.stringify({content:n})})}const Rr=50;function Xe(){const e=i.useRef([]),t=i.useCallback(o=>{e.current.push(o),e.current.length>Rr&&e.current.shift()},[]),n=i.useCallback(()=>e.current.pop(),[]),r=i.useCallback(()=>{e.current=[]},[]);return i.useMemo(()=>({pushUndo:t,popUndo:n,clearUndo:r}),[t,n,r])}function Ze(e,t,n){e.preventDefault();const r=e.currentTarget,o=r.selectionStart,l=r.selectionEnd,c=r.value;n==null||n(c);const d=c.slice(0,o)+" "+c.slice(l);t(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function Qe(e,t,n){const r=t();return r!==void 0?(e.preventDefault(),n(r),!0):!1}function et(e,t=10){var n;return Math.min(t,Math.max(1,(((n=e.match(/\n/g))==null?void 0:n.length)??0)+1))}const lt="chat-history",St=50;function Zt(){try{const e=localStorage.getItem(lt);return e?JSON.parse(e):[]}catch{return[]}}function zr(e){const n=Zt().filter(r=>r.text!==e);n.unshift({text:e,ts:Date.now()}),n.length>St&&(n.length=St),localStorage.setItem(lt,JSON.stringify(n))}const kt=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],Nr=i.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},l){const c=M(b=>b.fontSize),[d,a]=i.useState(""),u=i.useRef(null),f=i.useRef(void 0),m=i.useRef(!1),{pushUndo:p,popUndo:y}=Xe(),h=i.useRef(d);h.current=d;const g=i.useCallback(()=>p(h.current),[p]),[k,T]=i.useState(!1),[C,S]=i.useState(""),[w,O]=i.useState(0),[D,R]=i.useState(!1),[j,v]=i.useState([]),[x,z]=i.useState(0),[A,P]=i.useState(""),L=i.useRef(null),F=i.useMemo(()=>{if(!A)return j;const b=A.toLowerCase();return j.filter(E=>E.text.toLowerCase().includes(b))},[j,A]),[H,G]=i.useState(!1),[J,V]=i.useState(""),[Y,me]=i.useState(""),[he,ee]=i.useState(0),[de,xe]=i.useState([]),[ue,ye]=i.useState(!1),ae=i.useRef(""),fe=i.useRef(null),N=i.useMemo(()=>{if(!C)return kt;const b=C.toLowerCase();return kt.filter(E=>E.cmd.toLowerCase().includes(b)||E.desc.toLowerCase().includes(b))},[C]),I=i.useMemo(()=>{let b=de;if(J){const E=J.toLowerCase();b=b.filter(U=>U.name.toLowerCase().includes(E))}return[...b].sort((E,U)=>E.type==="directory"&&U.type!=="directory"?-1:E.type!=="directory"&&U.type==="directory"?1:E.name.localeCompare(U.name))},[de,J]);i.useEffect(()=>{let b=!1;return jr(o,r).then(E=>{!b&&E&&a(E),m.current=!0}).catch(()=>{m.current=!0}),()=>{b=!0}},[o,r]),i.useEffect(()=>{if(m.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{wt(o,r,d).catch(()=>{})},500),()=>{f.current&&clearTimeout(f.current)}},[d,o,r]),i.useEffect(()=>{var b;(b=u.current)==null||b.focus()},[]),i.useEffect(()=>{if(!H)return;let b=!1;return ye(!0),(async()=>{try{if(Y){if(!ae.current){const q=await Te(o,r);if(b)return;ae.current=q.cwd}const E=`${ae.current}/${Y.replace(/\/$/,"")}`,U=await Te(o,r,E);if(b)return;xe(U.files)}else{const E=await Te(o,r);if(b)return;ae.current=E.cwd,xe(E.files)}ye(!1)}catch{if(b)return;xe([]),ye(!1)}})(),()=>{b=!0}},[H,Y,o,r]),i.useEffect(()=>{if(!H||!fe.current)return;const b=fe.current.querySelector(".file-item--active");b==null||b.scrollIntoView({block:"nearest"})},[he,H]);const $=i.useCallback(()=>{const b=h.current.trim();b&&(zr(b),t(b),a(""),wt(o,r,"").catch(()=>{}))},[t,o,r]),B=i.useCallback(b=>{g(),a(b)},[g]);i.useImperativeHandle(l,()=>({send:$,fillContent:B}),[$,B]),i.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const W=i.useCallback(()=>{const b=Zt();T(!1),S("");const E=u.current;if(E){const U=E.selectionStart,q=d.slice(0,U),re=d.slice(U),we=q.match(/(?:^|\s)(\/history)\s*$/);if(we){const le=q.length-we[1].length;a(d.slice(0,le)+re)}}b.length!==0&&(v(b),z(0),P(""),R(!0))},[d]),ne=i.useCallback(b=>{g(),a(b.text),R(!1),requestAnimationFrame(()=>{const E=u.current;E&&(E.selectionStart=E.selectionEnd=b.text.length,E.focus())})},[g]),_=i.useCallback(b=>{const E=F[b];if(!E)return;const U=j.filter(re=>re.ts!==E.ts||re.text!==E.text);v(U),localStorage.setItem(lt,JSON.stringify(U));const q=A?U.filter(re=>re.text.toLowerCase().includes(A.toLowerCase())):U;x>=q.length&&z(Math.max(0,q.length-1))},[F,j,x,A]);i.useEffect(()=>{if(!D||!L.current)return;const b=L.current.querySelector(".history-item--active");b==null||b.scrollIntoView({block:"nearest"})},[x,D]);const K=i.useCallback(b=>{if(b==="/history"){W();return}const E=u.current;if(!E)return;g();const U=E.selectionStart,q=d.slice(0,U),re=d.slice(U),le=q.lastIndexOf(`
26
+ `)+1,pe=q.slice(le).match(/\/[a-zA-Z:-]*$/);if(pe){const ie=le+(pe.index??0),ke=b+" ",Be=d.slice(0,ie)+ke+re;a(Be);const rn=ie+ke.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=rn,E.focus()})}else{const ie=q+b+re;a(ie);const ke=U+b.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ke,E.focus()})}T(!1),S(""),O(0)},[d,g,W]),X=i.useCallback(b=>{const E=u.current;if(!E)return;g();const U=E.selectionStart,q=d.slice(0,U),re=d.slice(U),we=q.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!we)return;const le=q.length-we[0].length;if(b.type==="directory"){const ce="@"+Y+b.name+"/",pe=d.slice(0,le)+ce+re;a(pe);const ie=le+ce.length;me(Y+b.name+"/"),V(""),ee(0),requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ie,E.focus()})}else{const ce=b.name+" ",pe=d.slice(0,le)+ce+re;a(pe);const ie=le+ce.length;G(!1),V(""),me(""),ee(0),xe([]),ae.current="",requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ie,E.focus()})}},[d,Y,g]),Z=i.useCallback(b=>{const E=b.target.value;if(a(E),D){const ce=E.trim();ce?(P(ce),z(0)):P("");return}const U=b.target.selectionStart,q=E.slice(0,U),re=q.lastIndexOf(`
27
+ `),le=q.slice(re+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(le)T(!0),S(le[1]),O(0),G(!1);else{T(!1);const ce=q.match(/@([a-zA-Z0-9_.\-/]*)$/);if(ce){const pe=ce[1],ie=pe.lastIndexOf("/"),ke=ie>=0?pe.slice(0,ie+1):"",Be=ie>=0?pe.slice(ie+1):pe;V(Be),ee(0),me(ke),G(!0)}else G(!1)}},[D]),ve=i.useCallback(b=>{if(k&&N.length>0){if(b.key==="ArrowDown"){b.preventDefault(),O(E=>(E+1)%N.length);return}if(b.key==="ArrowUp"){b.preventDefault(),O(E=>(E-1+N.length)%N.length);return}if(b.key==="Enter"||b.key==="Tab"){b.preventDefault(),K(N[w].cmd);return}if(b.key==="Escape"){b.preventDefault(),T(!1);return}}if(H&&I.length>0){if(b.key==="ArrowDown"){b.preventDefault(),ee(E=>(E+1)%I.length);return}if(b.key==="ArrowUp"){b.preventDefault(),ee(E=>(E-1+I.length)%I.length);return}if(b.key==="Tab"||b.key==="Enter"){b.preventDefault(),X(I[he]);return}if(b.key==="Escape"){b.preventDefault(),G(!1);return}}if(D&&F.length>0){if(b.key==="ArrowDown"){b.preventDefault(),z(E=>(E+1)%F.length);return}if(b.key==="ArrowUp"){b.preventDefault(),z(E=>(E-1+F.length)%F.length);return}if(b.key==="Enter"){b.preventDefault(),ne(F[x]);return}if(b.key==="Delete"||b.key==="Backspace"&&(b.ctrlKey||b.metaKey)){b.preventDefault(),_(x);return}if(b.key==="Escape"){b.preventDefault(),R(!1);return}}if(b.key==="z"&&(b.ctrlKey||b.metaKey)&&!b.shiftKey){Qe(b,y,a);return}if(b.key==="Tab"){Ze(b,a,p);return}b.key==="Enter"&&(b.ctrlKey||b.metaKey)&&(b.preventDefault(),$())},[$,k,N,w,K,H,I,he,X,p,y,D,F,x,ne,_]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[k&&N.length>0&&s.jsx("div",{className:"slash-dropdown",children:N.map((b,E)=>s.jsxs("div",{className:`slash-item${E===w?" slash-item--active":""}`,onMouseDown:U=>{U.preventDefault(),K(b.cmd)},onMouseEnter:()=>O(E),children:[s.jsx("span",{className:"slash-cmd",children:b.cmd}),s.jsx("span",{className:"slash-desc",children:b.desc})]},b.cmd))}),H&&(ue||I.length>0)&&s.jsx("div",{className:"file-dropdown",ref:fe,children:ue?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):I.map((b,E)=>s.jsxs("div",{className:`file-item${E===he?" file-item--active":""}`,onMouseDown:U=>{U.preventDefault(),X(b)},onMouseEnter:()=>ee(E),children:[s.jsx("span",{className:"file-icon",children:b.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:b.name})]},b.name))}),D&&s.jsx("div",{className:"history-dropdown",ref:L,children:F.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):F.map((b,E)=>s.jsxs("div",{className:`history-item${E===x?" history-item--active":""}`,onMouseDown:U=>{U.preventDefault(),ne(b)},onMouseEnter:()=>z(E),children:[s.jsx("span",{className:"history-text",children:b.text.length>120?b.text.slice(0,120)+"...":b.text}),s.jsx("span",{className:"history-time",children:new Date(b.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:U=>{U.preventDefault(),U.stopPropagation(),_(E)},title:"Delete (Del key)",children:"×"})]},`${b.ts}-${E}`))}),s.jsx("textarea",{ref:u,className:"md-editor-textarea",value:d,onChange:Z,onKeyDown:ve,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${c}px`}})]})});function Lr({sessionId:e,onSelect:t,onClose:n}){const{cwd:r,files:o,loading:l,error:c,handleNavigate:d,handleGoUp:a,handleRefresh:u}=ot({sessionId:e,onClose:n}),f=(m,p)=>{t(r+"/"+m,p)};return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"#1a1b26",display:"flex",flexDirection:"column",fontFamily:"inherit"},children:[s.jsx(it,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(at,{loading:l,error:c,empty:o.length===0,emptyText:"No files found"}),!l&&!c&&o.map(m=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent"},onClick:()=>{m.type==="directory"?d(m.name):f(m.name,m.size)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:m.type==="directory"?"#7aa2f7":"#565f89"},children:Yt(m.name,m.type)}),s.jsx("span",{style:{flex:1,color:m.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m.name}),m.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:st(m.size)})]},m.name))]})]})}const Mr="modulepreload",Dr=function(e){return"/"+e},Ct={},Or=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(n.map(a=>{if(a=Dr(a),a in Ct)return;Ct[a]=!0;const u=a.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${f}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":Mr,u||(m.as="script"),m.crossOrigin="",m.href=a,d&&m.setAttribute("nonce",d),document.head.appendChild(m),u)return new Promise((p,y)=>{m.addEventListener("load",p),m.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${a}`)))})}))}function l(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&l(d.reason);return t().catch(l)})};let tt=null,We=null;function Ar(){return We||(We=Or(()=>import("./pdf-Tk4_4Bu3.js"),[]).then(e=>(tt=e,e.GlobalWorkerOptions.workerSrc=new URL("/assets/pdf.worker-BA9kU3Pw.mjs",import.meta.url).toString(),e))),We}function $r({data:e,scrollRef:t}){const n=i.useRef(null),[r,o]=i.useState(null),[l,c]=i.useState(!0),d=i.useRef(0),a=u=>{n.current=u,t==null||t(u)};return i.useEffect(()=>{if(!e)return;const u=++d.current;return c(!0),o(null),(async()=>{try{if(await Ar(),!tt||u!==d.current)return;let f;if(e instanceof Uint8Array)f=e;else{const h=atob(e);f=new Uint8Array(h.length);for(let g=0;g<h.length;g++)f[g]=h.charCodeAt(g)}const m=await tt.getDocument({data:f}).promise;if(u!==d.current)return;const p=n.current;if(!p)return;for(;p.firstChild;)p.removeChild(p.firstChild);const y=p.clientWidth-24;for(let h=1;h<=m.numPages;h++){const g=await m.getPage(h);if(u!==d.current)return;const k=g.getViewport({scale:1}),T=Math.min(y/k.width,2),C=g.getViewport({scale:T}),S=document.createElement("canvas");S.width=C.width,S.height=C.height,S.style.display="block",S.style.margin="0 auto 8px",S.style.maxWidth="100%";const w=S.getContext("2d");if(w){if(await g.render({canvasContext:w,viewport:C,canvas:S}).promise,u!==d.current)return;p.appendChild(S)}}c(!1)}catch(f){if(u!==d.current)return;o(f instanceof Error?f.message:"Failed to render PDF"),c(!1)}})(),()=>{d.current++}},[e]),s.jsxs("div",{ref:a,className:"pdf-renderer",children:[l&&s.jsx("div",{style:{padding:"20px",textAlign:"center",color:"#565f89",fontSize:13},children:"Loading PDF..."}),r&&s.jsxs("div",{style:{padding:"12px",color:"#f7768e",fontSize:12},children:["PDF Error: ",r]})]})}const Ne=typeof window<"u"?i.useLayoutEffect:i.useEffect;function Tt(e){if(e!==void 0)switch(typeof e){case"number":return e;case"string":{if(e.endsWith("px"))return parseFloat(e);break}}}function Pr({box:e,defaultHeight:t,defaultWidth:n,disabled:r,element:o,mode:l,style:c}){const{styleHeight:d,styleWidth:a}=i.useMemo(()=>({styleHeight:Tt(c==null?void 0:c.height),styleWidth:Tt(c==null?void 0:c.width)}),[c==null?void 0:c.height,c==null?void 0:c.width]),[u,f]=i.useState({height:t,width:n}),m=r||d!==void 0||l==="only-width"||d!==void 0&&a!==void 0;return Ne(()=>{if(o===null||m)return;const p=new ResizeObserver(y=>{for(const h of y){const{contentRect:g,target:k}=h;o===k&&f(T=>T.height===g.height&&T.width===g.width?T:{height:g.height,width:g.width})}});return p.observe(o,{box:e}),()=>{p==null||p.unobserve(o)}},[e,m,o,d,a]),i.useMemo(()=>({height:d??u.height,width:a??u.width}),[u,d,a])}function _r(e){const t=i.useRef(()=>{throw new Error("Cannot call during render.")});return Ne(()=>{t.current=e},[e]),i.useCallback(n=>{var r;return(r=t.current)==null?void 0:r.call(t,n)},[t])}function He({containerElement:e,direction:t,isRtl:n,scrollOffset:r}){return r}function ge(e,t="Assertion error"){if(!e)throw Error(t)}function ze(e,t){if(e===t)return!0;if(!!e!=!!t||(ge(e!==void 0),ge(t!==void 0),Object.keys(e).length!==Object.keys(t).length))return!1;for(const n in e)if(!Object.is(t[n],e[n]))return!1;return!0}function Qt({cachedBounds:e,itemCount:t,itemSize:n}){if(t===0)return 0;if(typeof n=="number")return t*n;{const r=e.get(e.size===0?0:e.size-1);ge(r!==void 0,"Unexpected bounds cache miss");const o=(r.scrollOffset+r.size)/e.size;return t*o}}function Br({align:e,cachedBounds:t,index:n,itemCount:r,itemSize:o,containerScrollOffset:l,containerSize:c}){if(n<0||n>=r)throw RangeError(`Invalid index specified: ${n}`,{cause:`Index ${n} is not within the range of 0 - ${r-1}`});const d=Qt({cachedBounds:t,itemCount:r,itemSize:o}),a=t.get(n),u=Math.max(0,Math.min(d-c,a.scrollOffset)),f=Math.max(0,a.scrollOffset-c+a.size);switch(e==="smart"&&(l>=f&&l<=u?e="auto":e="center"),e){case"start":return u;case"end":return f;case"center":return a.scrollOffset<=c/2?0:a.scrollOffset+a.size/2>=d-c/2?d-c:a.scrollOffset+a.size/2-c/2;case"auto":default:return l>=f&&l<=u?l:l<f?f:u}}function Ke({cachedBounds:e,containerScrollOffset:t,containerSize:n,itemCount:r,overscanCount:o}){const l=r-1;let c=0,d=-1,a=0,u=-1,f=0;for(;f<l;){const m=e.get(f);if(m.scrollOffset+m.size>t)break;f++}for(c=f,a=Math.max(0,c-o);f<l;){const m=e.get(f);if(m.scrollOffset+m.size>=t+n)break;f++}return d=Math.min(l,f),u=Math.min(r-1,d+o),c<0&&(c=0,d=-1,a=0,u=-1),{startIndexVisible:c,stopIndexVisible:d,startIndexOverscan:a,stopIndexOverscan:u}}function Fr({itemCount:e,itemProps:t,itemSize:n}){const r=new Map;return{get(o){for(ge(o<e,`Invalid index ${o}`);r.size-1<o;){const c=r.size;let d;switch(typeof n){case"function":{d=n(c,t);break}case"number":{d=n;break}}if(c===0)r.set(c,{size:d,scrollOffset:0});else{const a=r.get(c-1);ge(a!==void 0,`Unexpected bounds cache miss for index ${o}`),r.set(c,{scrollOffset:a.scrollOffset+a.size,size:d})}}const l=r.get(o);return ge(l!==void 0,`Unexpected bounds cache miss for index ${o}`),l},set(o,l){r.set(o,l)},get size(){return r.size}}}function Ur({itemCount:e,itemProps:t,itemSize:n}){return i.useMemo(()=>Fr({itemCount:e,itemProps:t,itemSize:n}),[e,t,n])}function Wr({containerSize:e,itemSize:t}){let n;switch(typeof t){case"string":{ge(t.endsWith("%"),`Invalid item size: "${t}"; string values must be percentages (e.g. "100%")`),ge(e!==void 0,"Container size must be defined if a percentage item size is specified"),n=e*parseInt(t)/100;break}default:{n=t;break}}return n}function Hr({containerElement:e,containerStyle:t,defaultContainerSize:n=0,direction:r,isRtl:o=!1,itemCount:l,itemProps:c,itemSize:d,onResize:a,overscanCount:u}){const{height:f=n,width:m=n}=Pr({defaultHeight:n,defaultWidth:void 0,element:e,mode:"only-height",style:t}),p=i.useRef({height:0,width:0}),y=f,h=Wr({containerSize:y,itemSize:d});i.useLayoutEffect(()=>{if(typeof a=="function"){const x=p.current;(x.height!==f||x.width!==m)&&(a({height:f,width:m},{...x}),x.height=f,x.width=m)}},[f,a,m]);const g=Ur({itemCount:l,itemProps:c,itemSize:h}),k=i.useCallback(x=>g.get(x),[g]),[T,C]=i.useState(()=>Ke({cachedBounds:g,containerScrollOffset:0,containerSize:y,itemCount:l,overscanCount:u})),{startIndexVisible:S,startIndexOverscan:w,stopIndexVisible:O,stopIndexOverscan:D}={startIndexVisible:Math.min(l-1,T.startIndexVisible),startIndexOverscan:Math.min(l-1,T.startIndexOverscan),stopIndexVisible:Math.min(l-1,T.stopIndexVisible),stopIndexOverscan:Math.min(l-1,T.stopIndexOverscan)},R=i.useCallback(()=>Qt({cachedBounds:g,itemCount:l,itemSize:h}),[g,l,h]),j=i.useCallback(x=>{const z=He({containerElement:e,direction:r,isRtl:o,scrollOffset:x});return Ke({cachedBounds:g,containerScrollOffset:z,containerSize:y,itemCount:l,overscanCount:u})},[g,e,y,r,o,l,u]);Ne(()=>{const x=(e==null?void 0:e.scrollTop)??0;C(j(x))},[e,r,j]),Ne(()=>{if(!e)return;const x=()=>{C(z=>{const{scrollLeft:A,scrollTop:P}=e,L=He({containerElement:e,direction:r,isRtl:o,scrollOffset:P}),F=Ke({cachedBounds:g,containerScrollOffset:L,containerSize:y,itemCount:l,overscanCount:u});return ze(F,z)?z:F})};return e.addEventListener("scroll",x),()=>{e.removeEventListener("scroll",x)}},[g,e,y,r,l,u]);const v=_r(({align:x="auto",containerScrollOffset:z,index:A})=>{let P=Br({align:x,cachedBounds:g,containerScrollOffset:z,containerSize:y,index:A,itemCount:l,itemSize:h});if(e){if(P=He({containerElement:e,direction:r,isRtl:o,scrollOffset:P}),typeof e.scrollTo!="function"){const L=j(P);ze(T,L)||C(L)}return P}});return{getCellBounds:k,getEstimatedSize:R,scrollToIndex:v,startIndexOverscan:w,startIndexVisible:S,stopIndexOverscan:D,stopIndexVisible:O}}function Kr(e){return i.useMemo(()=>e,Object.values(e))}function Vr(e,t){const{ariaAttributes:n,style:r,...o}=e,{ariaAttributes:l,style:c,...d}=t;return ze(n,l)&&ze(r,c)&&ze(o,d)}function Gr(e){return e!=null&&typeof e=="object"&&"getAverageRowHeight"in e&&typeof e.getAverageRowHeight=="function"}const Jr="data-react-window-index";function Yr({children:e,className:t,defaultHeight:n=0,listRef:r,onResize:o,onRowsRendered:l,overscanCount:c=3,rowComponent:d,rowCount:a,rowHeight:u,rowProps:f,tagName:m="div",style:p,...y}){const h=Kr(f),g=i.useMemo(()=>i.memo(d,Vr),[d]),[k,T]=i.useState(null),C=Gr(u),S=i.useMemo(()=>C?P=>u.getRowHeight(P)??u.getAverageRowHeight():u,[C,u]),{getCellBounds:w,getEstimatedSize:O,scrollToIndex:D,startIndexOverscan:R,startIndexVisible:j,stopIndexOverscan:v,stopIndexVisible:x}=Hr({containerElement:k,containerStyle:p,defaultContainerSize:n,direction:"vertical",itemCount:a,itemProps:h,itemSize:S,onResize:o,overscanCount:c});i.useImperativeHandle(r,()=>({get element(){return k},scrollToRow({align:P="auto",behavior:L="auto",index:F}){const H=D({align:P,containerScrollOffset:(k==null?void 0:k.scrollTop)??0,index:F});typeof(k==null?void 0:k.scrollTo)=="function"&&k.scrollTo({behavior:L,top:H})}}),[k,D]),Ne(()=>{if(!k)return;const P=Array.from(k.children).filter((L,F)=>{if(L.hasAttribute("aria-hidden"))return!1;const H=`${R+F}`;return L.setAttribute(Jr,H),!0});if(C)return u.observeRowElements(P)},[k,C,u,R,v]),i.useEffect(()=>{R>=0&&v>=0&&l&&l({startIndex:j,stopIndex:x},{startIndex:R,stopIndex:v})},[l,R,j,v,x]);const z=i.useMemo(()=>{const P=[];if(a>0)for(let L=R;L<=v;L++){const F=w(L);P.push(i.createElement(g,{...h,ariaAttributes:{"aria-posinset":L+1,"aria-setsize":a,role:"listitem"},key:L,index:L,style:{position:"absolute",left:0,transform:`translateY(${F.scrollOffset}px)`,height:C?void 0:F.size,width:"100%"}}))}return P},[g,w,C,a,h,R,v]),A=s.jsx("div",{"aria-hidden":!0,style:{height:O(),width:"100%",zIndex:-1}});return i.createElement(m,{role:"list",...y,className:t,ref:T,style:{position:"relative",maxHeight:"100%",flexGrow:1,overflowY:"auto",...p}},z,e,A)}const qr='"Cascadia Code", "Fira Code", "JetBrains Mono", Consolas, monospace',Xr=20;function Zr({index:e,style:t,lines:n}){return s.jsx("div",{style:{...t,padding:"0 12px",color:"#a9b1d6",whiteSpace:"pre",overflow:"hidden",boxSizing:"border-box"},children:n[e]})}function It({lines:e,totalSize:t,receivedBytes:n,streaming:r}){const o=i.useRef(null),[,l]=i.useState(0),c=M(y=>y.fontSize),d=Math.round(c*1.5);i.useEffect(()=>{const y=o.current;if(!y)return;const h=new ResizeObserver(()=>l(g=>g+1));return h.observe(y),()=>h.disconnect()},[]);const a=t>0?Math.round(n/t*100):0,u=e.length.toLocaleString(),f=o.current,m=(f==null?void 0:f.clientWidth)||0,p=(f==null?void 0:f.clientHeight)||0;return s.jsxs("div",{ref:o,style:{height:"100%",width:"100%",position:"relative",fontFamily:qr,fontSize:c,lineHeight:`${d}px`},children:[p>0&&s.jsx(Yr,{rowComponent:Zr,rowCount:e.length,rowHeight:d,rowProps:{lines:e},overscanCount:Xr,style:{height:p,width:m}}),s.jsxs("div",{style:{position:"absolute",bottom:6,right:14,fontSize:10,color:"#565f89",background:"rgba(22, 22, 30, 0.85)",padding:"2px 8px",borderRadius:4,pointerEvents:"none",userSelect:"none"},children:[u," lines",r&&` (${a}%)`]})]})}const je={additions:[],deletions:[]};let Qr=0;function Et(){return`ann_${++Qr}_${Date.now()}`}function Ve(e,t){return`plan-annotations-${e}-${t}`}function eo(e){const t=rt.parser([e],{async:!1});return $t.sanitize(t,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function Ge(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++){const o=e[r].raw??"";for(const l of o)l===`
28
+ `&&n++}return n}function jt(e,t){const n=[];return e.additions.length>0&&(n.push("[增加批注]"),e.additions.forEach((r,o)=>{var c;const l=((c=t[r.sourceLine-1])==null?void 0:c.trim().slice(0,50))??"";n.push(`${o+1}. 在第${r.sourceLine}行 ("${l}") 之后添加: "${r.content}"`)})),e.deletions.length>0&&(n.length>0&&n.push(""),n.push("[删除标记]"),e.deletions.forEach((r,o)=>{const l=t.slice(r.startLine-1,r.endLine).join(" ").trim();n.push(`${o+1}. 删除第${r.startLine}-${r.endLine}行: "${l.slice(0,60)}${l.length>60?"...":""}"`)})),n.length===0?"":`请根据以下用户批注修改 PLAN.md:
29
+
30
+ `+n.join(`
31
+ `)}const Rt=i.forwardRef(function({markdown:t,filePath:n,sessionId:r,onExecute:o,onClear:l,expanded:c},d){const a=M(N=>N.fontSize),u=i.useMemo(()=>t?rt.lexer(t):[],[t]),f=i.useMemo(()=>t.split(`
32
+ `),[t]),m=i.useRef(new Set),[p,y]=i.useState(()=>{try{const N=localStorage.getItem(Ve(r,n)),I=N?JSON.parse(N):je,$=new Set;return I.additions.forEach(B=>$.add(B.id)),I.deletions.forEach(B=>$.add(B.id)),m.current=$,I}catch{return je}}),h=i.useRef([]),g=30,k=i.useCallback(()=>{h.current.push(JSON.parse(JSON.stringify(p))),h.current.length>g&&h.current.shift()},[p]),T=i.useRef(void 0);i.useEffect(()=>(T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{localStorage.setItem(Ve(r,n),JSON.stringify(p))},300),()=>{T.current&&clearTimeout(T.current)}),[p,r,n]),i.useEffect(()=>{try{const N=localStorage.getItem(Ve(r,n)),I=N?JSON.parse(N):je;y(I);const $=new Set;I.additions.forEach(B=>$.add(B.id)),I.deletions.forEach(B=>$.add(B.id)),m.current=$,h.current=[]}catch{y(je),m.current=new Set}},[r,n]);const[C,S]=i.useState(null),[w,O]=i.useState(""),D=i.useRef(null),[R,j]=i.useState(null),[v,x]=i.useState(""),z=i.useRef(null),[A,P]=i.useState(null),L=i.useRef(null);i.useEffect(()=>{C!=null&&requestAnimationFrame(()=>{var N;return(N=D.current)==null?void 0:N.focus()})},[C]);const F=i.useCallback(N=>{if(!w.trim()){S(null),O("");return}k();const I=Ge(u,N+1);y($=>({...$,additions:[...$.additions,{id:Et(),afterTokenIndex:N,sourceLine:I,content:w.trim()}]})),S(null),O("")},[w,k,u]),H=i.useCallback(N=>{k(),y(I=>({...I,additions:I.additions.filter($=>$.id!==N)}))},[k]),G=i.useCallback((N,I)=>{k(),y($=>({...$,additions:$.additions.map(B=>B.id===N?{...B,content:I}:B)}))},[k]),J=i.useCallback(()=>{var N;A&&(k(),y(I=>({...I,deletions:[...I.deletions,{id:Et(),tokenIndices:A.tokenIndices,startLine:A.startLine,endLine:A.endLine,selectedText:A.text.slice(0,80)}]})),P(null),(N=window.getSelection())==null||N.removeAllRanges())},[A,k]),V=i.useCallback(N=>{k(),y(I=>({...I,deletions:I.deletions.filter($=>$.id!==N)}))},[k]),Y=i.useCallback((N,I)=>{k(),y($=>({...$,deletions:$.deletions.map(B=>B.id===N?{...B,selectedText:I}:B)}))},[k]),me=i.useCallback(N=>{let I=N instanceof Element?N:N.parentElement;for(;I&&I!==L.current;){if(I.hasAttribute("data-token-index"))return I;I=I.parentElement}return null},[]),he=i.useCallback(()=>{const N=window.getSelection();if(!N||N.isCollapsed||!L.current){P(null);return}const I=N.toString().trim();if(!I){P(null);return}const $=N.getRangeAt(0);if(!L.current.contains($.commonAncestorContainer)){P(null);return}const B=me($.startContainer),W=me($.endContainer);if(!B||!W){P(null);return}const ne=parseInt(B.getAttribute("data-token-index")||"0",10),_=parseInt(W.getAttribute("data-token-index")||"0",10),K=[];for(let U=Math.min(ne,_);U<=Math.max(ne,_);U++)K.push(U);const X=Ge(u,Math.min(ne,_)),Z=Ge(u,Math.max(ne,_)+1),ve=$.getBoundingClientRect(),b=L.current,E=b.getBoundingClientRect();navigator.clipboard.writeText(I).catch(()=>{}),P({x:ve.right-E.left+b.scrollLeft+6,y:ve.top-E.top+b.scrollTop-2,tokenIndices:K,startLine:X,endLine:Z,text:I})},[u,me]),ee=i.useRef(void 0);i.useEffect(()=>{const N=()=>{ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{const I=window.getSelection();if(!I||I.isCollapsed||!L.current){P(null);return}const $=I.anchorNode;$&&L.current.contains($)&&he()},120)};return document.addEventListener("selectionchange",N),()=>{document.removeEventListener("selectionchange",N),ee.current&&clearTimeout(ee.current)}},[he]),Xt(L,u),i.useEffect(()=>{const N=I=>{var $;if((I.ctrlKey||I.metaKey)&&I.key==="z"&&!I.shiftKey){if((($=document.activeElement)==null?void 0:$.tagName)==="TEXTAREA")return;const B=h.current.pop();B&&(I.preventDefault(),y(B))}};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[]);const de=i.useCallback(()=>({additions:p.additions.filter(N=>!m.current.has(N.id)),deletions:p.deletions.filter(N=>!m.current.has(N.id))}),[p]),xe=i.useCallback(()=>{const N=jt(de(),f);if(N){o(N);const I=new Set;p.additions.forEach($=>I.add($.id)),p.deletions.forEach($=>I.add($.id)),m.current=I}},[de,p,f,o]);i.useImperativeHandle(d,()=>({getSummary:()=>jt(de(),f)}),[de,f]);const ue=i.useCallback(()=>{k(),y(je),l==null||l()},[k,l]),ye=i.useMemo(()=>{const N=new Set;return p.deletions.forEach(I=>I.tokenIndices.forEach($=>N.add($))),N},[p.deletions]),ae=i.useMemo(()=>{const N=new Map;return p.additions.forEach(I=>{const $=N.get(I.afterTokenIndex)||[];$.push(I),N.set(I.afterTokenIndex,$)}),N},[p.additions]),fe=p.additions.length>0||p.deletions.length>0;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("button",{className:"pane-btn",onClick:xe,disabled:!fe,title:"Save annotations to editor",style:fe?{color:"#9ece6a"}:{opacity:.4},children:"Save"}),s.jsx("button",{className:"pane-btn",onClick:ue,disabled:!fe,title:"Clear all annotations",style:fe?{}:{opacity:.4},children:"Clear"}),fe&&s.jsxs("span",{style:{fontSize:10,color:"#565f89",marginLeft:4},children:["+",p.additions.length," −",p.deletions.length]})]}),s.jsxs("div",{ref:L,className:"plan-anno-content md-preview",style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${a}px`},onMouseUp:he,children:[s.jsx(zt,{index:-1,active:C===-1,additions:ae.get(-1),onOpen:()=>{S(-1),O("")},onSubmit:()=>F(-1),onRemoveAddition:H,onEditAddition:G,insertText:w,setInsertText:O,textareaRef:C===-1?D:void 0,expanded:c,alwaysShow:u.length===0,fontSize:a}),u.map((N,I)=>{const $=eo(N);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":I,className:ye.has(I)?"plan-block--deleted":void 0,dangerouslySetInnerHTML:{__html:$}}),p.deletions.filter(B=>B.tokenIndices.includes(I)&&B.tokenIndices[0]===I).map(B=>s.jsx("div",{className:"plan-deletion-card",children:R===B.id?s.jsx("textarea",{ref:z,className:"plan-annotation-textarea",value:v,onChange:W=>x(W.target.value),onKeyDown:W=>{if(W.key==="Enter"&&(W.ctrlKey||W.metaKey)){W.preventDefault();const ne=v.trim();ne?Y(B.id,ne):V(B.id),j(null)}W.key==="Escape"&&(W.preventDefault(),j(null))},onBlur:()=>{const W=v.trim();W?Y(B.id,W):V(B.id),j(null)},rows:et(v),style:{fontSize:`${a}px`,flex:1}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${a}px`,color:"#f7768e",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>{j(B.id),x(B.selectedText),requestAnimationFrame(()=>{const W=z.current;W&&(W.focus(),W.selectionStart=W.selectionEnd=W.value.length)})},title:"Double-click to edit",children:B.selectedText}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>{j(B.id),x(B.selectedText),requestAnimationFrame(()=>{const W=z.current;W&&(W.focus(),W.selectionStart=W.selectionEnd=W.value.length)})},style:{color:"#7aa2f7"},title:"Edit deletion annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>V(B.id),title:"Remove deletion",children:"×"})]})},B.id)),s.jsx(zt,{index:I,active:C===I,additions:ae.get(I),onOpen:()=>{S(I),O("")},onSubmit:()=>F(I),onRemoveAddition:H,onEditAddition:G,insertText:w,setInsertText:O,textareaRef:C===I?D:void 0,expanded:c,fontSize:a})]},I)}),A&&s.jsx("button",{className:"plan-delete-float",style:{top:A.y,left:A.x},onMouseDown:N=>{N.preventDefault(),J()},children:"−"})]})]})});function zt({index:e,active:t,additions:n,onOpen:r,onSubmit:o,onRemoveAddition:l,onEditAddition:c,insertText:d,setInsertText:a,textareaRef:u,expanded:f,alwaysShow:m,fontSize:p=14}){const[y,h]=i.useState(null),[g,k]=i.useState(""),T=i.useRef(null),C=Xe(),S=Xe();i.useEffect(()=>{y&&(C.clearUndo(),requestAnimationFrame(()=>{const v=T.current;v&&(v.focus(),v.selectionStart=v.selectionEnd=v.value.length)}))},[y]),i.useEffect(()=>{t&&S.clearUndo()},[t]);const w=i.useCallback(v=>{k(x=>(C.pushUndo(x),v))},[C]),O=i.useCallback(v=>{S.pushUndo(d),a(v)},[d,a,S]),D=i.useCallback(v=>{h(v.id),k(v.content)},[]),R=i.useCallback(()=>{if(!y)return;const v=g.trim();v?c(y,v):l(y),h(null),k("")},[y,g,c,l]),j=i.useCallback(()=>{h(null),k("")},[]);return s.jsxs("div",{className:`plan-insert-zone${m?" plan-insert-zone--empty":""}`,"data-zone-index":e,children:[n==null?void 0:n.map(v=>s.jsx("div",{className:"plan-annotation-card",children:y===v.id?s.jsx("textarea",{ref:T,className:"plan-annotation-textarea",value:g,onChange:x=>w(x.target.value),onKeyDown:x=>{if(x.key==="Enter"&&(x.ctrlKey||x.metaKey)){x.preventDefault(),R();return}if(x.key==="Escape"){x.preventDefault(),j();return}if(x.key==="Tab"){Ze(x,w);return}if(x.key==="z"&&(x.ctrlKey||x.metaKey)&&!x.shiftKey){Qe(x,C.popUndo,k);return}},onBlur:R,rows:et(g),style:{fontSize:`${p}px`,flex:1,...f?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${p}px`,color:"#e0af68",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>D(v),title:"Double-click to edit",children:v.content}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>D(v),style:{color:"#7aa2f7"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>l(v.id),children:"×"})]})},v.id)),t?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:d,onChange:v=>O(v.target.value),onKeyDown:v=>{if(v.key==="Enter"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),o();return}if(v.key==="Escape"){v.preventDefault(),o();return}if(v.key==="Tab"){Ze(v,O);return}if(v.key==="z"&&(v.ctrlKey||v.metaKey)&&!v.shiftKey){Qe(v,S.popUndo,a);return}},placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:et(d),style:{fontSize:`${p}px`,...f?{minWidth:300}:void 0}})}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}const Je={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},to=200;function no(){const[e,t]=i.useState(Je),n=i.useRef("lines"),r=i.useRef([]),o=i.useRef(""),l=i.useRef(""),c=i.useRef([]),d=i.useRef(0),a=i.useRef(0),u=i.useRef(null),f=i.useRef(null),m=i.useCallback(()=>{const T=n.current;t(C=>({...C,receivedBytes:d.current,...T==="lines"?{lines:[...r.current]}:{},...T==="content"?{content:l.current}:{}}))},[]),p=i.useCallback(()=>{u.current===null&&(u.current=window.setTimeout(()=>{u.current=null,m()},to))},[m]),y=i.useCallback(T=>{n.current=T,r.current=[],o.current="",l.current="",c.current=[],d.current=0,a.current=0,f.current=new TextDecoder,u.current!==null&&(clearTimeout(u.current),u.current=null),t({...Je,mode:T,status:"streaming"})},[]),h=i.useCallback(T=>{d.current+=T.length;const C=n.current;if(C==="lines"){const w=f.current.decode(T,{stream:!0}).split(`
33
+ `);w[0]=o.current+w[0],o.current=w.pop(),w.length>0&&r.current.push(...w)}else if(C==="content"){const S=f.current.decode(T,{stream:!0});l.current+=S}else c.current.push(new Uint8Array(T));p()},[p]),g=i.useCallback(T=>{switch(T.type){case"file-stream-start":a.current=T.size,t(C=>({...C,totalSize:T.size,mtime:T.mtime}));break;case"file-stream-end":{u.current!==null&&(clearTimeout(u.current),u.current=null);const C=n.current;let S=r.current,w=l.current,O=null;if(C==="lines"){const D=f.current.decode(),R=o.current+D;R&&(S=[...S,R],r.current=S),o.current=""}else if(C==="content"){const D=f.current.decode();w=l.current+D,l.current=w}else{const D=c.current.reduce((j,v)=>j+v.length,0);O=new Uint8Array(D);let R=0;for(const j of c.current)O.set(j,R),R+=j.length;c.current=[]}t({status:"complete",mode:C,lines:C==="lines"?[...S]:[],content:C==="content"?w:"",buffer:C==="binary"?O:null,totalSize:a.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":u.current!==null&&(clearTimeout(u.current),u.current=null),t(C=>({...C,status:"error",error:T.error}));break}},[]),k=i.useCallback(()=>{u.current!==null&&(clearTimeout(u.current),u.current=null),r.current=[],o.current="",l.current="",c.current=[],d.current=0,a.current=0,f.current=null,t(Je)},[]);return{state:e,startStream:y,handleChunk:h,handleControl:g,reset:k}}function ro(e=50,t=20,n=80){const[r,o]=i.useState(e),l=i.useRef(null),c=i.useCallback(d=>{d.preventDefault();const a=l.current;if(!a)return;const u=a.getBoundingClientRect(),f=u.width;document.body.classList.add("resizing-panes-h");let m=null;const p=h=>{m||(m=requestAnimationFrame(()=>{m=null;const g=h.clientX-u.left,k=Math.min(n,Math.max(t,g/f*100));o(k)}))},y=()=>{m&&cancelAnimationFrame(m),document.body.classList.remove("resizing-panes-h"),document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",y)};document.addEventListener("mousemove",p),document.addEventListener("mouseup",y)},[t,n]);return{leftWidthPercent:r,containerRef:l,onDividerMouseDown:c}}function oo(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return t===".md"?"md":t===".html"||t===".htm"?"html":t===".pdf"?"pdf":"text"}function Nt(e){return e.split("/").pop()||e}const so=3e3;function Ye({label:e,percent:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"#565f89",fontSize:13},children:e}),t!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"#292e42",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${t}%`,backgroundColor:"#7aa2f7",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"#565f89",whiteSpace:"nowrap"},children:[t,"%"]})]})]})}function Lt({sessionId:e,onSelect:t}){const n=i.useCallback(()=>{},[]),{cwd:r,files:o,loading:l,error:c,handleNavigate:d,handleGoUp:a,handleRefresh:u}=ot({sessionId:e,onClose:n,pollCwd:so});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsx(it,{cwd:r,onGoUp:a,onRefresh:u,onClose:n}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsx(at,{loading:l,error:c,empty:o.length===0,emptyText:"No files found"}),!l&&!c&&o.map(f=>s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"3px 12px",fontSize:13,cursor:"pointer",borderBottom:"1px solid #1e2030"},onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#24283b"},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent"},onClick:()=>{f.type==="directory"?d(f.name):t(r+"/"+f.name)},children:[s.jsx("span",{style:{width:20,flexShrink:0,marginRight:6,color:f.type==="directory"?"#7aa2f7":"#565f89"},children:Yt(f.name,f.type)}),s.jsx("span",{style:{flex:1,color:f.type==="directory"?"#7aa2f7":"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:f.name}),f.type==="file"&&s.jsx("span",{style:{fontSize:10,color:"#565f89",marginLeft:6,flexShrink:0,whiteSpace:"nowrap"},children:st(f.size)})]},f.name))]})]})}function io({sessionId:e,token:t,connected:n,onClose:r,onSend:o,onRequestFileStream:l,planMode:c,onPlanModeClose:d}){const[a,u]=i.useState(null),[f,m]=i.useState(null),p=no(),[y,h]=i.useState(!1),[g,k]=i.useState(!1),[T,C]=i.useState(!1),{leftWidthPercent:S,containerRef:w,onDividerMouseDown:O}=ro(50),D=i.useRef(null),R=i.useRef(null),[j,v]=i.useState(!1),x=i.useRef("doc"),[z,A]=i.useState(null),[P,L]=i.useState(""),[F,H]=i.useState(!1),[G,J]=i.useState(!1);i.useEffect(()=>{if(!c){V.current=null;return}let _=!1;return H(!0),(async()=>{try{const K=await Te(t,e);if(_)return;if(K.files.find(Z=>Z.name==="PLAN.md")){const Z=K.cwd+"/PLAN.md";A(Z),L("")}else{try{const Z=await vr(t,e,"PLAN.md");if(_)return;if(Z.ok&&Z.path){A(Z.path),L(""),H(!1);return}}catch{}A(null),L("")}}catch{A(null)}finally{_||H(!1)}})(),()=>{_=!0}},[c,e,t]);const V=i.useRef(null);i.useEffect(()=>{!c||!z||!n||V.current===z&&P||(V.current=z,x.current="plan",p.reset(),p.startStream("content"),l==null||l(z))},[c,z,n]),i.useEffect(()=>{c&&p.state.status==="complete"&&z&&x.current==="plan"&&L(p.state.content)},[c,p.state.status,p.state.content,z]);const Y=i.useRef(null),me=i.useCallback(_=>{Y.current=_,d==null||d()},[d]);i.useEffect(()=>{!c&&Y.current&&D.current&&(D.current.fillContent(Y.current),Y.current=null)},[c]);const he=i.useCallback(()=>{!z||!n||(V.current=null,x.current="plan",L(""),p.reset(),p.startStream("content"),l==null||l(z),V.current=z)},[z,n,p,l]),ee=i.useRef(new Map),de=i.useRef(null),xe=i.useRef(null);i.useEffect(()=>(Qn(e,p.handleChunk,p.handleControl),()=>er(e)),[e,p.handleChunk,p.handleControl]);const ue=i.useCallback(()=>{if(!a)return;const _=g?xe.current:de.current;_&&ee.current.set(a,_.scrollTop)},[a,g]),ye=i.useCallback(_=>{const K=ee.current.get(_);K!=null&&requestAnimationFrame(()=>{const X=g?xe.current:de.current;X&&(X.scrollTop=K)})},[g]),ae=i.useCallback((_,K)=>{ue();const X=oo(_);u(_),m(X),h(!1),x.current="doc",p.reset();const Z=X==="text"?"lines":X==="pdf"?"binary":"content";p.startStream(Z),l==null||l(_)},[ue,p,l]),fe=i.useCallback(()=>{if(!a||!f)return;x.current="doc",p.reset();const _=f==="text"?"lines":f==="pdf"?"binary":"content";p.startStream(_),l==null||l(a)},[a,f,p,l]),N=i.useCallback(()=>{a&&navigator.clipboard.writeText(a).then(()=>{C(!0),setTimeout(()=>C(!1),1500)}).catch(()=>{})},[a]);i.useEffect(()=>{if(!g&&!G)return;const _=K=>{if(K.key==="Escape"){if(G){J(!1);return}ue(),k(!1)}};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[g,G,ue]),i.useEffect(()=>{a&&p.state.status==="complete"&&ye(a)},[g,a,ye,p.state.status]);const{totalSize:I,receivedBytes:$}=p.state,B=I>0?Math.round($/I*100):0,W=i.useCallback(()=>{const _=window.getSelection(),K=_==null?void 0:_.toString();K&&navigator.clipboard.writeText(K).catch(()=>{})},[]),ne=_=>{if(!a)return s.jsx(Lt,{sessionId:e,onSelect:ae});const{status:K,lines:X,content:Z,buffer:ve}=p.state;if(K==="error")return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#f7768e",fontSize:"13px",padding:"12px",textAlign:"center"},children:p.state.error||"Stream error"});if(K==="streaming")return f==="text"?s.jsx(It,{lines:X,totalSize:I,receivedBytes:$,streaming:!0}):s.jsx(Ye,{label:"Loading...",percent:B});if(K==="complete"){if(f==="text")return s.jsx(It,{lines:X,totalSize:I,receivedBytes:$,streaming:!1});if(f==="md")return s.jsx("div",{ref:_,style:{height:"100%",overflow:"auto"},children:s.jsx(Er,{content:Z})});if(f==="html")return s.jsx("div",{ref:_,style:{height:"100%",overflow:"auto"},children:s.jsx("iframe",{srcDoc:Z,sandbox:"",style:{width:"100%",height:"100%",border:"none",backgroundColor:"#fff"},title:"HTML Preview"})});if(f==="pdf"&&ve)return s.jsx($r,{data:ve,scrollRef:_})}return K==="idle"?s.jsx(Lt,{sessionId:e,onSelect:ae}):null};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"#1a1b26",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",height:"30px",flexShrink:0,backgroundColor:"#16161e",borderBottom:"1px solid #292e42"},children:[s.jsxs("div",{style:{width:`${S}%`,flexShrink:0,display:"flex",alignItems:"center",gap:"4px",padding:"0 8px",minWidth:0},children:[s.jsx("button",{className:"pane-btn",onClick:()=>h(_=>!_),title:"Open document",style:{color:"#7aa2f7"},children:"Open"}),a&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"11px",color:"#565f89",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,cursor:"pointer"},onClick:N,title:T?"Copied!":`Click to copy: ${a}`,children:T?"Copied!":Nt(a)}),s.jsx("button",{className:"pane-btn",onClick:()=>{ue(),k(!0)},title:"Expand document view",children:"⛶"}),s.jsx("button",{className:"pane-btn",onClick:fe,title:"Refresh document",children:"↻"})]})]}),s.jsx("div",{style:{width:"4px",flexShrink:0}}),s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",minWidth:0},children:c?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"#bb9af7",fontWeight:600},children:"Plan"}),z&&s.jsx("span",{style:{fontSize:"10px",color:"#565f89"},children:z.split("/").pop()})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("button",{className:"pane-btn",onClick:he,title:"Refresh PLAN.md",children:"↻"}),s.jsx("button",{className:"pane-btn",onClick:()=>J(!0),title:"Expand plan view",children:"⛶"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{var K;const _=(K=R.current)==null?void 0:K.getSummary();_&&(Y.current=_),d==null||d()},title:"Close Plan mode",children:"×Plan"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=D.current)==null?void 0:_.send()},disabled:!j,title:"Send to terminal (Ctrl+Enter)",style:j?{color:"#9ece6a"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"10px",color:"#414868"},children:"Ctrl+Enter"})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:r,title:"Close Doc panel",children:"×"})]})})]}),s.jsxs("div",{ref:w,className:"plan-panel-body",style:{position:"relative"},children:[s.jsxs("div",{className:"plan-renderer",style:{width:`${S}%`,flexShrink:0},onMouseUp:W,children:[ne(_=>{de.current=_}),y&&s.jsx(Lr,{sessionId:e,onSelect:ae,onClose:()=>h(!1)})]}),s.jsx("div",{className:"plan-divider-h",onMouseDown:O}),s.jsx("div",{className:"plan-editor-wrap",children:c?F?s.jsx(Ye,{label:"Loading PLAN.md..."}):z&&!P&&(p.state.status==="streaming"||p.state.status==="idle")?s.jsx(Ye,{label:"Loading PLAN.md...",percent:p.state.totalSize>0?Math.round(p.state.receivedBytes/p.state.totalSize*100):void 0}):z&&!G?s.jsx(Rt,{ref:R,markdown:P,filePath:z,sessionId:e,onExecute:me}):z&&G?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#565f89",fontSize:12},children:"Editing in expanded view"}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"#565f89",fontSize:13,fontStyle:"italic"},children:"No PLAN.md found in CWD"}),s.jsx("button",{className:"pane-btn",onClick:()=>h(!0),style:{color:"#7aa2f7"},children:"Select file"})]}):s.jsx(Nr,{ref:D,onSend:o,onContentChange:v,sessionId:e,token:t})})]}),g&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsx("span",{style:{fontSize:"14px",color:"#a9b1d6",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a?Nt(a):""}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>{ue(),k(!1)},title:"Close expanded view (ESC)",style:{fontSize:"14px"},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},onMouseUp:W,children:ne(_=>{xe.current=_})})]}),G&&z&&s.jsxs("div",{className:"doc-expanded-overlay",children:[s.jsxs("div",{className:"doc-expanded-header",children:[s.jsxs("span",{style:{fontSize:"14px",color:"#bb9af7"},children:["Plan: ",z.split("/").pop()]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:()=>J(!1),title:"Close expanded view (ESC)",style:{fontSize:"14px"},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(Rt,{ref:R,markdown:P,filePath:z,sessionId:e,onExecute:me,expanded:!0})})]})]})}const ao=100,lo=600,Ce=typeof window<"u"?window.matchMedia(`(max-width: ${lo-1}px)`):null;function co(){const[e,t]=i.useState(()=>(Ce==null?void 0:Ce.matches)??!1);return i.useEffect(()=>{if(!Ce)return;const n=r=>t(r.matches);return Ce.addEventListener("change",n),()=>Ce.removeEventListener("change",n)},[]),e}const uo=i.memo(function({terminal:t}){const n=co(),r=M(R=>R.splitTerminal),o=M(R=>R.token),l=M(R=>R.setTerminalPanelMode),c=i.useRef(null),d=i.useRef(null),[a,u]=i.useState(!1),[f,m]=i.useState(!1),[p,y]=i.useState(0),[h,g]=i.useState(50),k=t.panelMode!=="none",T=t.panelMode==="plan",C=i.useRef(null),S=async R=>{const j=R.target.files;if(!(!j||j.length===0||!o)){m(!0),y(0);try{await br(o,t.id,j,v=>{y(v)})}catch(v){alert(`Upload failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{m(!1),y(0),c.current&&(c.current.value="")}}},w=i.useRef(void 0),O=i.useCallback(R=>{if(d.current){const j=R.replace(/\r?\n/g," ").trimEnd();d.current.sendInput(j),w.current=window.setTimeout(()=>{var v;return(v=d.current)==null?void 0:v.sendInput("\r")},50)}},[]);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const D=i.useCallback(R=>{R.preventDefault();const j=C.current;if(!j)return;const v=j.getBoundingClientRect(),x=v.height;document.body.classList.add("resizing-panes-v");const z=P=>{const L=(P.clientY-v.top)/x*100,F=Math.min(80,Math.max(20,L));g(100-F)},A=()=>{document.body.classList.remove("resizing-panes-v"),document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",A)};document.addEventListener("mousemove",z),document.addEventListener("mouseup",A)},[]);return s.jsxs("div",{ref:C,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0,height:"28px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{display:"inline-block",width:"7px",height:"7px",borderRadius:"50%",backgroundColor:t.connected?"#9ece6a":"#f7768e",boxShadow:t.connected?"0 0 4px rgba(158,206,106,0.5)":"0 0 4px rgba(247,118,142,0.5)"}}),s.jsxs("span",{style:{fontSize:"14px",color:"#565f89"},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:c,type:"file",multiple:!0,style:{display:"none"},onChange:S}),s.jsx("button",{className:"pane-btn",onClick:()=>{var R;return(R=c.current)==null?void 0:R.click()},disabled:f,style:f?{color:"#e0af68"}:void 0,title:f?`Uploading ${p}%`:"Upload files","aria-label":"Upload files",children:f?`${p}%`:"↑"}),s.jsx("button",{className:"pane-btn",onClick:()=>u(R=>!R),style:a?{color:"#7aa2f7"}:void 0,title:"Browse files","aria-label":"Browse files",children:"↓"}),s.jsx("button",{className:`pane-btn${t.panelMode==="chat"?" pane-btn--active":""}`,onClick:()=>l(t.id,t.panelMode==="chat"?"none":"chat"),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${t.panelMode==="plan"?" pane-btn--active":""}`,onClick:()=>l(t.id,t.panelMode==="plan"?"none":"plan"),title:"Toggle Plan annotation mode","aria-label":"Toggle Plan annotation mode",children:"Plan"}),s.jsx("button",{className:"pane-btn",onClick:()=>r(t.id,n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>r(t.id,"vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minHeight:"80px"},children:[s.jsx(xr,{ref:d,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(26, 27, 38, 0.85)",zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"#565f89",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})}),a&&s.jsx(Sr,{sessionId:t.id,onClose:()=>u(!1)})]}),k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:D}),s.jsx("div",{style:{height:`${h}%`,minHeight:ao,flexShrink:0,overflow:"hidden"},children:s.jsx(io,{onSend:O,onClose:()=>l(t.id,"none"),sessionId:t.id,token:o||"",connected:t.connected,onRequestFileStream:R=>{var j;return(j=d.current)==null?void 0:j.requestFileStream(R)},onCancelFileStream:()=>{var R;return(R=d.current)==null?void 0:R.cancelFileStream()},planMode:T,onPlanModeClose:()=>l(t.id,"chat")})})]}),t.error&&s.jsx("div",{style:{padding:"2px 8px",backgroundColor:"#3b2029",borderTop:"1px solid #f7768e",color:"#f7768e",fontSize:"11px",flexShrink:0},children:t.error})]})});class en extends i.Component{constructor(){super(...arguments);ct(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){}render(){var n,r;return this.state.hasError?this.props.inline?s.jsxs("div",{style:{height:"100%",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"#c0caf5",fontFamily:"monospace",padding:"16px"},children:[s.jsx("div",{style:{fontSize:"14px",color:"#f7768e"},children:"Pane crashed"}),s.jsx("div",{style:{fontSize:"12px",color:"#565f89",textAlign:"center"},children:((n=this.state.error)==null?void 0:n.message)||"An unexpected error occurred"}),s.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"#292e42",border:"1px solid #414868",color:"#c0caf5",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):s.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"#1a1b26",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"#c0caf5",fontFamily:"monospace"},children:[s.jsx("div",{style:{fontSize:"18px",color:"#f7768e"},children:"Something went wrong"}),s.jsx("div",{style:{fontSize:"13px",color:"#565f89",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),s.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, #7aa2f7 0%, #bb9af7 100%)",border:"none",color:"#1a1b26",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const fo=4,Mt=10;function po(){const e=M(o=>o.layout),t=M(o=>o.terminalIds.length),n=M(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#1a1b26"},children:s.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed #292e42",color:"#565f89",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(tn,{node:e,canClose:r})})}const tn=i.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(mo,{terminalId:t.terminalId,canClose:n}):s.jsx(ho,{node:t,canClose:n})}),mo=i.memo(function({terminalId:t,canClose:n}){const r=M(o=>o.terminalsMap[t]);return r?s.jsx(en,{inline:!0,children:s.jsx(uo,{terminal:r,canClose:n})}):null}),ho=i.memo(function({node:t,canClose:n}){const r=M(u=>u.setSplitSizes),o=i.useRef(null),l=t.direction==="horizontal",c=i.useRef(t.sizes);c.current=t.sizes;const d=i.useCallback((u,f)=>{f.preventDefault();const m=l?"resizing-panes":"resizing-panes-v";document.body.classList.add(m);const p=l?f.clientX:f.clientY,y=[...c.current],h=o.current,g=l?(h==null?void 0:h.clientWidth)||1:(h==null?void 0:h.clientHeight)||1;let k=null;const T=S=>{k||(k=requestAnimationFrame(()=>{k=null;const D=((l?S.clientX:S.clientY)-p)/g*100,R=y[u]+D,j=y[u+1]-D;if(R>=Mt&&j>=Mt){const v=[...y];v[u]=R,v[u+1]=j,r(t.id,v)}}))},C=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(m),document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",C)};document.addEventListener("mousemove",T),document.addEventListener("mouseup",C)},[l,t.id,r]),a=[];return t.children.forEach((u,f)=>{const m=u.type==="leaf"?u.terminalId:u.id;a.push(s.jsx("div",{style:{flex:`${t.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(tn,{node:u,canClose:n})},m)),f<t.children.length-1&&a.push(s.jsx("div",{onMouseDown:p=>d(f,p),style:{flex:`0 0 ${fo}px`,cursor:l?"col-resize":"row-resize",backgroundColor:"#292e42",transition:"background-color 0.15s"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#7aa2f7"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="#292e42"}},`divider-${t.id}-${f}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:l?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:a})});function xo({tabId:e}){const t=M(x=>x.tabs.find(z=>z.id===e)),n=M(x=>x.activeTabId),r=M(x=>x.switchTab),o=M(x=>x.closeTab),l=M(x=>x.reopenTab),c=M(x=>x.deleteTab),d=M(x=>x.renameTab),a=M(x=>t?t.terminalIds.map(z=>{const A=x.terminalsMap[z];return A?{id:z,connected:A.connected}:{id:z,connected:!1}}):[]),u=M(x=>x.killServerSession),[f,m]=i.useState(!1),[p,y]=i.useState(""),[h,g]=i.useState(!1),k=i.useRef(null);if(!t)return null;const T=n===e,C=t.status==="open",S=()=>{C&&r(e)},w=x=>{C&&(x.stopPropagation(),y(t.name),m(!0),setTimeout(()=>{var z;return(z=k.current)==null?void 0:z.focus()},0))},O=()=>{const x=p.trim();x&&d(e,x),m(!1)},D=x=>{x.stopPropagation(),l(e)},R=x=>{x.stopPropagation(),o(e)},j=async x=>{x.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await c(e)},v=x=>{x.stopPropagation(),g(!h)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:S,style:{padding:"8px 12px",cursor:C?"pointer":"default",borderLeft:T?"3px solid #7aa2f7":"3px solid transparent",backgroundColor:T?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s",opacity:C?1:.5},onMouseEnter:x=>{C&&!T&&(x.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:x=>{T||(x.currentTarget.style.backgroundColor="transparent")},children:[C&&t.terminalIds.length>0&&s.jsx("button",{onClick:v,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:h?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[f?s.jsx("input",{ref:k,value:p,onChange:x=>y(x.target.value),onBlur:O,onKeyDown:x=>{x.key==="Enter"&&O(),x.key==="Escape"&&m(!1)},style:{width:"100%",background:"#1a1b26",border:"1px solid #7aa2f7",color:"#c0caf5",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):s.jsx("div",{onDoubleClick:w,style:{color:"#c0caf5",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",qt(Math.floor(t.createdAt/1e3))]})]}),C?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:R,style:{flexShrink:0},title:"Close tab",children:"×"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:D,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:j,title:"Delete tab",children:"×"})]})]}),C&&h&&a.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:a.map(x=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"#565f89",borderBottom:"1px solid rgba(41, 46, 66, 0.5)",display:"flex",alignItems:"center"},title:`Connected: ${x.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:x.id}),s.jsx("span",{style:{marginLeft:"8px",color:x.connected?"#9ece6a":"#f7768e"},children:x.connected?"●":"○"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:z=>{z.stopPropagation(),window.confirm(`Close terminal "${x.id}"?`)&&u(x.id)},style:{marginLeft:"auto",flexShrink:0},title:"Close terminal",children:"×"})]},x.id))})]})}function yo({sessionId:e,active:t,createdAt:n}){const r=M(d=>d.addTerminal),o=M(d=>d.killServerSession),l=()=>{r("horizontal",e)},c=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};return s.jsxs("div",{onClick:l,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid #292e42",transition:"background-color 0.15s"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"#9ece6a":"#565f89",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"#c0caf5",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"#565f89",fontSize:"11px",marginTop:"2px"},children:qt(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:c,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function bo(){const e=M(a=>a.sidebarOpen),t=M(a=>a.toggleSidebar),n=M(a=>a.fetchSessions),r=M(a=>e?a.serverSessions:[]),o=M(a=>e?a.tabs:[]),l=M(a=>a.terminalIds.length),c=new Set(o.flatMap(a=>a.terminalIds)),d=r.filter(a=>!c.has(a.sessionId));return i.useEffect(()=>{if(!e)return;n();let a=setInterval(n,5e3);const u=()=>{document.hidden?a&&(clearInterval(a),a=null):(n(),a||(a=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",u),()=>{a&&clearInterval(a),document.removeEventListener("visibilitychange",u)}},[e,n]),i.useEffect(()=>{if(!e)return;const a=setTimeout(n,800);return()=>clearTimeout(a)},[l,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"#16161e",borderLeft:e?"1px solid #292e42":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("span",{style:{color:"#7aa2f7",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Sessions"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#565f89",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"#7aa2f7",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid #292e42"},children:"TABS"}),o.length===0?s.jsx("div",{style:{color:"#565f89",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(a=>s.jsx(xo,{tabId:a.id},a.id))]}),d.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.jsx("div",{style:{padding:"8px 12px",color:"#e0af68",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid #292e42"},children:"ORPHANED SESSIONS"}),d.map(a=>s.jsx(yo,{sessionId:a.sessionId,active:a.active,createdAt:a.createdAt},a.sessionId))]})]})]})}const nn=nt.memo(()=>{const e=M(w=>w.tabs),t=M(w=>w.activeTabId),n=M(w=>w.addTab),r=M(w=>w.switchTab),o=M(w=>w.closeTab),l=M(w=>w.renameTab),[c,d]=i.useState(null),[a,u]=i.useState(""),f=i.useRef(null),m=e.filter(w=>w.status==="open");i.useEffect(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const p=w=>{d(w.id),u(w.name)},y=()=>{c&&a.trim()&&l(c,a.trim()),d(null),u("")},h=()=>{d(null),u("")},g=w=>{w.key==="Enter"?y():w.key==="Escape"&&h()},k=w=>{c||r(w)},T=(w,O)=>{w.stopPropagation(),o(O)},C=(w,O)=>{w.button===1&&(w.preventDefault(),o(O))},S=m.length>1;return s.jsxs("div",{className:"tab-bar",children:[m.map(w=>{const O=w.id===t,D=c===w.id,R=w.terminalIds.length;return s.jsx("div",{className:`tab-item ${O?"tab-item--active":""}`,onClick:()=>k(w.id),onDoubleClick:()=>p(w),onMouseDown:j=>C(j,w.id),children:D?s.jsx("input",{ref:f,type:"text",value:a,onChange:j=>u(j.target.value),onBlur:y,onKeyDown:g,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[w.name," ",R>0&&`(${R})`]}),S&&s.jsx("button",{className:"tab-item__close",onClick:j=>T(j,w.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},w.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});nn.displayName="TabBar";function go(){return localStorage.getItem("ai-cli-online-token")}function vo(){const e=M(a=>a.token),t=M(a=>a.setToken),n=M(a=>a.tabs),r=M(a=>a.addTab),o=M(a=>a.toggleSidebar),l=M(a=>a.fontSize),c=M(a=>a.setFontSize),d=M(a=>a.tabsLoading);return i.useEffect(()=>{const a=go();a&&!e&&t(a)},[]),i.useEffect(()=>{e&&!d&&n.filter(a=>a.status==="open").length===0&&r("Default")},[e,d]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"#1a1b26"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"#16161e",borderBottom:"1px solid #292e42",flexShrink:0},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"#7aa2f7",letterSpacing:"0.5px"},children:"AI-Cli Online"})}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>c(l-1),disabled:l<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),s.jsx("span",{style:{fontSize:"11px",color:"#a9b1d6",minWidth:"20px",textAlign:"center"},children:l}),s.jsx("button",{className:"header-btn",onClick:()=>c(l+1),disabled:l>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(So,{}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Sessions Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(po,{})}),s.jsx(bo,{})]}),s.jsx(nn,{})]}):s.jsx(Zn,{})}const wo=[1,2,3,4];function So(){const e=M(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"#414868"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="#9ece6a",n=4):e<150?(t="#e0af68",n=3):e<300?(t="#ff9e64",n=2):(t="#f7768e",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[wo.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"#292e42",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}qe.createRoot(document.getElementById("root")).render(s.jsx(nt.StrictMode,{children:s.jsx(en,{children:s.jsx(vo,{})})}));
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
3
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
4
+ * https://github.com/chjj/term.js
5
+ * @license MIT
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ * THE SOFTWARE.
24
+ *
25
+ * Originally forked from (with the author's permission):
26
+ * Fabrice Bellard's javascript vt100 for jslinux:
27
+ * http://bellard.org/jslinux/
28
+ * Copyright (c) 2011 Fabrice Bellard
29
+ * The original design remains. The terminal itself
30
+ * has been extended to include xterm CSI codes, among
31
+ * other features.
32
+ */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Regular.woff2) format("woff2");font-weight:400;font-style:normal;font-display:swap}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Bold.woff2) format("woff2");font-weight:700;font-style:normal;font-display:swap}*{margin:0;padding:0;box-sizing:border-box}html,body,#root{width:100%;height:100%;overflow:hidden;background-color:#1a1b26;font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}body.resizing-panes,body.resizing-panes *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.session-sidebar{transition:width .2s ease;overflow:hidden;flex-shrink:0;z-index:10;position:relative}body.resizing-panes-v,body.resizing-panes-v *{cursor:row-resize!important;-webkit-user-select:none!important;user-select:none!important}button{transition:all .15s ease;font-family:inherit}button:hover{filter:brightness(1.2)}button:active{transform:scale(.97)}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#292e42;border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#414868}::selection{background:#7aa2f74d;color:#c0caf5}input:focus-visible,button:focus-visible{outline:1px solid #7aa2f7;outline-offset:1px}.header-btn{background:none;border:1px solid #292e42;color:#7aa2f7;padding:3px 10px;border-radius:5px;cursor:pointer;font-size:13px;line-height:1.4;transition:all .15s ease}.header-btn:hover{background:#7aa2f71f;border-color:#7aa2f7;box-shadow:0 0 8px #7aa2f726}.header-btn--muted{color:#565f89;font-size:12px}.header-btn--muted:hover{color:#a9b1d6;border-color:#565f89;background:#565f891a}.pane-btn{background:none;border:none;color:#565f89;cursor:pointer;font-size:14px;line-height:1;padding:3px 6px;border-radius:4px;transition:all .15s ease}.pane-btn:hover{color:#7aa2f7;background:#7aa2f71f}.pane-btn--danger:hover{color:#f7768e;background:#f7768e1f}.login-input{transition:border-color .2s ease,box-shadow .2s ease}.login-input:focus{border-color:#7aa2f7!important;box-shadow:0 0 0 3px #7aa2f726}.login-card{box-shadow:0 8px 32px #0006,0 0 0 1px #7aa2f714;transition:box-shadow .3s ease}.login-submit{transition:all .2s ease}.login-submit:not(:disabled):hover{filter:brightness(1.1);box-shadow:0 4px 12px #7aa2f74d}.md-editor-textarea{flex:1;min-width:0;resize:none;border:none;outline:none;padding:8px 12px;font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;font-size:13px;line-height:1.5;color:#a9b1d6;background-color:#1a1b26;-moz-tab-size:2;tab-size:2}.md-editor-textarea::placeholder{color:#414868;font-style:italic}.md-editor-divider{height:4px;background:#292e42;cursor:row-resize;flex-shrink:0;transition:background .15s ease,box-shadow .15s ease}.md-editor-divider:hover{background:#7aa2f7;box-shadow:0 0 6px #7aa2f766}.pane-btn--active{color:#7aa2f7}.plan-panel-body{display:flex;flex-direction:row;flex:1;min-height:0;overflow:hidden}.plan-renderer{position:relative;overflow:hidden;padding:0;min-width:0;-webkit-user-select:text;user-select:text}.plan-divider-h{width:4px;background:#292e42;cursor:col-resize;flex-shrink:0;transition:background .15s ease,box-shadow .15s ease}.plan-divider-h:hover{background:#7aa2f7;box-shadow:0 0 6px #7aa2f766}.plan-editor-wrap{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}.plan-filename-input{background:#1a1b26;border:1px solid #292e42;color:#a9b1d6;padding:2px 6px;border-radius:3px;font-family:inherit;font-size:11px;width:120px;outline:none;transition:border-color .15s ease}.plan-filename-input:focus{border-color:#7aa2f7}body.resizing-panes-h,body.resizing-panes-h *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.md-preview{color:#a9b1d6;font-size:13px;line-height:1.6;word-wrap:break-word}.md-preview h1{color:#7aa2f7;font-size:1.4em;margin:.6em 0 .3em;padding-bottom:.2em;border-bottom:1px solid #292e42}.md-preview h2{color:#bb9af7;font-size:1.2em;margin:.5em 0 .3em}.md-preview h3{color:#7dcfff;font-size:1.05em;margin:.4em 0 .2em}.md-preview p{margin:.4em 0}.md-preview code{background:#24283b;color:#c0caf5;padding:1px 4px;border-radius:3px;font-size:.9em;font-family:JetBrains Mono,monospace}.md-preview pre{background:#24283b;border:1px solid #292e42;border-radius:4px;padding:10px 12px;overflow-x:auto;margin:.5em 0}.md-preview pre code{background:none;padding:0;border-radius:0}.md-preview blockquote{border-left:3px solid #7aa2f7;padding:2px 12px;margin:.4em 0;color:#565f89}.md-preview ul,.md-preview ol{padding-left:1.5em;margin:.3em 0}.md-preview li{margin:.15em 0}.md-preview table{border-collapse:collapse;width:100%;margin:.5em 0;font-size:12px}.md-preview th,.md-preview td{border:1px solid #292e42;padding:4px 8px;text-align:left}.md-preview th{background:#24283b;color:#7aa2f7;font-weight:600}.md-preview a{color:#7aa2f7;text-decoration:none}.md-preview a:hover{text-decoration:underline}.md-preview hr{border:none;border-top:1px solid #292e42;margin:.6em 0}.slash-dropdown{flex-shrink:0;max-height:200px;overflow-y:auto;background:#1e2030;border-bottom:1px solid #292e42;z-index:10;font-size:13px}.slash-item{display:flex;align-items:center;gap:10px;padding:6px 12px;cursor:pointer;transition:background .12s ease}.slash-item:hover,.slash-item--active{background:#292e42}.slash-cmd{color:#7aa2f7;font-weight:600;min-width:120px;font-family:JetBrains Mono,monospace}.slash-desc{color:#bb9af7;font-size:11px}.file-dropdown{flex-shrink:0;max-height:180px;overflow-y:auto;background:#1e2030;border-bottom:1px solid #292e42;z-index:10;font-size:12px}.file-item{display:flex;align-items:center;gap:8px;padding:5px 10px;cursor:pointer;transition:background .1s ease}.file-item:hover,.file-item--active{background:#292e42}.file-loading{color:#565f89;cursor:default}.file-icon{flex-shrink:0;width:16px;text-align:center;font-size:13px}.file-name{color:#c0caf5;font-family:JetBrains Mono,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.history-dropdown{flex-shrink:0;max-height:260px;overflow-y:auto;background:#1e2030;border-bottom:1px solid #292e42;z-index:10;font-size:12px}.history-item{display:flex;align-items:flex-start;gap:8px;padding:6px 10px;cursor:pointer;transition:background .1s ease;position:relative}.history-item:hover,.history-item--active{background:#292e42}.history-empty{color:#565f89;cursor:default;justify-content:center;padding:12px}.history-text{flex:1;color:#c0caf5;font-family:JetBrains Mono,monospace;white-space:pre-wrap;overflow-wrap:break-word;line-height:1.4}.history-time{flex-shrink:0;color:#565f89;font-size:10px;white-space:nowrap;margin-top:2px}.history-delete{flex-shrink:0;background:none;border:none;color:#565f89;cursor:pointer;font-size:14px;padding:0 2px;line-height:1;opacity:0;transition:opacity .1s ease,color .1s ease}.history-item:hover .history-delete,.history-item--active .history-delete{opacity:1}.history-delete:hover{color:#f7768e}.tab-bar{display:flex;align-items:center;padding:0 10px;height:32px;background:#16161e;border-top:1px solid #292e42;flex-shrink:0;overflow-x:auto;gap:3px}.tab-bar::-webkit-scrollbar{height:0}.tab-item{display:flex;align-items:center;gap:6px;padding:4px 12px;font-size:13px;color:#565f89;cursor:pointer;border-bottom:2px solid transparent;white-space:nowrap;transition:color .15s ease,border-color .15s ease,background .15s ease,box-shadow .15s ease;border-radius:5px 5px 0 0;-webkit-user-select:none;user-select:none;flex-shrink:0}.tab-item:hover{color:#a9b1d6;background:#7aa2f70f}.tab-item--active{color:#c0caf5;border-bottom-color:#7aa2f7;background:#7aa2f71a;box-shadow:inset 0 -1px #7aa2f7}.tab-item__name{max-width:150px;overflow:hidden;text-overflow:ellipsis}.tab-item__count{font-size:10px;color:#414868}.tab-item__close{font-size:14px;line-height:1;color:inherit;opacity:0;background:none;border:none;cursor:pointer;padding:0 2px;border-radius:3px;transition:opacity .1s ease}.tab-item:hover .tab-item__close{opacity:.5}.tab-item__close:hover{opacity:1!important;color:#f7768e;background:#f7768e1a}.tab-item__rename-input{background:transparent;border:1px solid #7aa2f7;color:#c0caf5;font-size:13px;font-family:inherit;padding:0 6px;border-radius:3px;outline:none;width:100px}.tab-bar-add{background:none;border:1px solid transparent;color:#565f89;font-size:18px;line-height:1;padding:2px 8px;border-radius:5px;cursor:pointer;margin-left:4px;flex-shrink:0}.tab-bar-add:hover{color:#7aa2f7;border-color:#292e42;background:#7aa2f71a}.pdf-renderer{height:100%;overflow-y:auto;padding:12px;background:#1a1b26}.pdf-renderer canvas{display:block;margin:0 auto 8px;max-width:100%}.doc-expanded-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:100;background:#1a1b26;display:flex;flex-direction:column}.doc-expanded-header{display:flex;align-items:center;justify-content:space-between;padding:0 14px;height:34px;flex-shrink:0;background:#16161e;border-bottom:1px solid #292e42}.md-editor-actions{display:flex;align-items:center;gap:8px;padding:4px 8px;flex-shrink:0;background:#16161e;border-top:1px solid #292e42}.plan-anno-toolbar{display:flex;align-items:center;gap:6px;padding:3px 10px;height:32px;flex-shrink:0;background:#16161e;border-bottom:1px solid #292e42}.plan-anno-content{-webkit-user-select:text;user-select:text}.plan-insert-zone{position:relative;min-height:12px}.plan-insert-btn{display:none;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:20px;height:20px;border-radius:50%;border:1px solid #414868;background:#1e2030;color:#7aa2f7;font-size:15px;cursor:pointer;padding:0;z-index:2;transition:background .12s ease,border-color .12s ease,transform .12s ease;align-items:center;justify-content:center}.plan-insert-zone:hover .plan-insert-btn,.plan-insert-zone--empty .plan-insert-btn{display:flex}.plan-insert-zone--empty{min-height:48px}.plan-insert-zone--empty .plan-insert-btn{width:24px;height:24px;font-size:16px;border-color:#565f89}.plan-insert-btn:hover{background:#292e42;border-color:#7aa2f7;transform:translate(-50%,-50%) scale(1.15)}.plan-annotation-card{display:flex;align-items:flex-start;gap:6px;padding:6px 10px;margin:4px 0;background:#e0af681f;border-left:3px solid #e0af68;border-radius:0 4px 4px 0}.plan-annotation-card--editing{border-left-color:#7aa2f7;background:#7aa2f70f}.plan-annotation-textarea{flex:1;min-height:36px;resize:vertical;border:1px solid #292e42;border-radius:3px;background:#1a1b26;color:#a9b1d6;font-family:JetBrains Mono,monospace;font-size:12px;padding:4px 6px;outline:none;transition:border-color .15s ease}.plan-annotation-textarea:focus{border-color:#7aa2f7}.plan-annotation-textarea::placeholder{color:#414868;font-style:italic}.plan-deletion-card{display:flex;align-items:center;gap:6px;padding:2px 8px;margin:2px 0;background:#f7768e0f;border-left:3px solid #f7768e;border-radius:0 4px 4px 0;font-size:11px}.plan-delete-float{position:absolute;z-index:1000;width:24px;height:24px;border-radius:50%;border:1.5px solid #f7768e;background:#2a1520;color:#f7768e;font-size:16px;font-weight:700;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 10px #f7768e40,0 1px 4px #0006;transition:background .12s ease,transform .12s ease}.plan-delete-float:hover{background:#f7768e33;transform:scale(1.15)}.plan-block--deleted{border-left:3px solid rgba(247,118,142,.5);padding-left:8px;border-radius:2px;position:relative}.mermaid-diagram{margin:8px 0;padding:12px;background:#1e2030;border:1px solid #292e42;border-radius:6px;overflow-x:auto}.mermaid-diagram svg{display:block;margin:0 auto;max-width:100%;height:auto}.mermaid-error{border-left:3px solid #f7768e;padding-left:8px}.mermaid-error__msg{color:#f7768e;font-size:11px;margin-top:4px}.pane-btn--sm{font-size:11px;flex-shrink:0}
@@ -7,11 +7,11 @@
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-CwCy8bpB.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-Ciwt6-Lg.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">
14
- <link rel="stylesheet" crossorigin href="/assets/index-CcvD-9RC.css">
14
+ <link rel="stylesheet" crossorigin href="/assets/index-ClJzpPT-.css">
15
15
  </head>
16
16
  <body>
17
17
  <div id="root"></div>
package/web/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-web",
3
- "version": "2.2.5",
3
+ "version": "2.4.0",
4
4
  "description": "CLI-Online Web Frontend",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -1,32 +0,0 @@
1
- /**
2
- * Copyright (c) 2014 The xterm.js authors. All rights reserved.
3
- * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
4
- * https://github.com/chjj/term.js
5
- * @license MIT
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in
15
- * all copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
- * THE SOFTWARE.
24
- *
25
- * Originally forked from (with the author's permission):
26
- * Fabrice Bellard's javascript vt100 for jslinux:
27
- * http://bellard.org/jslinux/
28
- * Copyright (c) 2011 Fabrice Bellard
29
- * The original design remains. The terminal itself
30
- * has been extended to include xterm CSI codes, among
31
- * other features.
32
- */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Regular.woff2) format("woff2");font-weight:400;font-style:normal;font-display:swap}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Bold.woff2) format("woff2");font-weight:700;font-style:normal;font-display:swap}*{margin:0;padding:0;box-sizing:border-box}html,body,#root{width:100%;height:100%;overflow:hidden;background-color:#1a1b26;font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}body.resizing-panes,body.resizing-panes *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.session-sidebar{transition:width .2s ease;overflow:hidden;flex-shrink:0;z-index:10;position:relative}body.resizing-panes-v,body.resizing-panes-v *{cursor:row-resize!important;-webkit-user-select:none!important;user-select:none!important}button{transition:all .15s ease;font-family:inherit}button:hover{filter:brightness(1.2)}button:active{transform:scale(.97)}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#292e42;border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#414868}::selection{background:#7aa2f74d;color:#c0caf5}input:focus-visible,button:focus-visible{outline:1px solid #7aa2f7;outline-offset:1px}.header-btn{background:none;border:1px solid #292e42;color:#7aa2f7;padding:2px 10px;border-radius:5px;cursor:pointer;font-size:13px;line-height:1.4;transition:all .15s ease}.header-btn:hover{background:#7aa2f71a;border-color:#7aa2f7}.header-btn--muted{color:#565f89;font-size:12px}.header-btn--muted:hover{color:#a9b1d6;border-color:#565f89;background:#565f891a}.pane-btn{background:none;border:none;color:#565f89;cursor:pointer;font-size:14px;line-height:1;padding:2px 4px;border-radius:3px;transition:all .15s ease}.pane-btn:hover{color:#7aa2f7;background:#7aa2f71a}.pane-btn--danger:hover{color:#f7768e;background:#f7768e1a}.login-input{transition:border-color .2s ease,box-shadow .2s ease}.login-input:focus{border-color:#7aa2f7!important;box-shadow:0 0 0 3px #7aa2f726}.login-card{box-shadow:0 8px 32px #0006,0 0 0 1px #7aa2f714;transition:box-shadow .3s ease}.login-submit{transition:all .2s ease}.login-submit:not(:disabled):hover{filter:brightness(1.1);box-shadow:0 4px 12px #7aa2f74d}.md-editor-textarea{flex:1;min-width:0;resize:none;border:none;outline:none;padding:8px 12px;font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;font-size:13px;line-height:1.5;color:#a9b1d6;background-color:#1a1b26;-moz-tab-size:2;tab-size:2}.md-editor-textarea::placeholder{color:#414868;font-style:italic}.md-editor-divider{height:4px;background:#292e42;cursor:row-resize;flex-shrink:0;transition:background .15s ease}.md-editor-divider:hover{background:#7aa2f7}.pane-btn--active{color:#7aa2f7}.plan-panel-body{display:flex;flex-direction:row;flex:1;min-height:0;overflow:hidden}.plan-renderer{position:relative;overflow:hidden;padding:0;min-width:0;-webkit-user-select:text;user-select:text}.plan-divider-h{width:4px;background:#292e42;cursor:col-resize;flex-shrink:0;transition:background .15s ease}.plan-divider-h:hover{background:#7aa2f7}.plan-editor-wrap{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}.plan-filename-input{background:#1a1b26;border:1px solid #292e42;color:#a9b1d6;padding:2px 6px;border-radius:3px;font-family:inherit;font-size:11px;width:120px;outline:none;transition:border-color .15s ease}.plan-filename-input:focus{border-color:#7aa2f7}body.resizing-panes-h,body.resizing-panes-h *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.md-preview{color:#a9b1d6;font-size:13px;line-height:1.6;word-wrap:break-word}.md-preview h1{color:#7aa2f7;font-size:1.4em;margin:.6em 0 .3em;padding-bottom:.2em;border-bottom:1px solid #292e42}.md-preview h2{color:#bb9af7;font-size:1.2em;margin:.5em 0 .3em}.md-preview h3{color:#7dcfff;font-size:1.05em;margin:.4em 0 .2em}.md-preview p{margin:.4em 0}.md-preview code{background:#24283b;color:#c0caf5;padding:1px 4px;border-radius:3px;font-size:.9em;font-family:JetBrains Mono,monospace}.md-preview pre{background:#24283b;border:1px solid #292e42;border-radius:4px;padding:10px 12px;overflow-x:auto;margin:.5em 0}.md-preview pre code{background:none;padding:0;border-radius:0}.md-preview blockquote{border-left:3px solid #7aa2f7;padding:2px 12px;margin:.4em 0;color:#565f89}.md-preview ul,.md-preview ol{padding-left:1.5em;margin:.3em 0}.md-preview li{margin:.15em 0}.md-preview table{border-collapse:collapse;width:100%;margin:.5em 0;font-size:12px}.md-preview th,.md-preview td{border:1px solid #292e42;padding:4px 8px;text-align:left}.md-preview th{background:#24283b;color:#7aa2f7;font-weight:600}.md-preview a{color:#7aa2f7;text-decoration:none}.md-preview a:hover{text-decoration:underline}.md-preview hr{border:none;border-top:1px solid #292e42;margin:.6em 0}.slash-dropdown{flex-shrink:0;max-height:180px;overflow-y:auto;background:#1e2030;border-bottom:1px solid #292e42;z-index:10;font-size:12px}.slash-item{display:flex;align-items:center;gap:8px;padding:5px 10px;cursor:pointer;transition:background .1s ease}.slash-item:hover,.slash-item--active{background:#292e42}.slash-cmd{color:#7aa2f7;font-weight:600;min-width:120px;font-family:JetBrains Mono,monospace}.slash-desc{color:#565f89;font-size:11px}.file-dropdown{flex-shrink:0;max-height:180px;overflow-y:auto;background:#1e2030;border-bottom:1px solid #292e42;z-index:10;font-size:12px}.file-item{display:flex;align-items:center;gap:8px;padding:5px 10px;cursor:pointer;transition:background .1s ease}.file-item:hover,.file-item--active{background:#292e42}.file-loading{color:#565f89;cursor:default}.file-icon{flex-shrink:0;width:16px;text-align:center;font-size:13px}.file-name{color:#c0caf5;font-family:JetBrains Mono,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tab-bar{display:flex;align-items:center;padding:0 8px;height:28px;background:#1a1b26;border-top:1px solid #292e42;flex-shrink:0;overflow-x:auto;gap:2px}.tab-bar::-webkit-scrollbar{height:0}.tab-item{display:flex;align-items:center;gap:6px;padding:2px 10px;font-size:12px;color:#565f89;cursor:pointer;border-bottom:2px solid transparent;white-space:nowrap;transition:color .15s ease,border-color .15s ease,background .15s ease;border-radius:4px 4px 0 0;-webkit-user-select:none;user-select:none;flex-shrink:0}.tab-item:hover{color:#a9b1d6;background:#7aa2f70d}.tab-item--active{color:#c0caf5;border-bottom-color:#7aa2f7;background:#7aa2f714}.tab-item__name{max-width:150px;overflow:hidden;text-overflow:ellipsis}.tab-item__count{font-size:10px;color:#414868}.tab-item__close{font-size:14px;line-height:1;color:inherit;opacity:0;background:none;border:none;cursor:pointer;padding:0 2px;border-radius:3px;transition:opacity .1s ease}.tab-item:hover .tab-item__close{opacity:.5}.tab-item__close:hover{opacity:1!important;color:#f7768e;background:#f7768e1a}.tab-item__rename-input{background:transparent;border:1px solid #7aa2f7;color:#c0caf5;font-size:12px;font-family:inherit;padding:0 4px;border-radius:2px;outline:none;width:100px}.tab-bar-add{background:none;border:1px solid transparent;color:#565f89;font-size:16px;line-height:1;padding:2px 8px;border-radius:4px;cursor:pointer;margin-left:4px;flex-shrink:0}.tab-bar-add:hover{color:#7aa2f7;border-color:#292e42;background:#7aa2f71a}.pdf-renderer{height:100%;overflow-y:auto;padding:12px;background:#1a1b26}.pdf-renderer canvas{display:block;margin:0 auto 8px;max-width:100%}.doc-expanded-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:100;background:#1a1b26;display:flex;flex-direction:column}.doc-expanded-header{display:flex;align-items:center;justify-content:space-between;padding:0 12px;height:32px;flex-shrink:0;background:#16161e;border-bottom:1px solid #292e42}.md-editor-actions{display:flex;align-items:center;gap:8px;padding:4px 8px;flex-shrink:0;background:#16161e;border-top:1px solid #292e42}
@@ -1,28 +0,0 @@
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,{})})}));