ai-cli-online 3.0.6 → 3.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/install-service.sh +2 -3
- package/package.json +1 -1
- package/server/dist/index.js +30 -23
- package/server/dist/routes/files.js +4 -2
- package/server/dist/tmux.d.ts +13 -1
- package/server/dist/tmux.js +95 -7
- package/server/package.json +1 -1
- package/shared/package.json +1 -1
- package/web/dist/assets/index-BHAsZRWj.js +32 -0
- package/web/dist/index.html +1 -1
- package/web/package.json +1 -1
- package/web/dist/assets/index-D4ZKzY3K.js +0 -32
package/install-service.sh
CHANGED
package/package.json
CHANGED
package/server/dist/index.js
CHANGED
|
@@ -10,7 +10,7 @@ import { existsSync, readFileSync } from 'fs';
|
|
|
10
10
|
import { join, dirname } from 'path';
|
|
11
11
|
import { fileURLToPath } from 'url';
|
|
12
12
|
import { setupWebSocket, clearWsIntervals } from './websocket.js';
|
|
13
|
-
import { isTmuxAvailable,
|
|
13
|
+
import { isTmuxAvailable, cleanupOrphanedProcesses } from './tmux.js';
|
|
14
14
|
import { cleanupOldDrafts, cleanupOldAnnotations, closeDb } from './db.js';
|
|
15
15
|
import { safeTokenCompare } from './auth.js';
|
|
16
16
|
// Route modules
|
|
@@ -28,7 +28,6 @@ const HTTPS_ENABLED = process.env.HTTPS_ENABLED !== 'false';
|
|
|
28
28
|
const CORS_ORIGIN = process.env.CORS_ORIGIN || '';
|
|
29
29
|
const TRUST_PROXY = process.env.TRUST_PROXY || '';
|
|
30
30
|
const MAX_CONNECTIONS = parseInt(process.env.MAX_CONNECTIONS || '10', 10);
|
|
31
|
-
const SESSION_TTL_HOURS = parseInt(process.env.SESSION_TTL_HOURS || '24', 10);
|
|
32
31
|
const RATE_LIMIT_READ = parseInt(process.env.RATE_LIMIT_READ || '300', 10);
|
|
33
32
|
const RATE_LIMIT_WRITE = parseInt(process.env.RATE_LIMIT_WRITE || '100', 10);
|
|
34
33
|
const CERT_PATH = join(__dirname, '../certs/server.crt');
|
|
@@ -159,7 +158,13 @@ async function main() {
|
|
|
159
158
|
console.log('='.repeat(50));
|
|
160
159
|
console.log('');
|
|
161
160
|
});
|
|
162
|
-
// ---
|
|
161
|
+
// --- Startup cleanup ---
|
|
162
|
+
try {
|
|
163
|
+
await cleanupOrphanedProcesses();
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
console.error('[startup:orphans]', e);
|
|
167
|
+
}
|
|
163
168
|
try {
|
|
164
169
|
const purged = cleanupOldDrafts(7);
|
|
165
170
|
if (purged > 0)
|
|
@@ -168,26 +173,28 @@ async function main() {
|
|
|
168
173
|
catch (e) {
|
|
169
174
|
console.error('[startup:drafts]', e);
|
|
170
175
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
176
|
+
const CLEANUP_INTERVAL = 60 * 60 * 1000;
|
|
177
|
+
const cleanupTimer = setInterval(async () => {
|
|
178
|
+
try {
|
|
179
|
+
await cleanupOrphanedProcesses();
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
console.error('[cleanup:orphans]', e);
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
cleanupOldDrafts(7);
|
|
186
|
+
}
|
|
187
|
+
catch (e) {
|
|
188
|
+
console.error('[cleanup:drafts]', e);
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
cleanupOldAnnotations(7);
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
console.error('[cleanup:annotations]', e);
|
|
195
|
+
}
|
|
196
|
+
}, CLEANUP_INTERVAL);
|
|
197
|
+
console.log('Sessions persist until manually closed (cleanup every hour)');
|
|
191
198
|
// --- Graceful shutdown ---
|
|
192
199
|
const shutdown = () => {
|
|
193
200
|
console.log('\n[shutdown] Closing server...');
|
|
@@ -4,12 +4,14 @@ import { createReadStream, mkdirSync } from 'fs';
|
|
|
4
4
|
import { copyFile, unlink, stat, mkdir, readFile, writeFile, rm } from 'fs/promises';
|
|
5
5
|
import { join, dirname, basename, extname } from 'path';
|
|
6
6
|
import { spawn } from 'child_process';
|
|
7
|
+
import { fileURLToPath } from 'url';
|
|
7
8
|
import { resolveSession } from '../middleware/auth.js';
|
|
8
9
|
import { getCwd } from '../tmux.js';
|
|
9
10
|
import { listFiles, validatePath, validatePathNoSymlink, validateNewPath, MAX_DOWNLOAD_SIZE, MAX_UPLOAD_SIZE } from '../files.js';
|
|
10
11
|
const router = Router();
|
|
11
|
-
// Multer setup for file uploads
|
|
12
|
-
const
|
|
12
|
+
// Multer setup for file uploads — use server/data/ instead of /tmp to survive tmpfs cleanup
|
|
13
|
+
const __files_dirname = dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const UPLOAD_TMP_DIR = join(__files_dirname, '../../data/uploads');
|
|
13
15
|
mkdirSync(UPLOAD_TMP_DIR, { recursive: true, mode: 0o700 });
|
|
14
16
|
const upload = multer({
|
|
15
17
|
dest: UPLOAD_TMP_DIR,
|
package/server/dist/tmux.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export declare function resizeSession(name: string, cols: number, rows: number):
|
|
|
34
34
|
export declare function killSession(name: string): Promise<void>;
|
|
35
35
|
/** List all tmux sessions belonging to a given token */
|
|
36
36
|
export declare function listSessions(token: string): Promise<TmuxSessionInfo[]>;
|
|
37
|
-
/** Clean up idle tmux sessions
|
|
37
|
+
/** Clean up idle tmux sessions whose last activity exceeds the given TTL (hours) */
|
|
38
38
|
export declare function cleanupStaleSessions(ttlHours: number): Promise<void>;
|
|
39
39
|
/** 获取 tmux session 当前活动 pane 的工作目录 */
|
|
40
40
|
export declare function getCwd(sessionName: string): Promise<string>;
|
|
@@ -42,3 +42,15 @@ export declare function getCwd(sessionName: string): Promise<string>;
|
|
|
42
42
|
export declare function getPaneCommand(sessionName: string): Promise<string>;
|
|
43
43
|
/** Check if tmux is available on the system (sync — startup only) */
|
|
44
44
|
export declare function isTmuxAvailable(): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Clean up orphaned process trees from dead tmux sessions.
|
|
47
|
+
*
|
|
48
|
+
* With KillMode=process, tmux child processes (bash → claude → plugins) survive
|
|
49
|
+
* service restarts. When a tmux session is killed (by cleanup or manually), its
|
|
50
|
+
* child processes may keep running as orphans. This function identifies tmux server
|
|
51
|
+
* processes in the service cgroup whose sessions no longer exist and kills their
|
|
52
|
+
* entire process trees.
|
|
53
|
+
*
|
|
54
|
+
* Called once at startup.
|
|
55
|
+
*/
|
|
56
|
+
export declare function cleanupOrphanedProcesses(): Promise<void>;
|
package/server/dist/tmux.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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';
|
|
4
|
+
import { mkdirSync, existsSync } from 'fs';
|
|
5
5
|
import { join } from 'path';
|
|
6
6
|
const _execFile = promisify(execFileCb);
|
|
7
7
|
const EXEC_TIMEOUT = 5000; // 5s safety timeout for all tmux calls
|
|
@@ -147,14 +147,14 @@ export async function listSessions(token) {
|
|
|
147
147
|
return [];
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
|
-
/** Clean up idle tmux sessions
|
|
150
|
+
/** Clean up idle tmux sessions whose last activity exceeds the given TTL (hours) */
|
|
151
151
|
export async function cleanupStaleSessions(ttlHours) {
|
|
152
152
|
const cutoff = Math.floor(Date.now() / 1000) - ttlHours * 3600;
|
|
153
153
|
try {
|
|
154
154
|
const { stdout } = await tmuxExec([
|
|
155
155
|
'list-sessions',
|
|
156
156
|
'-F',
|
|
157
|
-
'#{session_name}:#{
|
|
157
|
+
'#{session_name}:#{session_activity}:#{session_attached}',
|
|
158
158
|
], { encoding: 'utf-8' });
|
|
159
159
|
const staleNames = [];
|
|
160
160
|
for (const line of stdout.trim().split('\n')) {
|
|
@@ -168,14 +168,14 @@ export async function cleanupStaleSessions(ttlHours) {
|
|
|
168
168
|
const secondLastColon = rest.lastIndexOf(':');
|
|
169
169
|
if (secondLastColon === -1)
|
|
170
170
|
continue;
|
|
171
|
-
const
|
|
171
|
+
const lastActivity = parseInt(rest.slice(secondLastColon + 1), 10);
|
|
172
172
|
const name = rest.slice(0, secondLastColon);
|
|
173
173
|
if (!name.startsWith('ai-cli-online-'))
|
|
174
174
|
continue;
|
|
175
175
|
if (attached > 0)
|
|
176
176
|
continue;
|
|
177
|
-
if (
|
|
178
|
-
console.log(`[tmux] Cleaning up stale session: ${name} (
|
|
177
|
+
if (lastActivity < cutoff) {
|
|
178
|
+
console.log(`[tmux] Cleaning up stale session: ${name} (last activity ${new Date(lastActivity * 1000).toISOString()})`);
|
|
179
179
|
staleNames.push(name);
|
|
180
180
|
}
|
|
181
181
|
}
|
|
@@ -191,7 +191,16 @@ export async function getCwd(sessionName) {
|
|
|
191
191
|
const { stdout } = await tmuxExec([
|
|
192
192
|
'list-panes', '-t', `=${sessionName}`, '-F', '#{pane_current_path}',
|
|
193
193
|
], { encoding: 'utf-8' });
|
|
194
|
-
|
|
194
|
+
let cwd = stdout.trim();
|
|
195
|
+
// tmux appends " (deleted)" when the CWD directory has been removed (e.g. /tmp after cleanup)
|
|
196
|
+
if (cwd.endsWith(' (deleted)')) {
|
|
197
|
+
cwd = cwd.slice(0, -' (deleted)'.length);
|
|
198
|
+
}
|
|
199
|
+
// Fall back to DEFAULT_WORKING_DIR or HOME if the path no longer exists
|
|
200
|
+
if (!cwd || !existsSync(cwd)) {
|
|
201
|
+
cwd = process.env.DEFAULT_WORKING_DIR || process.env.HOME || '/root';
|
|
202
|
+
}
|
|
203
|
+
return cwd;
|
|
195
204
|
}
|
|
196
205
|
/** 获取 tmux pane 当前运行的命令名称 */
|
|
197
206
|
export async function getPaneCommand(sessionName) {
|
|
@@ -215,3 +224,82 @@ export function isTmuxAvailable() {
|
|
|
215
224
|
return false;
|
|
216
225
|
}
|
|
217
226
|
}
|
|
227
|
+
/**
|
|
228
|
+
* Clean up orphaned process trees from dead tmux sessions.
|
|
229
|
+
*
|
|
230
|
+
* With KillMode=process, tmux child processes (bash → claude → plugins) survive
|
|
231
|
+
* service restarts. When a tmux session is killed (by cleanup or manually), its
|
|
232
|
+
* child processes may keep running as orphans. This function identifies tmux server
|
|
233
|
+
* processes in the service cgroup whose sessions no longer exist and kills their
|
|
234
|
+
* entire process trees.
|
|
235
|
+
*
|
|
236
|
+
* Called once at startup.
|
|
237
|
+
*/
|
|
238
|
+
export async function cleanupOrphanedProcesses() {
|
|
239
|
+
// Get live session names from the socket-based tmux server
|
|
240
|
+
const liveSessions = new Set();
|
|
241
|
+
try {
|
|
242
|
+
const { stdout } = await tmuxExec([
|
|
243
|
+
'list-sessions', '-F', '#{session_name}',
|
|
244
|
+
], { encoding: 'utf-8' });
|
|
245
|
+
for (const line of stdout.trim().split('\n')) {
|
|
246
|
+
if (line)
|
|
247
|
+
liveSessions.add(line);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
// tmux server not running — nothing to clean
|
|
252
|
+
}
|
|
253
|
+
// Find tmux server processes that belong to ai-cli-online but manage dead sessions.
|
|
254
|
+
// These show up as `tmux new-session -d -s <session-name>` in /proc/*/cmdline.
|
|
255
|
+
try {
|
|
256
|
+
const { stdout } = await _execFile('ps', [
|
|
257
|
+
'-eo', 'pid,ppid,args', '--no-headers',
|
|
258
|
+
], { encoding: 'utf-8', timeout: EXEC_TIMEOUT });
|
|
259
|
+
const orphanPids = [];
|
|
260
|
+
for (const line of stdout.trim().split('\n')) {
|
|
261
|
+
if (!line)
|
|
262
|
+
continue;
|
|
263
|
+
const match = line.match(/^\s*(\d+)\s+\d+\s+tmux.*new-session\s+-d\s+-s\s+(ai-cli-online-\S+)/);
|
|
264
|
+
if (!match)
|
|
265
|
+
continue;
|
|
266
|
+
const pid = parseInt(match[1], 10);
|
|
267
|
+
const sessionName = match[2];
|
|
268
|
+
if (!liveSessions.has(sessionName)) {
|
|
269
|
+
orphanPids.push(pid);
|
|
270
|
+
console.log(`[cleanup] Found orphaned tmux process tree: PID ${pid}, dead session: ${sessionName}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
for (const pid of orphanPids) {
|
|
274
|
+
try {
|
|
275
|
+
// Kill the entire process group/tree rooted at this tmux server
|
|
276
|
+
process.kill(-pid, 'SIGTERM');
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// Process group kill failed, try individual kill
|
|
280
|
+
try {
|
|
281
|
+
process.kill(pid, 'SIGTERM');
|
|
282
|
+
}
|
|
283
|
+
catch { /* already gone */ }
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (orphanPids.length > 0) {
|
|
287
|
+
// Give processes time to exit gracefully, then force-kill survivors
|
|
288
|
+
await new Promise((resolve) => setTimeout(resolve, 2000));
|
|
289
|
+
for (const pid of orphanPids) {
|
|
290
|
+
try {
|
|
291
|
+
process.kill(-pid, 'SIGKILL');
|
|
292
|
+
}
|
|
293
|
+
catch { /* already gone */ }
|
|
294
|
+
try {
|
|
295
|
+
process.kill(pid, 'SIGKILL');
|
|
296
|
+
}
|
|
297
|
+
catch { /* already gone */ }
|
|
298
|
+
}
|
|
299
|
+
console.log(`[cleanup] Cleaned up ${orphanPids.length} orphaned tmux process tree(s)`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
catch (err) {
|
|
303
|
+
console.error('[cleanup] Failed to scan for orphaned processes:', err);
|
|
304
|
+
}
|
|
305
|
+
}
|
package/server/package.json
CHANGED
package/shared/package.json
CHANGED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
var Kn=Object.defineProperty;var Jn=(t,e,n)=>e in t?Kn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var $t=(t,e,n)=>Jn(t,typeof e!="symbol"?e+"":e,n);import{r as a,a as Vn,g as Gn,R as It}from"./react-vendor-BCIvbQoU.js";import{D as hn,o as gn,L as qn,x as bn}from"./terminal-DnNpv9tw.js";import{p as St,g as xn}from"./markdown-CU76q5qk.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var yn={exports:{}},ct={};/**
|
|
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 Yn=a,Xn=Symbol.for("react.element"),Zn=Symbol.for("react.fragment"),Qn=Object.prototype.hasOwnProperty,er=Yn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,tr={key:!0,ref:!0,__self:!0,__source:!0};function vn(t,e,n){var r,s={},i=null,l=null;n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),e.ref!==void 0&&(l=e.ref);for(r in e)Qn.call(e,r)&&!tr.hasOwnProperty(r)&&(s[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)s[r]===void 0&&(s[r]=e[r]);return{$$typeof:Xn,type:t,key:i,ref:l,props:s,_owner:er.current}}ct.Fragment=Zn;ct.jsx=vn;ct.jsxs=vn;yn.exports=ct;var o=yn.exports,kt={},_t=Vn;kt.createRoot=_t.createRoot,kt.hydrateRoot=_t.hydrateRoot;const nr={},Ot=t=>{let e;const n=new Set,r=(f,u)=>{const h=typeof f=="function"?f(e):f;if(!Object.is(h,e)){const g=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),n.forEach(b=>b(e,g))}},s=()=>e,p={setState:r,getState:s,getInitialState:()=>c,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},c=e=t(r,s,p);return p},rr=t=>t?Ot(t):Ot;var wn={exports:{}},Sn={},kn={exports:{}},Tn={};/**
|
|
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 Ue=a;function sr(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var ar=typeof Object.is=="function"?Object.is:sr,or=Ue.useState,ir=Ue.useEffect,lr=Ue.useLayoutEffect,cr=Ue.useDebugValue;function dr(t,e){var n=e(),r=or({inst:{value:n,getSnapshot:e}}),s=r[0].inst,i=r[1];return lr(function(){s.value=n,s.getSnapshot=e,xt(s)&&i({inst:s})},[t,n,e]),ir(function(){return xt(s)&&i({inst:s}),t(function(){xt(s)&&i({inst:s})})},[t]),cr(n),n}function xt(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!ar(t,n)}catch{return!0}}function ur(t,e){return e()}var fr=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?ur:dr;Tn.useSyncExternalStore=Ue.useSyncExternalStore!==void 0?Ue.useSyncExternalStore:fr;kn.exports=Tn;var pr=kn.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 dt=a,mr=pr;function hr(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var gr=typeof Object.is=="function"?Object.is:hr,br=mr.useSyncExternalStore,xr=dt.useRef,yr=dt.useEffect,vr=dt.useMemo,wr=dt.useDebugValue;Sn.useSyncExternalStoreWithSelector=function(t,e,n,r,s){var i=xr(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=vr(function(){function p(g){if(!c){if(c=!0,f=g,g=r(g),s!==void 0&&l.hasValue){var b=l.value;if(s(b,g))return u=b}return u=g}if(b=u,gr(f,g))return b;var j=r(g);return s!==void 0&&s(b,j)?(f=g,b):(f=g,u=j)}var c=!1,f,u,h=n===void 0?null:n;return[function(){return p(e())},h===null?void 0:function(){return p(h())}]},[e,n,r,s]);var d=br(t,i[0],i[1]);return yr(function(){l.hasValue=!0,l.value=d},[d]),wr(d),d};wn.exports=Sn;var Sr=wn.exports;const kr=Gn(Sr),Cn={},{useDebugValue:Tr}=It,{useSyncExternalStoreWithSelector:Cr}=kr;let Ft=!1;const Er=t=>t;function jr(t,e=Er,n){(Cn?"production":void 0)!=="production"&&n&&!Ft&&(Ft=!0);const r=Cr(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return Tr(r),r}const Bt=t=>{const e=typeof t=="function"?rr(t):t,n=(r,s)=>jr(e,r,s);return Object.assign(n,e),n},Ir=t=>t?Bt(t):Bt,Me="";function xe(t){return{Authorization:`Bearer ${t}`}}class Ve extends Error{constructor(e,n){super(n),this.status=e,this.name="ApiError"}}function ze(t,e){return`${Me}/api/sessions/${encodeURIComponent(t)}/${e}`}function Pt(t){return`${Me}/api/settings/${t}`}async function Je(t){if(!t.ok){const e=await t.text().catch(()=>t.statusText);throw new Ve(t.status,e)}return t.json()}const ge={async get(t,e,n,r){const s=new URL(ze(e,n),window.location.origin);if(r)for(const[l,d]of Object.entries(r))s.searchParams.set(l,d);const i=await fetch(s.toString(),{headers:xe(t)});return Je(i)},async getOptional(t,e,n,r){const s=new URL(ze(e,n),window.location.origin);if(r)for(const[l,d]of Object.entries(r))s.searchParams.set(l,d);const i=await fetch(s.toString(),{headers:xe(t)});return i.status===304?null:Je(i)},async post(t,e,n,r){const s=await fetch(ze(e,n),{method:"POST",headers:{...xe(t),"Content-Type":"application/json"},body:JSON.stringify(r)});return Je(s)},async put(t,e,n,r){const s=await fetch(ze(e,n),{method:"PUT",headers:{...xe(t),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const i=await s.text().catch(()=>s.statusText);throw new Ve(s.status,i)}},async putJson(t,e,n,r){const s=await fetch(ze(e,n),{method:"PUT",headers:{...xe(t),"Content-Type":"application/json"},body:JSON.stringify(r)});return Je(s)},async del(t,e,n,r){const s=await fetch(ze(e,n),{method:"DELETE",headers:{...xe(t),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!s.ok){const i=await s.text().catch(()=>s.statusText);throw new Ve(s.status,i)}},async getBlob(t,e,n,r){const s=new URL(ze(e,n),window.location.origin);if(r)for(const[l,d]of Object.entries(r))s.searchParams.set(l,d);const i=await fetch(s.toString(),{headers:xe(t)});if(!i.ok)throw new Ve(i.status,"Download failed");return i}},ut={async get(t,e){const n=await fetch(Pt(e),{headers:xe(t)});return Je(n)},async put(t,e,n){const r=await fetch(Pt(e),{method:"PUT",headers:{...xe(t),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const s=await r.text().catch(()=>r.statusText);throw new Ve(r.status,s)}}};async function Rr(t){try{return(await ut.get(t,"font-size")).fontSize}catch{return 14}}async function Nr(t,e){try{await ut.put(t,"font-size",{fontSize:e})}catch{}}let Ze=null;const Lr=(t,e)=>({fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));t({fontSize:r}),Ze&&clearTimeout(Ze),Ze=setTimeout(()=>{Ze=null;const s=e().token;s&&Nr(s,r)},500)},latency:null,setLatency:n=>t({latency:n}),theme:(()=>{try{const n=localStorage.getItem("ai-cli-online-theme");if(n==="light"||n==="dark")return n}catch{}return"dark"})(),setTheme:n=>{t({theme:n});try{localStorage.setItem("ai-cli-online-theme",n)}catch{}document.documentElement.setAttribute("data-theme",n)},toggleTheme:()=>{const n=e().theme==="dark"?"light":"dark";e().setTheme(n)},sidebarOpen:!1,toggleSidebar:()=>t(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=e().token;if(n)try{const r=await fetch(`${Me}/api/sessions`,{headers:xe(n)});if(!r.ok)return;const s=await r.json();t({serverSessions:s})}catch{}}});function st(t,e){if(t.type==="leaf")return t.terminalId===e?null:t;const n=[],r=[];for(let l=0;l<t.children.length;l++){const d=st(t.children[l],e);d!==null&&(n.push(d),r.push(t.sizes[l]))}if(n.length===0)return null;if(n.length===1)return n[0];const s=r.reduce((l,d)=>l+d,0),i=r.map(l=>l/s*100);return{...t,children:n,sizes:i}}function En(t,e,n,r,s){return t.type==="leaf"?t.terminalId===e?{id:s,type:"split",direction:n,children:[t,r],sizes:[50,50]}:t:{...t,children:t.children.map(i=>En(i,e,n,r,s))}}function jn(t,e,n){return t.type==="leaf"?t:t.id===e?{...t,sizes:n}:{...t,children:t.children.map(r=>jn(r,e,n))}}function yt(t){return t.tabs.find(e=>e.id===t.activeTabId)}function Ie(t,e,n){return t.map(r=>r.id===e?n(r):r)}function Wt(t,e){const n=t.tabs.find(c=>c.terminalIds.includes(e));if(!n){const{[e]:c,...f}=t.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(c=>c!==e),s=n.layout?st(n.layout,e):null,i=Ie(t.tabs,n.id,c=>({...c,terminalIds:r,layout:s})),{[e]:l,...d}=t.terminalsMap,p={terminalsMap:d,tabs:i};return n.id===t.activeTabId&&(p.terminalIds=r,p.layout=s),p}async function Mr(t){try{return(await ut.get(t,"tabs-layout")).layout}catch{return null}}async function Dr(t,e){try{await ut.put(t,"tabs-layout",{layout:e})}catch{}}function Ut(t,e){try{const n=`${Me}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:t});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const Tt="ai-cli-online-tabs",Ht="ai-cli-online-layout",Kt="ai-cli-online-session-names";let Ce=null;function Ar(t){Ce=t,Br()}let Qe=null,$e=null,Ge=null;function zr(t){Ge=t,$e&&clearTimeout($e),$e=setTimeout(()=>{$e=null,Ge=null;const e=Ce==null?void 0:Ce.getState().token;e&&Dr(e,t)},2e3)}function me(t){const e={version:2,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId,tabs:t.tabs};try{localStorage.setItem(Tt,JSON.stringify(e))}catch{}zr(e)}function $r(t){Qe&&clearTimeout(Qe),Qe=setTimeout(()=>{Qe=null,me(t)},500)}function fe(t){return{tabs:t.tabs,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId}}function _r(){try{const t=localStorage.getItem(Tt);if(t){const e=JSON.parse(t);if(e.version===2)return e}}catch{}try{const t=localStorage.getItem(Ht);if(t){const e=JSON.parse(t);let n="Default";try{const i=localStorage.getItem(Kt);if(i){const l=JSON.parse(i),d=Object.values(l)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},s={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(Tt,JSON.stringify(s))}catch{}return localStorage.removeItem(Ht),localStorage.removeItem(Kt),s}}catch{}return null}function Or(t,e){const n=new Set(e.map(l=>l.sessionId)),r=[];for(const l of t.tabs){if(l.status!=="open"){const c=l.terminalIds.filter(f=>n.has(f));if(c.length>0){let f=l.layout;for(const u of l.terminalIds)!n.has(u)&&f&&(f=st(f,u));r.push({...l,terminalIds:c,layout:f})}continue}const d=l.terminalIds.filter(c=>n.has(c));if(d.length===0)continue;let p=l.layout;for(const c of l.terminalIds)!n.has(c)&&p&&(p=st(p,c));r.push({...l,terminalIds:d,layout:p})}if(r.filter(l=>l.status==="open").length===0)return null;let s=t.activeTabId;if(!r.find(l=>l.id===s&&l.status==="open")){const l=r.find(d=>d.status==="open");s=(l==null?void 0:l.id)||""}return{...t,activeTabId:s,tabs:r}}async function Fr(t,e){var s,i;if(!Ce)return;const{setState:n,getState:r}=Ce;try{const[l,d]=await Promise.all([Mr(t),fetch(`${Me}/api/sessions`,{headers:xe(t)}).then(b=>b.ok?b.json():[]).catch(()=>[])]);if(r().token!==t)return;const p=l&&((s=l.tabs)==null?void 0:s.length)>0?l:e;if(!p||p.tabs.length===0){n({tabsLoading:!1});return}const c=Or(p,d);if(!c){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:p.nextId,nextSplitId:p.nextSplitId,nextTabId:p.nextTabId,terminalIds:[],layout:null});return}const f=r().terminalsMap,u={};for(const b of c.tabs)if(b.status==="open")for(const j of b.terminalIds)u[j]=f[j]||{id:j,connected:!1,sessionResumed:!1,error:null,panels:((i=b.panelStates)==null?void 0:i[j])||{chatOpen:!1,planOpen:!1}};const h=c.tabs.find(b=>b.id===c.activeTabId&&b.status==="open")||c.tabs.find(b=>b.status==="open"),g=(h==null?void 0:h.id)||"";n({tabsLoading:!1,terminalsMap:u,tabs:c.tabs,activeTabId:g,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(h==null?void 0:h.terminalIds)||[],layout:(h==null?void 0:h.layout)||null}),me(fe(r()))}catch{r().token===t&&n({tabsLoading:!1})}}function Br(){typeof window>"u"||!Ce||window.addEventListener("beforeunload",()=>{const t=Ce==null?void 0:Ce.getState().token;if(t)if(Ge)$e&&(clearTimeout($e),$e=null),Ut(t,Ge),Ge=null;else{const e=Ce.getState();e.tabs.length>0&&Ut(t,fe(e))}})}const D=Ir((...t)=>{const[e,n]=t;return{...Lr(...t),token:null,tabsLoading:!1,setToken:r=>{var s;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}Rr(r).then(l=>{n().token===r&&e({fontSize:l})});const i=_r();if(i&&i.tabs.length>0){const l={};for(const c of i.tabs)if(c.status==="open")for(const f of c.terminalIds)l[f]={id:f,connected:!1,sessionResumed:!1,error:null,panels:((s=c.panelStates)==null?void 0:s[f])||{chatOpen:!1,planOpen:!1}};const d=i.tabs.find(c=>c.id===i.activeTabId&&c.status==="open")||i.tabs.find(c=>c.status==="open"),p=(d==null?void 0:d.id)||"";e({token:r,tabsLoading:!0,terminalsMap:l,tabs:i.tabs,activeTabId:p,nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:(d==null?void 0:d.terminalIds)||[],layout:(d==null?void 0:d.layout)||null})}else e({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Fr(r,i);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),e({token:r,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:r=>{const s=n(),i=`tab${s.nextTabId}`,l=`t${s.nextId}`,d={id:l,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},p={type:"leaf",terminalId:l},c={id:i,name:r||`Tab ${s.nextTabId}`,status:"open",terminalIds:[l],layout:p,createdAt:Date.now()};return e({tabs:[...s.tabs,c],activeTabId:i,nextTabId:s.nextTabId+1,nextId:s.nextId+1,terminalsMap:{...s.terminalsMap,[l]:d},terminalIds:c.terminalIds,layout:c.layout}),me(fe(n())),i},switchTab:r=>{const i=n().tabs.find(l=>l.id===r);!i||i.status!=="open"||(e({activeTabId:r,terminalIds:i.terminalIds,layout:i.layout}),me(fe(n())))},closeTab:r=>{const s=n(),i=s.tabs.find(h=>h.id===r);if(!i||i.status!=="open"||s.tabs.filter(h=>h.status==="open").length<=1)return;const d={...s.terminalsMap};for(const h of i.terminalIds)delete d[h];const p=Ie(s.tabs,r,h=>({...h,status:"closed"}));let c=s.activeTabId,f=s.terminalIds,u=s.layout;if(s.activeTabId===r){const h=s.tabs.findIndex(j=>j.id===r),g=p.filter(j=>j.status==="open"),b=g.find(j=>p.findIndex(C=>C.id===j.id)>h)||g[g.length-1];b&&(c=b.id,f=b.terminalIds,u=b.layout)}e({tabs:p,activeTabId:c,terminalsMap:d,terminalIds:f,layout:u}),me(fe(n()))},reopenTab:r=>{var p;const s=n(),i=s.tabs.find(c=>c.id===r);if(!i||i.status!=="closed")return;const l={...s.terminalsMap};for(const c of i.terminalIds)l[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((p=i.panelStates)==null?void 0:p[c])||{chatOpen:!1,planOpen:!1}};const d=Ie(s.tabs,r,c=>({...c,status:"open"}));e({tabs:d,activeTabId:r,terminalsMap:l,terminalIds:i.terminalIds,layout:i.layout}),me(fe(n()))},deleteTab:async r=>{const s=n(),i=s.tabs.find(b=>b.id===r);if(!i)return;const l=s.token;l&&await Promise.all(i.terminalIds.map(b=>fetch(`${Me}/api/sessions/${encodeURIComponent(b)}`,{method:"DELETE",headers:xe(l)}).catch(()=>{})));const d=n(),p=d.tabs.find(b=>b.id===r);if(!p)return;const c={...d.terminalsMap};for(const b of p.terminalIds)delete c[b];const f=d.tabs.filter(b=>b.id!==r);let u=d.activeTabId,h=d.terminalIds,g=d.layout;if(d.activeTabId===r){const b=f.find(j=>j.status==="open");b?(u=b.id,h=b.terminalIds,g=b.layout):(u="",h=[],g=null)}e({tabs:f,activeTabId:u,terminalsMap:c,terminalIds:h,layout:g}),me(fe(n())),setTimeout(()=>n().fetchSessions(),500)},renameTab:(r,s)=>{const i=Ie(n().tabs,r,l=>({...l,name:s}));e({tabs:i}),me(fe(n()))},addTerminal:(r,s)=>{const i=n();if(s&&i.terminalsMap[s])return s;const l=yt(i);if(!l){const z=`tab${i.nextTabId}`,_=s||`t${i.nextId}`;let B=i.nextId;const F=_.match(/^t(\d+)$/);F&&(B=Math.max(B,parseInt(F[1],10)+1));const O=s?B:B+1,N={id:_,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},S={type:"leaf",terminalId:_},w={id:z,name:`Tab ${i.nextTabId}`,status:"open",terminalIds:[_],layout:S,createdAt:Date.now()};return e({tabs:[...i.tabs,w],activeTabId:z,nextTabId:i.nextTabId+1,nextId:O,terminalsMap:{...i.terminalsMap,[_]:N},terminalIds:[_],layout:S}),me(fe(n())),_}const{nextId:d,nextSplitId:p,terminalsMap:c}=i,{terminalIds:f,layout:u}=l,h=s||`t${d}`;let g=d;const b=h.match(/^t(\d+)$/);b&&(g=Math.max(g,parseInt(b[1],10)+1));const j={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},k={type:"leaf",terminalId:h};let C,v=p;if(!u)C=k;else if(u.type==="leaf"){const z=r||"horizontal";C={id:`s${v}`,type:"split",direction:z,children:[u,k],sizes:[50,50]},v++}else if(u.direction===(r||"horizontal")){const _=100/(u.children.length+1),B=(100-_)/100,F=[...u.sizes.map(O=>O*B),_];C={...u,children:[...u.children,k],sizes:F}}else{const z=r||"horizontal";C={id:`s${v}`,type:"split",direction:z,children:[u,k],sizes:[50,50]},v++}const I=[...f,h],T=s?g:g+1,L=Ie(i.tabs,l.id,z=>({...z,terminalIds:I,layout:C}));return e({terminalsMap:{...c,[h]:j},terminalIds:I,layout:C,tabs:L,nextId:T,nextSplitId:v}),me(fe(n())),h},splitTerminal:(r,s,i)=>{const l=n(),d=yt(l);if(!d||!d.layout)return"";const{nextId:p,nextSplitId:c,terminalsMap:f}=l,u=`t${p}`,h={id:u,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1},...i?{startCwd:i}:{}},g={type:"leaf",terminalId:u},b=`s${c}`,j=En(d.layout,r,s,g,b),k=[...d.terminalIds,u],C=p+1,v=c+1,I=Ie(l.tabs,d.id,T=>({...T,terminalIds:k,layout:j}));return e({terminalsMap:{...f,[u]:h},terminalIds:k,layout:j,tabs:I,nextId:C,nextSplitId:v}),me(fe(n())),u},removeTerminal:r=>{const s=Wt(n(),r);s&&(e(s),me(fe(n())))},disconnectTerminal:r=>{const s=n();if(!s.terminalsMap[r])return;const{[r]:l,...d}=s.terminalsMap;e({terminalsMap:d})},reconnectTerminal:r=>{var p;const s=n();if(s.terminalsMap[r])return;const i=s.tabs.find(c=>c.terminalIds.includes(r)),l=((p=i==null?void 0:i.panelStates)==null?void 0:p[r])||{chatOpen:!1,planOpen:!1},d={id:r,connected:!1,sessionResumed:!1,error:null,panels:l};e({terminalsMap:{...s.terminalsMap,[r]:d}})},setTerminalConnected:(r,s)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.connected===s?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,connected:s}}}})},setTerminalResumed:(r,s)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.sessionResumed===s?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,sessionResumed:s}}}})},setTerminalError:(r,s)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.error===s?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,error:s}}}})},toggleChat:r=>{const s=n(),i=s.terminalsMap[r];if(!i)return;const l={...i.panels,chatOpen:!i.panels.chatOpen},d={...s.terminalsMap,[r]:{...i,panels:l}},p=s.tabs.find(f=>f.terminalIds.includes(r));let c=s.tabs;if(p){const f={...p.panelStates,[r]:l};c=Ie(s.tabs,p.id,u=>({...u,panelStates:f}))}e({terminalsMap:d,tabs:c}),me(fe(n()))},togglePlan:r=>{const s=n(),i=s.terminalsMap[r];if(!i)return;const l={...i.panels,planOpen:!i.panels.planOpen},d={...s.terminalsMap,[r]:{...i,panels:l}},p=s.tabs.find(f=>f.terminalIds.includes(r));let c=s.tabs;if(p){const f={...p.panelStates,[r]:l};c=Ie(s.tabs,p.id,u=>({...u,panelStates:f}))}e({terminalsMap:d,tabs:c}),me(fe(n()))},setSplitSizes:(r,s)=>{const i=n(),l=yt(i);if(!l||!l.layout)return;const d=jn(l.layout,r,s),p=Ie(i.tabs,l.id,c=>({...c,layout:d}));e({layout:d,tabs:p}),$r(fe(n()))},killServerSession:async r=>{const s=n().token;if(!s)return;try{await fetch(`${Me}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:xe(s)})}catch{}const i=Wt(n(),r);i&&(e(i),me(fe(n()))),setTimeout(()=>n().fetchSessions(),500)}}});Ar(D);typeof document<"u"&&document.documentElement.setAttribute("data-theme",D.getState().theme);function Pr(){const[t,e]=a.useState(""),n=D(s=>s.setToken),r=s=>{s.preventDefault(),t.trim()&&n(t.trim())};return o.jsx("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, var(--bg-primary) 70%)"},children:o.jsxs("div",{className:"login-card",style:{backgroundColor:"var(--bg-tertiary)",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid var(--border)"},children:[o.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[o.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"var(--bg-primary)",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),o.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),o.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),o.jsxs("form",{onSubmit:r,children:[o.jsxs("div",{style:{marginBottom:"20px"},children:[o.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"var(--accent-blue)",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),o.jsx("input",{type:"password",id:"token",className:"login-input",value:t,onChange:s=>e(s.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"var(--bg-primary)",color:"var(--text-bright)",border:"1px solid var(--border)",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),o.jsx("button",{type:"submit",className:"login-submit",disabled:!t.trim(),style:{width:"100%",padding:"11px",background:t.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:t.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:t.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),o.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:o.jsxs("p",{children:["Token is configured in"," ",o.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const ft=new Map;function Wr(t,e,n){ft.set(t,{onChunk:e,onControl:n})}function Ur(t){ft.delete(t)}function Hr(t,e){var n;(n=ft.get(t))==null||n.onChunk(e)}function Kr(t,e){var n;(n=ft.get(t))==null||n.onControl(e)}const Jr=1,Jt=2,Vr=3,Gr=4,qr=5,Yr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,et=500,Xr=8e3,Zr=1e4,Vt=4e3,Qr=5e3,es=10,ts=64*1024,ns=new TextDecoder,rs=new TextEncoder;function Gt(t,e){const n=rs.encode(e),r=new Uint8Array(1+n.length);return r[0]=t,r.set(n,1),r.buffer}function ss(t,e,n){const r=a.useRef(null),s=a.useRef(et),i=a.useRef(null),l=a.useRef(null),d=a.useRef(null),p=a.useRef(null),c=a.useRef(!1),f=a.useRef(n),u=a.useRef(!1),h=a.useRef(0),g=a.useRef(!0),b=a.useRef(!navigator.onLine),j=a.useRef(""),k=a.useRef(null),C=a.useRef("");f.current=n;const v=a.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null),d.current&&(clearTimeout(d.current),d.current=null),i.current&&(clearTimeout(i.current),i.current=null),p.current&&(clearTimeout(p.current),p.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),I=a.useCallback(()=>{var Y;const{token:F,setTerminalError:O}=D.getState();if(!F||c.current)return;if(r.current){const P=r.current.readyState;if(P===WebSocket.OPEN||P===WebSocket.CONNECTING)return}u.current=!1;const N=(Y=D.getState().terminalsMap[e])==null?void 0:Y.startCwd;let S=`${Yr}?sessionId=${encodeURIComponent(e)}`;N&&(S+=`&cwd=${encodeURIComponent(N)}`);const w=new WebSocket(S);w.binaryType="arraybuffer",p.current=window.setTimeout(()=>{w.readyState===WebSocket.CONNECTING&&w.close()},Qr);const ee=()=>{w.readyState===WebSocket.OPEN&&(h.current=performance.now(),w.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,w.close())},Vt))};w.onopen=()=>{p.current&&(clearTimeout(p.current),p.current=null),w.send(JSON.stringify({type:"auth",token:F})),O(e,null),s.current=et,g.current=!0},w.onclose=P=>{const{setTerminalConnected:G,setTerminalError:$,setToken:U}=D.getState();if(G(e,!1),v(),u.current)return;if(P.code===4001){c.current=!0,$(e,"Authentication failed"),U(null),localStorage.removeItem("ai-cli-online-token");return}if(P.code===4002)return;if(P.code===4005){$(e,"Connection limit reached");return}if(!navigator.onLine){b.current=!0;return}if(g.current){g.current=!1,i.current=window.setTimeout(()=>I(),50);return}const H=s.current;s.current=Math.min(H*2,Xr);const V=Math.round(H*(.5+Math.random()));i.current=window.setTimeout(()=>{I()},V)},w.onerror=()=>{},w.onmessage=P=>{var G;try{const $=t.current;if(P.data instanceof ArrayBuffer){const H=new Uint8Array(P.data);if(H.length<1)return;const V=H[0],ne=H.subarray(1);switch(V){case Jr:$==null||$.write(ne);break;case Vr:$==null||$.write(ne);break;case Gr:{(G=f.current)==null||G.call(f,ns.decode(ne));break}case qr:{Hr(e,ne);break}}return}const U=JSON.parse(P.data);switch(U.type){case"connected":{const H=D.getState();H.setTerminalConnected(e,!0),H.setTerminalResumed(e,U.resumed);const V=t.current;V&&w.readyState===WebSocket.OPEN&&w.send(JSON.stringify({type:"resize",cols:V.cols,rows:V.rows})),C.current&&(w.send(Gt(Jt,C.current)),C.current=""),ee(),l.current=window.setInterval(ee,Zr);break}case"error":D.getState().setTerminalError(e,U.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),h.current>0){const H=Math.round(performance.now()-h.current),V=D.getState();(V.terminalIds.length===0||V.terminalIds[0]===e)&&V.setLatency(H),h.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Kr(e,U);break}}catch{}},r.current=w},[e,t,v]),T=a.useCallback(F=>{const O=r.current;if(!O||O.readyState!==WebSocket.OPEN){C.current.length<ts&&(C.current+=F);return}j.current+=F,k.current||(k.current=window.setTimeout(()=>{const N=j.current;j.current="",k.current=null,N&&O.readyState===WebSocket.OPEN&&O.send(Gt(Jt,N))},es))},[]),L=a.useCallback((F,O)=>{var N;((N=r.current)==null?void 0:N.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:F,rows:O}))},[]),z=a.useCallback(()=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),_=a.useCallback(F=>{var O;((O=r.current)==null?void 0:O.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:F}))},[]),B=a.useCallback(()=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return a.useEffect(()=>{D.getState().token&&(c.current=!1,I());const O=()=>{b.current=!1,s.current=et,g.current=!0;const w=r.current;(!w||w.readyState===WebSocket.CLOSED||w.readyState===WebSocket.CLOSING)&&I()},N=()=>{b.current=!0},S=()=>{if(document.visibilityState!=="visible")return;const w=r.current;if(!w||w.readyState!==WebSocket.OPEN){!b.current&&!u.current&&(s.current=et,g.current=!0,I());return}h.current=performance.now(),w.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,w.close())},Vt)};return window.addEventListener("online",O),window.addEventListener("offline",N),document.addEventListener("visibilitychange",S),()=>{u.current=!0,v(),window.removeEventListener("online",O),window.removeEventListener("offline",N),document.removeEventListener("visibilitychange",S),r.current&&(r.current.close(),r.current=null)}},[I,v,e]),{sendInput:T,sendResize:L,requestScrollback:z,requestFileStream:_,cancelFileStream:B}}function as(t){const e=a.useRef(null),n=a.useRef(null),r=a.useRef(t);r.current=t;const s=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null),e.current&&(e.current.remove(),e.current=null)},[]),i=a.useCallback((l,d)=>{s();const p=document.createElement("div");p.style.cssText=`position:fixed;left:${l}px;top:${d}px;z-index:1000;display:flex;align-items:center;gap:4px;padding:4px 6px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.4);font-family:inherit;`;const c=document.createElement("textarea");c.style.cssText="width:90px;height:22px;resize:none;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-size:11px;font-family:inherit;padding:2px 4px;outline:none;",c.placeholder="Ctrl+V",c.addEventListener("paste",f=>{var h;f.preventDefault();const u=(h=f.clipboardData)==null?void 0:h.getData("text/plain");u&&r.current(u),s()}),c.addEventListener("keydown",f=>{f.key==="Escape"&&s()}),p.appendChild(c),document.body.appendChild(p),e.current=p,requestAnimationFrame(()=>{const f=p.getBoundingClientRect();f.right>window.innerWidth&&(p.style.left=`${window.innerWidth-f.width-8}px`),f.bottom>window.innerHeight&&(p.style.top=`${window.innerHeight-f.height-8}px`),c.focus()}),n.current=setTimeout(s,8e3)},[s]);return a.useEffect(()=>{const l=()=>{e.current&&s()};return document.addEventListener("click",l),()=>{document.removeEventListener("click",l),s()}},[s]),{showPasteFloat:i,removePasteFloat:s}}const at={background:"#000000",foreground:"#cccccc",cursor:"#aeafad",selectionBackground:"rgba(38, 79, 120, 0.5)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5"},ot={background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"rgba(9, 105, 218, 0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#2da44e",brightYellow:"#bf8803",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"},In="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",os=a.forwardRef(function({sessionId:e},n){const r=a.useRef(null),s=a.useRef(null),i=a.useRef(null),[l,d]=a.useState(!1),[p,c]=a.useState(""),f=D(L=>L.fontSize),u=D(L=>L.theme),h=a.useCallback(L=>{c(L),d(!0)},[]),{sendInput:g,sendResize:b,requestScrollback:j,requestFileStream:k,cancelFileStream:C}=ss(s,e,h);a.useImperativeHandle(n,()=>({sendInput:g,requestFileStream:k,cancelFileStream:C}),[g,k,C]);const v=a.useRef(g),I=a.useRef(b);v.current=g,I.current=b;const{removePasteFloat:T}=as(L=>v.current(L));return a.useEffect(()=>{if(!r.current)return;let L=!1,z=null,_=null,B=null,F=null;if(L||!r.current)return;const O=new hn({cursorBlink:!0,scrollback:1e4,fontSize:D.getState().fontSize,fontFamily:In,theme:D.getState().theme==="dark"?at:ot,allowProposedApi:!0}),N=new gn;O.loadAddon(N),O.loadAddon(new qn((U,H)=>{window.open(H,"_blank","noopener,noreferrer")})),O.open(r.current);try{const U=new bn;U.onContextLoss(()=>{U.dispose()}),O.loadAddon(U)}catch{}s.current=O,i.current=N,O.onSelectionChange(()=>{const U=O.getSelection();U&&navigator.clipboard.writeText(U).catch(()=>{})});const S=O.element,w=U=>{var H;U.preventDefault(),T(),(H=navigator.clipboard)!=null&&H.readText&&navigator.clipboard.readText().then(V=>{V&&v.current(V)}).catch(()=>{})};S&&S.addEventListener("contextmenu",w);const ee=()=>{try{const U=r.current;if(U&&U.clientWidth>0&&U.clientHeight>0)return N.fit(),I.current(O.cols,O.rows),!0}catch{}return!1};requestAnimationFrame(()=>ee());let Y=0;z=setInterval(()=>{Y++,(ee()||Y>=10)&&(clearInterval(z),z=null)},100),document.fonts.ready.then(()=>{if(!L)try{N.fit(),I.current(O.cols,O.rows)}catch{}});let P=null;const G=()=>{L||(P&&clearTimeout(P),P=setTimeout(()=>{if(!L)try{N.fit(),I.current(O.cols,O.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",G),O.onData(U=>{v.current(U)});let $=!1;return F=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!$){$=!0;const H=()=>{document.removeEventListener("mouseup",H),$=!1,requestAnimationFrame(()=>{try{N.fit(),I.current(O.cols,O.rows)}catch{}})};document.addEventListener("mouseup",H)}return}_||(_=requestAnimationFrame(()=>{_=null;try{N.fit(),B&&clearTimeout(B),B=setTimeout(()=>{B=null,I.current(O.cols,O.rows)},50)}catch{}}))}),F.observe(r.current),()=>{L=!0,z&&clearInterval(z),_&&cancelAnimationFrame(_),B&&clearTimeout(B),P&&clearTimeout(P),document.fonts.removeEventListener("loadingdone",G),F&&F.disconnect(),T(),S&&S.removeEventListener("contextmenu",w),s.current&&(s.current.dispose(),s.current=null),i.current=null}},[e]),a.useEffect(()=>{const L=s.current,z=i.current;if(!(!L||!z)&&L.options.fontSize!==f){L.options.fontSize=f;try{z.fit()}catch{}I.current(L.cols,L.rows)}},[f]),a.useEffect(()=>{s.current&&(s.current.options.theme=u==="dark"?at:ot)},[u]),o.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[o.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),o.jsx("button",{tabIndex:-1,onClick:L=>{L.currentTarget.blur(),l?(d(!1),c("")):j()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:l?"var(--accent-blue)":"var(--bg-hover)",color:"var(--text-bright)",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:L=>{L.currentTarget.style.opacity="1"},onMouseLeave:L=>{L.currentTarget.style.opacity="0.8"},children:l?"✕":o.jsx("span",{style:{fontSize:14},children:"👁"})}),l&&o.jsx(is,{data:p,onClose:()=>{d(!1),c("")}})]})});function is({data:t,onClose:e}){const n=a.useRef(null),r=a.useRef(e);r.current=e;const s=D(c=>c.fontSize),i=D(c=>c.theme),l=a.useRef(null),d=a.useRef(null);a.useEffect(()=>{if(!n.current)return;const c=new hn({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:s,fontFamily:In,theme:i==="dark"?at:ot});l.current=c;const f=new gn;d.current=f,c.loadAddon(f),c.open(n.current);let u=null;try{u=new bn,u.onContextLoss(()=>{u==null||u.dispose(),u=null}),c.loadAddon(u)}catch{u=null}c.onSelectionChange(()=>{const C=c.getSelection();C&&navigator.clipboard.writeText(C).catch(()=>{})}),c.attachCustomKeyEventHandler(C=>(C.key==="Escape"&&r.current(),!1)),c.write(t);let h=null;const g=()=>{const C=n.current;if(!C||C.clientWidth<=0||C.clientHeight<=0)return!1;try{return f.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!g()){let C=0;h=setInterval(()=>{C++,(g()||C>=30)&&(clearInterval(h),h=null)},50)}});let b=null;const j=new ResizeObserver(()=>{b||(b=requestAnimationFrame(()=>{b=null,g()}))});j.observe(n.current);const k=C=>{C.key==="Escape"&&r.current()};return document.addEventListener("keydown",k),()=>{if(h&&clearInterval(h),b&&cancelAnimationFrame(b),document.removeEventListener("keydown",k),j.disconnect(),u){try{u.dispose()}catch{}u=null}c.dispose(),l.current=null,d.current=null}},[t]),a.useEffect(()=>{var c;if(l.current){l.current.options.fontSize=s;try{(c=d.current)==null||c.fit()}catch{}}},[s]),a.useEffect(()=>{l.current&&(l.current.options.theme=i==="dark"?at:ot)},[i]);const p=28;return o.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[o.jsx("div",{style:{height:p,boxSizing:"border-box",padding:"0 12px",background:"var(--bg-tertiary)",color:"var(--accent-blue)",fontSize:12,borderBottom:"1px solid var(--scrollbar-thumb-hover)",display:"flex",alignItems:"center"},children:o.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),o.jsx("div",{ref:n,style:{position:"absolute",top:p,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const ls=50;function Ct(){const t=a.useRef([]),e=a.useCallback(s=>{t.current.push(s),t.current.length>ls&&t.current.shift()},[]),n=a.useCallback(()=>t.current.pop(),[]),r=a.useCallback(()=>{t.current=[]},[]);return a.useMemo(()=>({pushUndo:e,popUndo:n,clearUndo:r}),[e,n,r])}function Et(t,e,n){t.preventDefault();const r=t.currentTarget,s=r.selectionStart,i=r.selectionEnd,l=r.value;n==null||n(l);const d=l.slice(0,s)+" "+l.slice(i);e(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=s+2})}function it(t,e=20){var n;return Math.min(e,Math.max(1,(((n=t.match(/\n/g))==null?void 0:n.length)??0)+1))}let Pe=null,Rn="dark";const cs=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],ds={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"},us={primaryColor:"#2e59a8",primaryTextColor:"#343b58",primaryBorderColor:"#9aa5ce",lineColor:"#8c8fa1",secondaryColor:"#7847bd",tertiaryColor:"#d5d6db",background:"#f5f5f5",mainBkg:"#e8e8ed",nodeBorder:"#9aa5ce",clusterBkg:"#ebebf0",titleColor:"#343b58",edgeLabelBackground:"#ebebf0",gridColor:"#d5d6db",doneTaskBkgColor:"#4e8a2f",doneTaskBorderColor:"#3d6e25",activeTaskBkgColor:"#2e59a8",activeTaskBorderColor:"#24478a",critBkgColor:"#c4384b",critBorderColor:"#a02e3e",taskBkgColor:"#c0c1c9",taskBorderColor:"#9aa5ce",taskTextColor:"#343b58",taskTextDarkColor:"#f5f5f5",sectionBkgColor:"#e8e8ed",sectionBkgColor2:"#d5d6db",altSectionBkgColor:"#e8e8ed",todayLineColor:"#b68d28"},fs={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function qt(t,e){return Rn=e,t.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?ds:us,gantt:fs}),t}function ps(t="dark"){return Pe?Rn!==t?Pe.then(e=>qt(e,t)):Pe:(Pe=(async()=>{for(const e of cs)try{const n=await import(e);return qt(n.default,t)}catch{}throw Pe=null,new Error("All mermaid CDN sources failed")})(),Pe)}let Yt=0;function ms(t,e,n="dark"){const r=a.useRef(n);a.useEffect(()=>{const s=t.current;if(!s)return;const i=r.current!==n;r.current=n;const l=s.querySelectorAll("code.language-mermaid, code.language-gantt"),d=i?s.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(l.length===0&&d.length===0)return;let p=!1;return(async()=>{let c;try{c=await ps(n)}catch{if(p)return;for(const u of l){const h=u.parentElement;if(!h||h.tagName!=="PRE")continue;h.classList.add("mermaid-error");const g=document.createElement("div");g.className="mermaid-error__msg",g.textContent="Failed to load Mermaid library",h.appendChild(g)}return}if(!p){for(const f of d){if(p)break;const u=f.getAttribute("data-mermaid-source");if(!u)continue;const h=`mermaid-${++Yt}`;try{const{svg:g}=await c.render(h,u);if(p)break;f.innerHTML=St.sanitize(g,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const f of l){if(p)break;const u=f.parentElement;if(!u||u.tagName!=="PRE")continue;const h=f.textContent||"";if(!h.trim())continue;const g=`mermaid-${++Yt}`;try{const{svg:b}=await c.render(g,h);if(p)break;const j=document.createElement("div");j.className="mermaid-diagram",j.setAttribute("data-mermaid-source",h),j.innerHTML=St.sanitize(b,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),u.replaceWith(j)}catch{if(p)break;u.classList.add("mermaid-error");const b=document.createElement("div");b.className="mermaid-error__msg",b.textContent="Mermaid syntax error",u.appendChild(b)}}}})(),()=>{p=!0}},[e,n])}async function hs(t,e,n){const r=await ge.get(t,e,"annotations",{path:n});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function Nn(t,e,n,r,s){await ge.put(t,e,"annotations",{path:n,content:r,updatedAt:s})}async function Xt(t,e,n,r){return ge.post(t,e,"task-annotations",{modulePath:n,content:r})}const jt={additions:[],deletions:[],replacements:[],comments:[]};let gs=0;function Te(){return`ann_${++gs}_${Date.now()}`}function qe(t,e){return`plan-annotations-${t}-${e}`}function Zt(t,e){return`plan-scroll-${t}-${e}`}function bs(t){const e=String(xn.parser([t],{async:!1}));return St.sanitize(e,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function tt(t,e){let n=1;for(let r=0;r<e&&r<t.length;r++){const s=t[r].raw??"";for(const i of s)i===`
|
|
26
|
+
`&&n++}return n}function nt(t,e,n,r){const s=t.join(`
|
|
27
|
+
`);let i=0;for(let g=0;g<e-1&&g<t.length;g++)i+=t[g].length+1;let l=0;for(let g=0;g<n&&g<t.length;g++)l+=t[g].length+1;let d=i,p=Math.min(s.length,l);if(r){const g=Math.max(0,i-10),b=Math.min(s.length,l+10),k=s.slice(g,b).indexOf(r);k>=0&&(d=g+k,p=d+r.length)}const c=Math.max(0,d-20),f=s.slice(c,d).replace(/\n/g,"↵"),u=Math.min(s.length,p+20),h=s.slice(p,u).replace(/\n/g,"↵");return{before:f,after:h}}function Qt(t,e){const n=[],r=[],s=[],i=[];for(const l of t.additions){const{before:d,after:p}=nt(e,l.sourceLine,l.sourceLine);n.push([`Line${l.sourceLine}:...${d}`,l.content,`${p}...`])}for(const l of t.deletions){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);r.push([`Line${l.startLine}:...${d}`,l.selectedText,`${p}...`])}for(const l of t.replacements){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);s.push([`Line${l.startLine}:...${d}`,l.selectedText,l.content,`${p}...`])}for(const l of t.comments){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);i.push([`Line${l.startLine}:...${d}`,l.selectedText,l.content,`${p}...`])}return{"Insert Annotations":n,"Delete Annotations":r,"Replace Annotations":s,"Comment Annotations":i}}function en(t){return t.additions.length>0||t.deletions.length>0||t.replacements.length>0||t.comments.length>0}function tn(t){return/^[a-zA-Z0-9_./:@=-]+$/.test(t)?t:"'"+t.replace(/'/g,"'\\''")+"'"}function nn(t,e){return`/ai-cli-task:annotate ${tn(t)} ${tn(e)} --silent`}function rn(t){const e=t.split("/"),n=e.indexOf("AiTasks");return n>=0&&n+1<e.length?e.slice(0,n+2).join("/"):t.substring(0,t.lastIndexOf("/"))}function lt(t){const e=new Set;return t.additions.forEach(n=>e.add(n.id)),t.deletions.forEach(n=>e.add(n.id)),t.replacements.forEach(n=>e.add(n.id)),t.comments.forEach(n=>e.add(n.id)),e}function sn(t){return t.replacements||(t.replacements=[]),t.comments||(t.comments=[]),t}function xs({sessionId:t,filePath:e,token:n,annotations:r,annLoadedRef:s,setAnnotations:i,baselineIdsRef:l}){const d=D(u=>u.latency),p=a.useRef(void 0),c=a.useRef(void 0),f=a.useRef(!1);a.useEffect(()=>{if(!s.current)return;const u=qe(t,e),h=JSON.stringify(r);p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(u,h)}catch{}},50),c.current&&clearTimeout(c.current);const g=Math.max(200,(d??30)*3);return c.current=setTimeout(()=>{f.current||(f.current=!0,Nn(n,t,e,h,Date.now()).catch(()=>{}).finally(()=>{f.current=!1}))},g),()=>{p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current)}},[r,t,e,n,d,s]),a.useEffect(()=>{s.current=!1;let u=jt,h=0;try{const b=localStorage.getItem(qe(t,e));b&&(u=sn(JSON.parse(b)),h=Date.now())}catch{}i(u),l.current=lt(u);let g=!1;return hs(n,t,e).then(b=>{if(!g&&b&&b.updatedAt>h)try{const j=sn(JSON.parse(b.content));i(j);try{localStorage.setItem(qe(t,e),b.content)}catch{}l.current=lt(j)}catch{}}).catch(()=>{}).finally(()=>{s.current=!0}),s.current=!0,()=>{g=!0}},[t,e,n,s,i,l])}async function rt(t,e,n,r){const s={path:n};return r&&(s.since=String(r)),ge.getOptional(t,e,"file-content",s)}async function an(t,e,n,r){return ge.putJson(t,e,"file-content",{path:n,content:r})}function Ln(t,e){let n=t.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");n||(n="heading");const r=e.get(n)||0;return r>0&&(n=`${n}-${r}`),e.set(n,r+1),n}function Mn(t){return t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function ys(t){if(!t)return[];const e=[],n=new Map,r=t.split(`
|
|
28
|
+
`);let s=!1;for(const i of r){if(/^```/.test(i.trim())){s=!s;continue}if(s)continue;const l=i.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(l){const d=l[1].length,p=Mn(l[2]),c=Ln(p,n);e.push({id:c,text:p,level:d})}}return e}const vs=160,ws=22;function Ss({headings:t,scrollRef:e}){const[n,r]=a.useState(null),[s,i]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),l=a.useRef(null),d=a.useRef(!1),p=a.useMemo(()=>Math.min(...t.map(u=>u.level)),[t]),c=a.useCallback(()=>{i(u=>{const h=!u;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);a.useEffect(()=>{const u=e.current;if(!u||t.length===0)return;const h=()=>{d.current=!1;const b=u.scrollTop,j=50;let k=null;for(const C of t){const v=u.querySelector(`[id="${CSS.escape(C.id)}"]`);v&&v.offsetTop<=b+j&&(k=C.id)}r(k)},g=()=>{d.current||(d.current=!0,requestAnimationFrame(h))};return h(),u.addEventListener("scroll",g,{passive:!0}),()=>u.removeEventListener("scroll",g)},[t,e]);const f=a.useCallback(u=>{const h=e.current;if(!h)return;const g=h.querySelector(`[id="${CSS.escape(u)}"]`);g&&(g.scrollIntoView({behavior:"smooth",block:"start"}),r(u))},[e]);return a.useEffect(()=>{if(!n||s)return;const u=l.current;if(!u)return;const h=u.querySelector(`[data-toc-id="${CSS.escape(n)}"]`);if(h){const g=h.offsetTop-u.offsetTop,b=g+h.offsetHeight;(g<u.scrollTop||b>u.scrollTop+u.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[n,s]),t.length<2?null:s?o.jsx("div",{style:{width:ws,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:o.jsx("button",{onClick:c,title:"Show table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:13,cursor:"pointer",padding:"2px",lineHeight:1},onMouseEnter:u=>{u.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:u=>{u.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):o.jsxs("div",{ref:l,style:{width:vs,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[o.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),o.jsx("button",{onClick:c,title:"Hide table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:"0 2px",lineHeight:1},onMouseEnter:u=>{u.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:u=>{u.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),o.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:t.map((u,h)=>o.jsx("div",{"data-toc-id":u.id,onClick:()=>f(u.id),style:{padding:`2px 6px 2px ${(u.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:n===u.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:n===u.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:u.level<=2?500:400,transition:"color 0.1s"},title:u.text,onMouseEnter:g=>{n!==u.id&&(g.currentTarget.style.color="var(--text-primary)"),g.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:g=>{n!==u.id&&(g.currentTarget.style.color="var(--text-secondary)"),g.currentTarget.style.backgroundColor="transparent"},children:u.text},`${u.id}-${h}`))})]})}const ks={add:{symbol:"+",color:"var(--accent-yellow)",field:"content"},del:{symbol:"−",color:"var(--accent-red)",field:"selectedText"},rep:{symbol:"⇄",color:"var(--accent-blue)",field:"content"},com:{symbol:"?",color:"var(--accent-green)",field:"content"}};function Ts({annotations:t,annCounts:e,isSent:n,onSendAll:r,onSendSingle:s,onDelete:i}){const[l,d]=a.useState(!1),p=a.useRef(null);a.useEffect(()=>{if(!l)return;const u=h=>{p.current&&!p.current.contains(h.target)&&d(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[l]);const c=a.useCallback((u,h,g)=>{const b=ks[h],j=n(u);return o.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[o.jsx("span",{className:"plan-anno-dropdown__type",style:{color:b.color},children:b.symbol}),o.jsxs("span",{className:"plan-anno-dropdown__text",children:[g.slice(0,60),g.length>60?"...":""]}),o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!j&&s(u,h),disabled:j,title:j?"Already sent":"Send to terminal",style:j?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),o.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(u,h),title:"Delete",children:"×"})]},u)},[n,s,i]),f=(()=>{const u=t.additions[0],h=t.deletions[0],g=t.replacements[0],b=t.comments[0],j=u?u.content:h?h.selectedText:g?g.content:b?b.content:"";return j?j.slice(0,40)+(j.length>40?"...":""):""})();return o.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[o.jsxs("div",{className:`plan-anno-dropdown-trigger${l?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>d(u=>!u),title:e.total>0?`${e.total} annotations (${e.unsent} unsent)`:"No annotations",children:[o.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:f}),o.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),l&&o.jsxs("div",{className:"plan-anno-dropdown",children:[e.unsent>0&&o.jsx("div",{className:"plan-anno-dropdown__header",children:o.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",e.unsent,")"]})}),o.jsxs("div",{className:"plan-anno-dropdown__list",children:[t.additions.map(u=>c(u.id,"add",u.content)),t.deletions.map(u=>c(u.id,"del",u.selectedText)),t.replacements.map(u=>c(u.id,"rep",u.content)),t.comments.map(u=>c(u.id,"com",u.content)),e.total===0&&o.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const Cs={del:{className:"plan-deletion-card",icon:"",color:"var(--accent-red)"},rep:{className:"plan-replace-card",icon:"⇄",color:"var(--accent-blue)"},com:{className:"plan-comment-card",icon:"?",color:"var(--accent-green)"}};function vt({type:t,annotation:e,fontSize:n,onEdit:r,onRemove:s,onSend:i,isSent:l}){const d=Cs[t],[p,c]=a.useState(!1),[f,u]=a.useState(""),h=a.useRef(null),g=t==="del"?e.selectedText:e.content,b=a.useCallback(()=>{c(!0),u(g)},[g]),j=a.useCallback(()=>{const k=f.trim();k?r(e.id,k):s(e.id),c(!1)},[f,e.id,r,s]);return a.useEffect(()=>{p&&requestAnimationFrame(()=>{const k=h.current;k&&(k.focus(),k.selectionStart=k.selectionEnd=k.value.length)})},[p]),p?o.jsx("div",{className:d.className,children:o.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:f,onChange:k=>u(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),j()),k.key==="Escape"&&(k.preventDefault(),c(!1))},onBlur:j,rows:it(f),style:{fontSize:`${n}px`,flex:1}})}):o.jsxs("div",{className:d.className,children:[d.icon&&o.jsx("span",{style:{color:d.color,flexShrink:0},children:d.icon}),t==="del"?o.jsx("span",{style:{flex:1,fontSize:`${n}px`,color:d.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:e.selectedText}):t==="rep"?o.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:[o.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:e.selectedText}),o.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),o.jsx("span",{style:{color:"var(--accent-blue)"},children:e.content})]}):o.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:[o.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',e.selectedText,'"']}),o.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),o.jsx("span",{style:{color:"var(--accent-green)"},children:e.content})]}),i&&o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!l&&i(e.id),disabled:l,title:l?"Already sent":"Send to terminal",style:l?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"}),o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:b,style:{color:"var(--accent-blue)"},title:`Edit ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"✎"}),o.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>s(e.id),title:`Remove ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"×"})]})}function Es({x:t,y:e,onDelete:n,onReplace:r,onComment:s}){return o.jsxs("div",{className:"plan-selection-float",style:{top:e,left:t},children:[o.jsx("button",{className:"plan-selection-float__delete",onMouseDown:i=>{i.preventDefault(),n()},title:"Delete selection",children:"−"}),o.jsx("button",{className:"plan-selection-float__replace",onMouseDown:i=>{i.preventDefault(),r()},title:"Replace selection",children:"⇄"}),o.jsx("button",{className:"plan-selection-float__comment",onMouseDown:i=>{i.preventDefault(),s()},title:"Comment on selection",children:"?"})]})}const js=a.forwardRef(function({markdown:e,filePath:n,sessionId:r,token:s,onExecute:i,onSend:l,onRefresh:d,onClose:p,onContentSaved:c,expanded:f,readOnly:u},h){const g=D(m=>m.fontSize),[b,j]=a.useState(null),k=a.useRef(void 0),C=a.useCallback((m,x)=>{clearTimeout(k.current),j({type:m,msg:x}),k.current=setTimeout(()=>j(null),m==="ok"?2500:5e3)},[]);a.useEffect(()=>()=>clearTimeout(k.current),[]);const[v,I]=a.useState(!1),[T,L]=a.useState(""),[z,_]=a.useState(!1),B=a.useRef(null),F=D(m=>m.latency),O=`plan-edit:${r}:${n}`,N=a.useRef(void 0),S=a.useRef(void 0),w=a.useRef(!1);a.useEffect(()=>{if(!v)return;clearTimeout(N.current),N.current=setTimeout(()=>{try{localStorage.setItem(O,T)}catch{}},50),clearTimeout(S.current);const m=Math.max(200,(F??30)*3);return S.current=setTimeout(()=>{w.current||(w.current=!0,an(s,r,n,T).then(x=>{c==null||c(T,x.mtime)}).catch(()=>{}).finally(()=>{w.current=!1}))},m),()=>{clearTimeout(N.current),clearTimeout(S.current)}},[T,v,O,s,r,n,F,c]),a.useEffect(()=>{I(!1)},[n]),a.useEffect(()=>{v&&requestAnimationFrame(()=>{var m;return(m=B.current)==null?void 0:m.focus()})},[v]);const ee=a.useCallback(()=>{if(u||v)return;const m=localStorage.getItem(`plan-edit:${r}:${n}`);L(m??e),I(!0)},[u,v,e,r,n]),Y=a.useCallback(()=>{I(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${n}`)},[r,n]),P=a.useCallback(async()=>{if(!z){_(!0);try{const m=await an(s,r,n,T);c==null||c(T,m.mtime),I(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${n}`),C("ok","Saved")}catch(m){const x=m instanceof Error?m.message:"Failed to save";C("err",x)}finally{_(!1)}}},[z,s,r,n,T,c,C]),G=a.useMemo(()=>e?xn.lexer(e):[],[e]),$=a.useMemo(()=>e.split(`
|
|
29
|
+
`),[e]),U=a.useMemo(()=>ys(e),[e]),H=a.useMemo(()=>{const m=new Map,x=new Map;return G.forEach((M,R)=>{if(M.type==="heading"){const ae=Mn(M.text||""),te=Ln(ae,x);m.set(R,te)}}),m},[G]),V=a.useRef(new Set),ne=a.useRef(!1),[K,se]=a.useState(()=>{try{const m=localStorage.getItem(qe(r,n)),x=m?JSON.parse(m):jt;return V.current=lt(x),x.replacements||(x.replacements=[]),x.comments||(x.comments=[]),x}catch{return jt}});xs({sessionId:r,filePath:n,token:s,annotations:K,annLoadedRef:ne,setAnnotations:se,baselineIdsRef:V});const[we,ye]=a.useState(0),De=a.useMemo(()=>{const m=V.current,x=K.additions.length+K.deletions.length+K.replacements.length+K.comments.length;let M=0;return K.additions.forEach(R=>{m.has(R.id)&&M++}),K.deletions.forEach(R=>{m.has(R.id)&&M++}),K.replacements.forEach(R=>{m.has(R.id)&&M++}),K.comments.forEach(R=>{m.has(R.id)&&M++}),{total:x,sent:M,unsent:x-M}},[K,we]),[A,W]=a.useState(null),[X,Z]=a.useState(""),q=a.useRef(null),[Q,be]=a.useState(null),[Ee,je]=a.useState(""),Ae=a.useRef(null),[le,Se]=a.useState(null),ue=a.useRef(null),He=a.useRef(0),_e=a.useRef(null);a.useEffect(()=>{const m=ue.current;if(!m)return;let x;const M=()=>{clearTimeout(x),x=setTimeout(()=>{const R=Zt(r,n);if(m.scrollTop>0)try{localStorage.setItem(R,String(m.scrollTop))}catch{}else localStorage.removeItem(R)},50)};return m.addEventListener("scroll",M,{passive:!0}),()=>{clearTimeout(x),m.removeEventListener("scroll",M)}},[r,n]),a.useEffect(()=>{if(!G.length)return;const m=localStorage.getItem(Zt(r,n));if(!m)return;const x=Number(m),M=ue.current;if(!M||(M.scrollTop=x,M.scrollTop>=x-10))return;let R;const ae=()=>{M.scrollTop=x,te.disconnect()},te=new MutationObserver(()=>{clearTimeout(R),R=setTimeout(ae,80)});te.observe(M,{childList:!0,subtree:!0});const ie=setTimeout(ae,500);return()=>{clearTimeout(R),clearTimeout(ie),te.disconnect()}},[r,n,G.length]),a.useEffect(()=>{A!=null&&requestAnimationFrame(()=>{var m;return(m=q.current)==null?void 0:m.focus()})},[A]),a.useEffect(()=>{Q&&requestAnimationFrame(()=>{var m;return(m=Ae.current)==null?void 0:m.focus()})},[Q]);const Oe=a.useRef({annotations:K,activeInsert:A,insertText:X,pendingAction:Q,pendingText:Ee,tokens:G,filePath:n,sessionId:r,token:s});Oe.current={annotations:K,activeInsert:A,insertText:X,pendingAction:Q,pendingText:Ee,tokens:G,filePath:n,sessionId:r,token:s},a.useEffect(()=>()=>{const m=Oe.current;let x=m.annotations,M=!1;if(m.activeInsert!=null&&m.insertText.trim()){const R=tt(m.tokens,m.activeInsert+1);x={...x,additions:[...x.additions,{id:Te(),afterTokenIndex:m.activeInsert,sourceLine:R,content:m.insertText.trim()}]},M=!0}if(m.pendingAction&&m.pendingText.trim()){const R=m.pendingAction,ae=m.pendingText.trim();R.type==="replace"?x={...x,replacements:[...x.replacements,{id:Te(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ae}]}:x={...x,comments:[...x.comments,{id:Te(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ae}]},M=!0}if(M){const R=JSON.stringify(x);try{localStorage.setItem(qe(m.sessionId,m.filePath),R)}catch{}Nn(m.token,m.sessionId,m.filePath,R,Date.now()).catch(()=>{})}},[]);const Ne=a.useCallback(m=>{if(!X.trim()){W(null),Z("");return}const x=tt(G,m+1);se(M=>({...M,additions:[...M.additions,{id:Te(),afterTokenIndex:m,sourceLine:x,content:X.trim()}]})),W(null),Z("")},[X,G]),Le=a.useCallback(m=>{se(x=>({...x,additions:x.additions.filter(M=>M.id!==m)}))},[]),Ye=a.useCallback((m,x)=>{se(M=>({...M,additions:M.additions.map(R=>R.id===m?{...R,id:Te(),content:x}:R)}))},[]),pt=a.useCallback(()=>{var m;le&&(se(x=>({...x,deletions:[...x.deletions,{id:Te(),tokenIndices:le.tokenIndices,startLine:le.startLine,endLine:le.endLine,selectedText:le.text.slice(0,80)}]})),Se(null),(m=window.getSelection())==null||m.removeAllRanges())},[le]),y=a.useCallback(m=>{var x;le&&(be({type:m,tokenIndices:le.tokenIndices,startLine:le.startLine,endLine:le.endLine,text:le.text.slice(0,80)}),je(""),Se(null),(x=window.getSelection())==null||x.removeAllRanges())},[le]),E=a.useCallback(()=>{if(!Q)return;const m=Ee.trim();if(!m){be(null),je("");return}Q.type==="replace"?se(x=>({...x,replacements:[...x.replacements,{id:Te(),tokenIndices:Q.tokenIndices,startLine:Q.startLine,endLine:Q.endLine,selectedText:Q.text,content:m}]})):se(x=>({...x,comments:[...x.comments,{id:Te(),tokenIndices:Q.tokenIndices,startLine:Q.startLine,endLine:Q.endLine,selectedText:Q.text,content:m}]})),be(null),je("")},[Q,Ee]),J=a.useCallback(m=>{se(x=>({...x,replacements:x.replacements.filter(M=>M.id!==m)}))},[]),re=a.useCallback((m,x)=>{se(M=>({...M,replacements:M.replacements.map(R=>R.id===m?{...R,id:Te(),content:x}:R)}))},[]),oe=a.useCallback(m=>{se(x=>({...x,comments:x.comments.filter(M=>M.id!==m)}))},[]),ke=a.useCallback((m,x)=>{se(M=>({...M,comments:M.comments.map(R=>R.id===m?{...R,id:Te(),content:x}:R)}))},[]),ce=a.useCallback(m=>{se(x=>({...x,deletions:x.deletions.filter(M=>M.id!==m)}))},[]),he=a.useCallback((m,x)=>{se(M=>({...M,deletions:M.deletions.map(R=>R.id===m?{...R,id:Te(),selectedText:x}:R)}))},[]),pe=a.useCallback(m=>{let x=m instanceof Element?m:m.parentElement;for(;x&&x!==ue.current;){if(x.hasAttribute("data-token-index"))return x;x=x.parentElement}return null},[]),de=a.useCallback(()=>{const m=window.getSelection();if(!m||m.isCollapsed||!ue.current){Se(null);return}const x=m.toString().trim();if(!x){Se(null);return}const M=m.getRangeAt(0);if(!ue.current.contains(M.commonAncestorContainer)){Se(null);return}const R=pe(M.startContainer),ae=pe(M.endContainer);if(!R||!ae){Se(null);return}const te=parseInt(R.getAttribute("data-token-index")||"0",10),ie=parseInt(ae.getAttribute("data-token-index")||"0",10),Mt=[];for(let bt=Math.min(te,ie);bt<=Math.max(te,ie);bt++)Mt.push(bt);const Un=tt(G,Math.min(te,ie)),Hn=tt(G,Math.max(te,ie)+1),Dt=M.getBoundingClientRect(),gt=ue.current,At=gt.getBoundingClientRect();navigator.clipboard.writeText(x).catch(()=>{});const Xe=_e.current,zt=Xe&&Date.now()-Xe.time<500;He.current=Date.now(),Se({x:(zt?Xe.x:Dt.right)-At.left+gt.scrollLeft+6,y:(zt?Xe.y:Dt.top)-At.top+gt.scrollTop-44,tokenIndices:Mt,startLine:Un,endLine:Hn,text:x})},[G,pe]),ve=a.useRef(void 0);a.useEffect(()=>{const m=()=>{ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>{const x=window.getSelection();if(!x||x.isCollapsed||!ue.current){if(Date.now()-He.current<300)return;Se(null);return}const M=x.anchorNode;M&&ue.current.contains(M)&&de()},120)};return document.addEventListener("selectionchange",m),()=>{document.removeEventListener("selectionchange",m),ve.current&&clearTimeout(ve.current)}},[de]);const Ke=D(m=>m.theme);ms(ue,G,Ke);const Fe=a.useCallback(()=>{const m=V.current;return{additions:K.additions.filter(x=>!m.has(x.id)),deletions:K.deletions.filter(x=>!m.has(x.id)),replacements:K.replacements.filter(x=>!m.has(x.id)),comments:K.comments.filter(x=>!m.has(x.id))}},[K]),mt=a.useCallback(async()=>{const m=Fe();if(!en(m))return;const x=Qt(m,$),M=rn(n);try{const{path:R}=await Xt(s,r,M,x),ae=nn(n,R);i(ae),V.current=lt(K),ye(ie=>ie+1);const te=m.additions.length+m.deletions.length+m.replacements.length+m.comments.length;C("ok",`Sent ${te} annotation(s)`)}catch(R){const ae=R instanceof Error?R.message:"Failed to send";C("err",ae)}},[Fe,K,$,i,n,s,r,C]),Be=a.useCallback(async(m,x)=>{if(!l)return;const M={additions:[],deletions:[],replacements:[],comments:[]};if(x==="add"){const te=K.additions.find(ie=>ie.id===m);if(!te)return;M.additions.push(te)}else if(x==="del"){const te=K.deletions.find(ie=>ie.id===m);if(!te)return;M.deletions.push(te)}else if(x==="rep"){const te=K.replacements.find(ie=>ie.id===m);if(!te)return;M.replacements.push(te)}else{const te=K.comments.find(ie=>ie.id===m);if(!te)return;M.comments.push(te)}const R=Qt(M,$),ae=rn(n);try{const{path:te}=await Xt(s,r,ae,R);l(nn(n,te)),V.current.add(m),ye(ie=>ie+1),C("ok","Sent 1 annotation")}catch(te){const ie=te instanceof Error?te.message:"Failed to send";C("err",ie)}},[l,n,K,$,s,r,C]),Fn=a.useCallback((m,x)=>{x==="add"?Le(m):x==="del"?ce(m):x==="rep"?J(m):oe(m)},[Le,ce,J,oe]);a.useImperativeHandle(h,()=>({getSummary:()=>{const m=Fe();return en(m)?"[pending annotations]":""},handleEscape:()=>v?(Y(),!0):Q?(E(),!0):A!=null?(Ne(A),!0):!1,getScrollTop:()=>{var m;return((m=ue.current)==null?void 0:m.scrollTop)??0},setScrollTop:m=>{requestAnimationFrame(()=>{ue.current&&(ue.current.scrollTop=m)})}}),[Fe,v,Y,A,Ne,Q,E]);const Bn=a.useMemo(()=>{const m=new Set;return K.deletions.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[K.deletions]),Pn=a.useMemo(()=>{const m=new Set;return K.replacements.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[K.replacements]),Wn=a.useMemo(()=>{const m=new Set;return K.comments.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[K.comments]),Nt=a.useMemo(()=>{const m=new Map;return K.additions.forEach(x=>{const M=m.get(x.afterTokenIndex)||[];M.push(x),m.set(x.afterTokenIndex,M)}),m},[K.additions]),Lt=De.unsent>0,ht=a.useCallback(m=>V.current.has(m),[]);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[o.jsxs("div",{className:"plan-anno-toolbar",children:[o.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:n,children:n.split("/").pop()||n}),b&&o.jsx("span",{style:{fontSize:"10px",color:b.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:b.type==="err"?"pointer":void 0},title:b.type==="err"?"Click to copy":b.msg,onClick:b.type==="err"?()=>{navigator.clipboard.writeText(b.msg).catch(()=>{}),C("ok","Copied")}:void 0,children:b.msg}),v?o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"pane-btn",onClick:P,disabled:z,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:z?"Saving...":"Save"}),o.jsx("button",{className:"pane-btn",onClick:Y,disabled:z,title:"Cancel (Esc)",children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[d&&o.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),!u&&o.jsx("button",{className:"pane-btn",onClick:ee,title:"Edit file (double-click content)",children:"Edit"}),o.jsx("button",{className:"pane-btn",onClick:mt,disabled:!Lt,title:"Send all annotations",style:Lt?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),o.jsx(Ts,{annotations:K,annCounts:De,isSent:ht,onSendAll:mt,onSendSingle:Be,onDelete:Fn}),p&&o.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await mt(),p()},title:"Send annotations & close file",children:"×"})]})]}),o.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[v?o.jsx("textarea",{ref:B,className:"plan-edit-textarea",style:{fontSize:`${g}px`},value:T,onChange:m=>L(m.target.value),onKeyDown:m=>{if(m.key==="s"&&(m.ctrlKey||m.metaKey)){m.preventDefault(),P();return}if(m.key==="Escape"){m.preventDefault(),Y();return}},spellCheck:!1}):o.jsxs("div",{ref:ue,className:`plan-anno-content md-preview${A!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${g}px`,minWidth:0},onMouseUp:m=>{_e.current={x:m.clientX,y:m.clientY,time:Date.now()},de()},onDoubleClick:m=>{u||m.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||ee()},children:[!u&&o.jsx(on,{index:-1,active:A===-1,additions:Nt.get(-1),onOpen:()=>{W(-1),Z("")},onSubmit:()=>Ne(-1),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?m=>Be(m,"add"):void 0,isSent:ht,insertText:X,setInsertText:Z,textareaRef:A===-1?q:void 0,expanded:f,alwaysShow:G.length===0,fontSize:g}),G.map((m,x)=>{const M=bs(m);return o.jsxs("div",{children:[o.jsx("div",{"data-token-index":x,id:H.get(x),className:Bn.has(x)?"plan-block--deleted":Pn.has(x)?"plan-block--replaced":Wn.has(x)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:M}}),K.deletions.filter(R=>R.tokenIndices[0]===x).map(R=>o.jsx(vt,{type:"del",annotation:R,fontSize:g,onEdit:he,onRemove:ce,onSend:l?ae=>Be(ae,"del"):void 0,isSent:V.current.has(R.id)},R.id)),K.replacements.filter(R=>R.tokenIndices[0]===x).map(R=>o.jsx(vt,{type:"rep",annotation:R,fontSize:g,onEdit:re,onRemove:J,onSend:l?ae=>Be(ae,"rep"):void 0,isSent:V.current.has(R.id)},R.id)),K.comments.filter(R=>R.tokenIndices[0]===x).map(R=>o.jsx(vt,{type:"com",annotation:R,fontSize:g,onEdit:ke,onRemove:oe,onSend:l?ae=>Be(ae,"com"):void 0,isSent:V.current.has(R.id)},R.id)),Q&&Q.tokenIndices[0]===x&&o.jsxs("div",{className:Q.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[o.jsx("span",{style:{color:Q.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:Q.type==="replace"?"⇄":"?"}),o.jsx("textarea",{ref:Ae,className:"plan-annotation-textarea",value:Ee,onChange:R=>je(R.target.value),onKeyDown:R=>{if(R.key==="Enter"&&(R.ctrlKey||R.metaKey)){R.preventDefault(),E();return}if(R.key==="Escape"){R.preventDefault(),E();return}},onBlur:E,placeholder:Q.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:it(Ee),style:{fontSize:`${g}px`,flex:1}})]}),!u&&o.jsx(on,{index:x,active:A===x,additions:Nt.get(x),onOpen:()=>{W(x),Z("")},onSubmit:()=>Ne(x),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?R=>Be(R,"add"):void 0,isSent:ht,insertText:X,setInsertText:Z,textareaRef:A===x?q:void 0,expanded:f,fontSize:g})]},x)}),!u&&le&&o.jsx(Es,{x:le.x,y:le.y,onDelete:pt,onReplace:()=>y("replace"),onComment:()=>y("comment")})]}),!v&&o.jsx(Ss,{headings:U,scrollRef:ue})]})]})});function on({index:t,active:e,additions:n,onOpen:r,onSubmit:s,onRemoveAddition:i,onEditAddition:l,onSendSingle:d,isSent:p,insertText:c,setInsertText:f,textareaRef:u,expanded:h,alwaysShow:g,fontSize:b=14}){const[j,k]=a.useState(null),[C,v]=a.useState(""),I=a.useRef(null),T=Ct(),L=Ct();a.useEffect(()=>{j&&(T.clearUndo(),requestAnimationFrame(()=>{const N=I.current;N&&(N.focus(),N.selectionStart=N.selectionEnd=N.value.length)}))},[j]),a.useEffect(()=>{e&&L.clearUndo()},[e]);const z=a.useCallback(N=>{v(S=>(T.pushUndo(S),N))},[T]),_=a.useCallback(N=>{L.pushUndo(c),f(N)},[c,f,L]),B=a.useCallback(N=>{k(N.id),v(N.content)},[]),F=a.useCallback(()=>{if(!j)return;const N=C.trim();N?l(j,N):i(j),k(null),v("")},[j,C,l,i]),O=a.useCallback(()=>{k(null),v("")},[]);return o.jsxs("div",{className:`plan-insert-zone${g?" plan-insert-zone--empty":""}`,"data-zone-index":t,children:[n==null?void 0:n.map(N=>o.jsx("div",{className:"plan-annotation-card",children:j===N.id?o.jsx("textarea",{ref:I,className:"plan-annotation-textarea",value:C,onChange:S=>z(S.target.value),onKeyDown:S=>{if(S.key==="Enter"&&(S.ctrlKey||S.metaKey)){S.preventDefault(),F();return}if(S.key==="Escape"){S.preventDefault(),O();return}if(S.key==="Tab"){Et(S,z);return}},onBlur:F,rows:it(C),style:{fontSize:`${b}px`,flex:1,...h?{minWidth:300}:void 0}}):o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{flex:1,fontSize:`${b}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>B(N),title:"Double-click to edit",children:N.content}),d&&(()=>{const S=(p==null?void 0:p(N.id))??!1;return o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!S&&d(N.id),disabled:S,title:S?"Already sent":"Send to terminal",style:S?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>B(N),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),o.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(N.id),children:"×"})]})},N.id)),e?o.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:o.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:c,onChange:N=>_(N.target.value),onKeyDown:N=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)){N.preventDefault(),s();return}if(N.key==="Escape"){N.preventDefault(),s();return}if(N.key==="Tab"){Et(N,_);return}},onBlur:s,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:it(c),style:{fontSize:`${b}px`,...h?{minWidth:300}:void 0}})}):g&&!(n!=null&&n.length)?o.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:r,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):o.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function Re(t,e,n){const r=n?{path:n}:void 0;return ge.get(t,e,"files",r)}function Is(t,e,n,r){return new Promise((s,i)=>{const l=new FormData;for(const p of n)l.append("files",p);const d=new XMLHttpRequest;d.open("POST",`${Me}/api/sessions/${encodeURIComponent(e)}/upload`),d.setRequestHeader("Authorization",`Bearer ${t}`),d.upload.addEventListener("progress",p=>{p.lengthComputable&&r&&r(Math.round(p.loaded/p.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?s():i(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>i(new Error("Upload network error"))),d.addEventListener("abort",()=>i(new Error("Upload aborted"))),d.send(l)})}async function ln(t,e){return(await ge.get(t,e,"cwd")).cwd}async function Rs(t,e,n){return ge.post(t,e,"touch",{name:n})}async function Ns(t,e,n){return ge.post(t,e,"mkdir",{path:n})}async function Ls(t,e,n){return ge.del(t,e,"rm",{path:n})}async function Ms(t,e){const n=await ge.getBlob(t,e,"download-cwd"),r=await n.blob(),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s;const l=n.headers.get("Content-Disposition"),d=l==null?void 0:l.match(/filename="(.+)"/);i.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(s)}async function Ds(t,e,n){const s=await(await ge.getBlob(t,e,"download",{path:n})).blob(),i=URL.createObjectURL(s),l=document.createElement("a");l.href=i,l.download=n.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}function Dn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function As(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function An(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function zs({sessionId:t,token:e,planDir:n,selectedFile:r,onSelectFile:s,onCreateFile:i,onDeleteFile:l}){const[d,p]=a.useState([]),[c,f]=a.useState(!0),[u,h]=a.useState(""),[g,b]=a.useState(!1),j=a.useRef(null),[k,C]=a.useState(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n))return w}return n});a.useEffect(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n)){C(w);return}}C(n)},[r,n]);const v=a.useCallback(async()=>{if(!(!e||!k)){f(!0);try{const ee=(await Re(e,t,k)).files.filter(Y=>Y.type==="file"&&(Y.name.toLowerCase().endsWith(".md")||Y.name===".index.json")||Y.type==="directory").sort((Y,P)=>{const G=Y.type==="file"&&Y.name===".index.json",$=P.type==="file"&&P.name===".index.json";return G&&!$?-1:!G&&$?1:Y.type==="directory"&&P.type!=="directory"?-1:Y.type!=="directory"&&P.type==="directory"?1:Y.name.localeCompare(P.name)});p(ee)}catch{p([])}finally{f(!1)}}},[e,t,k]);a.useEffect(()=>{v()},[v]),a.useEffect(()=>{const w=setInterval(v,5e3);return()=>clearInterval(w)},[v]);const I=a.useCallback(()=>{const w=n.substring(0,n.lastIndexOf("/")+1);return k.startsWith(w)?k.substring(w.length):k},[n,k]),T=a.useCallback(async()=>{const w=u.trim();if(!w)return;const ee=w.endsWith(".md")?w:`${w}.md`;b(!0);try{const Y=await Rs(e,t,`${I()}/${ee}`);Y.ok&&(h(""),await v(),i(Y.path))}catch{}finally{b(!1)}},[u,e,t,I,v,i]),L=a.useCallback(async()=>{const w=u.trim().replace(/\/+$/,"");if(w){b(!0);try{await Ns(e,t,`${I()}/${w}`),h(""),await v()}catch{}finally{b(!1)}}},[u,e,t,I,v]),z=a.useCallback(async w=>{const ee=`${k}/${w.name}`,Y=w.type==="directory"?`folder "${w.name}" and all its contents`:`"${w.name}"`;if(window.confirm(`Delete ${Y}?`))try{await Ls(e,t,ee),l==null||l(ee),await v()}catch{}},[e,t,k,v,l]),_=a.useCallback(w=>{C(ee=>`${ee}/${w}`)},[]),B=a.useCallback(()=>{k!==n&&C(w=>w.substring(0,w.lastIndexOf("/")))},[k,n]),F=n.split("/").pop()||"AiTasks",O=(()=>{const w=n.split("/");return w.length>=2?w[w.length-2]+"/":""})(),N=k===n?O+F+"/":O+F+"/"+k.substring(n.length+1)+"/",S=r?r.split("/").pop():null;return o.jsxs("div",{className:"plan-file-browser",children:[o.jsxs("div",{className:"plan-file-browser__header",children:[o.jsx("span",{className:"plan-file-browser__title",title:N,children:N}),o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:v,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),o.jsxs("div",{className:"plan-file-browser__create",children:[o.jsx("input",{ref:j,className:"plan-file-browser__input",value:u,onChange:w=>h(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),T())},placeholder:"name",disabled:g}),o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:T,disabled:g||!u.trim(),title:"Create new .md file",style:u.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),o.jsx("button",{className:"pane-btn pane-btn--sm",onClick:L,disabled:g||!u.trim(),title:"Create new folder",style:u.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),o.jsxs("div",{className:"plan-file-browser__list",children:[c&&d.length===0&&o.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&d.length===0&&o.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),k!==n&&o.jsxs("div",{className:"plan-file-browser__item",onClick:B,title:"Go up to parent directory",style:{cursor:"pointer"},children:[o.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),o.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(w=>{const ee=`${k}/${w.name}`,Y=w.type==="file"&&w.name===S,P=w.type==="directory";return o.jsxs("div",{className:`plan-file-browser__item${Y?" plan-file-browser__item--active":""}`,onClick:()=>P?_(w.name):s(ee),title:P?`Open folder ${w.name}`:w.name,style:{cursor:"pointer"},children:[o.jsx("span",{className:"plan-file-browser__icon",children:P?"📁":w.name===".index.json"?"🔒":"□"}),o.jsxs("span",{className:"plan-file-browser__name",children:[w.name,P?"/":""]}),!P&&o.jsx("span",{className:"plan-file-browser__size",children:Dn(w.size)}),!w.name.startsWith(".")&&o.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:G=>{G.stopPropagation(),z(w)},title:`Delete ${w.name}`,children:"×"})]},w.name)})]})]})}const wt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},$s=200;function _s(){const[t,e]=a.useState(wt),n=a.useRef("lines"),r=a.useRef([]),s=a.useRef(""),i=a.useRef(""),l=a.useRef([]),d=a.useRef(0),p=a.useRef(0),c=a.useRef(null),f=a.useRef(null),u=a.useCallback(()=>{const C=n.current;e(v=>({...v,receivedBytes:d.current,...C==="lines"?{lines:[...r.current]}:{},...C==="content"?{content:i.current}:{}}))},[]),h=a.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,u()},$s))},[u]),g=a.useCallback(C=>{n.current=C,r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...wt,mode:C,status:"streaming"})},[]),b=a.useCallback(C=>{d.current+=C.length;const v=n.current;if(v==="lines"){const T=f.current.decode(C,{stream:!0}).split(`
|
|
30
|
+
`);T[0]=s.current+T[0],s.current=T.pop(),T.length>0&&r.current.push(...T)}else if(v==="content"){const I=f.current.decode(C,{stream:!0});i.current+=I}else l.current.push(new Uint8Array(C));h()},[h]),j=a.useCallback(C=>{switch(C.type){case"file-stream-start":p.current=C.size,e(v=>({...v,totalSize:C.size,mtime:C.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const v=n.current;let I=r.current,T=i.current,L=null;if(v==="lines"){const z=f.current.decode(),_=s.current+z;_&&(I=[...I,_],r.current=I),s.current=""}else if(v==="content"){const z=f.current.decode();T=i.current+z,i.current=T}else{const z=l.current.reduce((B,F)=>B+F.length,0);L=new Uint8Array(z);let _=0;for(const B of l.current)L.set(B,_),_+=B.length;l.current=[]}e({status:"complete",mode:v,lines:v==="lines"?[...I]:[],content:v==="content"?T:"",buffer:v==="binary"?L:null,totalSize:p.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(v=>({...v,status:"error",error:C.error}));break}},[]),k=a.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=null,e(wt)},[]);return{state:t,startStream:g,handleChunk:b,handleControl:j,reset:k}}function cn({label:t,percent:e}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[o.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:t}),e!=null&&o.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[o.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),o.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function Os({sessionId:t,token:e,connected:n,onRequestFileStream:r,onSendToTerminal:s}){const i=_s(),[l,d]=a.useState(!1),[p,c]=a.useState(null),[f,u]=a.useState(null),[h,g]=a.useState(""),[b,j]=a.useState(!1),[k,C]=a.useState(!1),v=a.useRef(null),I="plan-selected-file",T=a.useRef(void 0);a.useEffect(()=>{if(f)return clearTimeout(T.current),T.current=setTimeout(()=>{try{localStorage.setItem(I,f)}catch{}},50),()=>clearTimeout(T.current)},[f]);const L=a.useRef(null);a.useEffect(()=>{L.current=null;let A=!1;return j(!0),C(!1),(async()=>{let W="";try{const X=await Re(e,t);if(A)return;if(W=X.home||"",X.files.find(q=>q.name==="AiTasks"&&q.type==="directory")){const q=X.cwd+"/AiTasks";c(q);const Q=localStorage.getItem(I);Q&&Q.startsWith(q+"/")&&u(Q)}else c(null),u(null),C(!0)}catch{c(null)}finally{A||j(!1)}try{if(A)return;if(W){const X=`${W}/.claude/plugins/installed_plugins.json`,Z=await rt(e,t,X,0);if(!A&&Z)try{const q=JSON.parse(Z.content);"ai-cli-task@moonview"in(q.plugins||q)||d(!0)}catch{d(!0)}}}catch{}})(),()=>{A=!0}},[t,e]),a.useEffect(()=>{if(!k||!n)return;const A=setInterval(async()=>{try{const W=await Re(e,t);if(W.files.find(Z=>Z.name==="AiTasks"&&Z.type==="directory")){const Z=W.cwd+"/AiTasks";c(Z),C(!1);const q=localStorage.getItem(I);q&&q.startsWith(Z+"/")&&u(q)}}catch{}},3e3);return()=>clearInterval(A)},[k,n,e,t,I]),a.useEffect(()=>(Wr(t,i.handleChunk,i.handleControl),()=>Ur(t)),[t,i.handleChunk,i.handleControl]),a.useEffect(()=>{!f||!n||L.current===f&&h||(L.current=f,i.reset(),i.startStream("content"),r==null||r(f))},[f,n]);const z=a.useRef(0);a.useEffect(()=>{i.state.status==="complete"&&f&&(g(i.state.content),z.current=Date.now())},[i.state.status,i.state.content,f]),a.useEffect(()=>{if(!f||!n||!h)return;const A=setInterval(async()=>{if(z.current)try{const W=await rt(e,t,f,z.current);W&&(g(W.content),z.current=W.mtime)}catch{}},3e3);return()=>clearInterval(A)},[f,n,h,e,t]);const _=a.useRef(new Map),B=a.useCallback(()=>{var W,X;if(!f)return;const A=((X=(W=v.current)==null?void 0:W.getScrollTop)==null?void 0:X.call(W))??0;A>0&&_.current.set(f,A)},[f]);a.useEffect(()=>{if(!f||!h)return;const A=_.current.get(f);A!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var W,X;(X=(W=v.current)==null?void 0:W.setScrollTop)==null||X.call(W,A)})})},[f,h]);const F=a.useCallback(A=>{A!==f&&(B(),u(A),g(""),L.current=null)},[f,B]),O=a.useCallback(A=>{f&&(f===A||f.startsWith(A+"/"))&&(u(null),g(""),L.current=null)},[f]),N=a.useCallback(A=>{u(A),g(""),L.current=null},[]),S=a.useCallback(A=>{A&&(s==null||s(A))},[s]),w=a.useCallback((A,W)=>{g(A),z.current=W},[]),ee=a.useCallback(()=>{B(),u(null),g(""),L.current=null},[B]),Y=a.useCallback(()=>{!f||!n||(L.current=null,g(""),i.reset(),i.startStream("content"),r==null||r(f),L.current=f)},[f,n,i,r]),[P,G]=a.useState(()=>{const A=localStorage.getItem(`plan-fb-width-${t}`);if(A){const W=Number(A);if(Number.isFinite(W)&&W>=60&&W<=300)return W}return 130}),$=a.useRef(P);if(P!==$.current){$.current=P;try{localStorage.setItem(`plan-fb-width-${t}`,String(Math.round(P)))}catch{}}const U=a.useCallback(A=>{A.preventDefault();const W=A.clientX,X=P;document.body.classList.add("resizing-panes");const Z=Q=>{const be=Q.clientX-W;G(Math.min(300,Math.max(60,X+be)))},q=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",Z),document.removeEventListener("mouseup",q)};document.addEventListener("mousemove",Z),document.addEventListener("mouseup",q)},[P]),H=a.useMemo(()=>{if(!p||!f||!f.startsWith(p+"/"))return null;const A=f.substring(p.length+1),W=A.indexOf("/");if(W<0)return null;const X=A.substring(0,W);return!X||X.startsWith(".")?null:{name:X,dir:`${p}/${X}`}},[p,f]),V=H==null?void 0:H.dir,[ne,K]=a.useState(null),se=a.useRef(0);a.useEffect(()=>{K(null),se.current=0},[V]),a.useEffect(()=>{if(!V||!n)return;let A=!1;const W=async()=>{try{const Z=await rt(e,t,`${V}/.index.json`,se.current||void 0);if(A)return;if(Z){se.current=Z.mtime;try{const q=JSON.parse(Z.content);K({status:q.status||"draft",phase:q.phase||"",type:q.type||"",completed_steps:q.completed_steps||0,title:q.title||""})}catch{}}}catch{}};W();const X=setInterval(W,3e3);return()=>{A=!0,clearInterval(X)}},[V,n,e,t]);const[we,ye]=a.useState(null);a.useEffect(()=>{ye(null)},[V]),a.useEffect(()=>{if(!V||!n)return;let A=!1;const W=async()=>{try{const Z=await rt(e,t,`${V}/.auto-signal`);if(A)return;if(Z)try{const q=JSON.parse(Z.content);ye({step:q.step,result:q.result,next:q.next,iteration:q.iteration})}catch{ye(null)}}catch{A||ye(null)}};W();const X=setInterval(W,2e3);return()=>{A=!0,clearInterval(X)}},[V,n,e,t]);const De=a.useCallback(()=>{!H||!s||s(`/ai-cli-task:auto AiTasks/${H.name}`)},[H,s]);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[l&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",fontSize:12,flexShrink:0},children:[o.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),o.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{s&&s("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),d(!1)},children:"Install"}),o.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>d(!1),children:"×"})]}),o.jsxs("div",{className:"plan-overlay-body",children:[p&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:P,flexShrink:0,overflow:"hidden"},children:o.jsx(zs,{sessionId:t,token:e,planDir:p,selectedFile:f,onSelectFile:F,onCreateFile:N,onDeleteFile:O})}),o.jsx("div",{onMouseDown:U,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:A=>{A.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="var(--border)"}})]}),o.jsx("div",{className:"plan-overlay-center",children:b?o.jsx(cn,{label:"Loading AiTasks/..."}):k?o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[o.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),o.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",o.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/ai-cli-task:init <name>"})," in the terminal to create a task"]})]}):f&&!h&&(i.state.status==="streaming"||i.state.status==="idle")?o.jsx(cn,{label:`Loading ${f.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):f?o.jsx(js,{ref:v,markdown:h,filePath:f,sessionId:t,token:e,onExecute:S,onSend:s,onRefresh:Y,onClose:ee,onContentSaved:w,readOnly:f.endsWith("/.index.json")}):o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:o.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]}),H&&ne&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--border)",fontSize:11,flexShrink:0,minHeight:22},children:[o.jsx("span",{style:{color:"var(--text-primary)",fontWeight:500},title:ne.title,children:H.name}),o.jsx("span",{style:{color:ne.status==="complete"?"var(--accent-green)":ne.status==="executing"||ne.status==="review"?"var(--accent-blue)":ne.status==="blocked"?"var(--accent-red)":ne.status==="cancelled"?"var(--text-secondary)":"var(--accent-yellow)",fontWeight:500},children:ne.status}),ne.phase&&o.jsxs("span",{style:{color:"var(--text-secondary)"},children:["(",ne.phase,")"]}),we?o.jsxs("span",{style:{color:"var(--accent-yellow)"},children:[we.step,":",we.result," → ",we.next,we.iteration!=null&&` #${we.iteration}`]}):o.jsx("button",{className:"pane-btn",onClick:De,disabled:!n||ne.status==="complete"||ne.status==="cancelled",style:{color:"var(--accent-green)",fontWeight:500,fontSize:11,...!n||ne.status==="complete"||ne.status==="cancelled"?{opacity:.4}:{}},title:"Start auto mode for this task",children:"Auto ▶"}),ne.completed_steps>0&&o.jsxs("span",{style:{color:"var(--text-secondary)",marginLeft:"auto"},children:["step ",ne.completed_steps]})]})]})}async function Fs(t,e){try{return(await ge.get(t,e,"draft")).content??""}catch{return""}}async function dn(t,e,n){try{await ge.put(t,e,"draft",{content:n})}catch{}}const Rt="chat-history",un=50;function zn(){try{const t=localStorage.getItem(Rt);return t?JSON.parse(t):[]}catch{return[]}}function Bs(t){const n=zn().filter(r=>r.text!==t);n.unshift({text:t,ts:Date.now()}),n.length>un&&(n.length=un),localStorage.setItem(Rt,JSON.stringify(n))}const fn=[{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:"/ai-cli-task:ai-cli-task",desc:"Task lifecycle management (13 skills)"},{cmd:"/ai-cli-task:init",desc:"Initialize task module + branch"},{cmd:"/ai-cli-task:plan",desc:"Generate implementation plan"},{cmd:"/ai-cli-task:research",desc:"Collect external references"},{cmd:"/ai-cli-task:check",desc:"Check feasibility (post-plan/mid/post-exec)"},{cmd:"/ai-cli-task:verify",desc:"Run domain-adapted tests"},{cmd:"/ai-cli-task:exec",desc:"Execute implementation plan"},{cmd:"/ai-cli-task:merge",desc:"Merge task branch to main"},{cmd:"/ai-cli-task:report",desc:"Generate completion report"},{cmd:"/ai-cli-task:auto",desc:"Autonomous full lifecycle loop"},{cmd:"/ai-cli-task:cancel",desc:"Cancel task + optional cleanup"},{cmd:"/ai-cli-task:list",desc:"Query task status (read-only)"},{cmd:"/ai-cli-task:annotate",desc:"Process Plan panel annotations"},{cmd:"/ai-cli-task:summarize",desc:"Regenerate context summary"}],Ps=a.forwardRef(function({onSend:e,onContentChange:n,sessionId:r,token:s},i){const l=D(y=>y.fontSize),[d,p]=a.useState(""),c=a.useRef(null),f=a.useRef(void 0),u=a.useRef(!1),h=a.useRef(!1),{pushUndo:g,popUndo:b}=Ct(),j=a.useRef(d);j.current=d;const k=a.useCallback(()=>g(j.current),[g]),[C,v]=a.useState(!1),[I,T]=a.useState(""),[L,z]=a.useState(0),[_,B]=a.useState(!1),[F,O]=a.useState([]),[N,S]=a.useState(0),[w,ee]=a.useState(""),Y=a.useRef(null),P=a.useMemo(()=>{if(!w)return F;const y=w.toLowerCase();return F.filter(E=>E.text.toLowerCase().includes(y))},[F,w]),[G,$]=a.useState(!1),[U,H]=a.useState(""),[V,ne]=a.useState(""),[K,se]=a.useState(0),[we,ye]=a.useState([]),[De,A]=a.useState(!1),W=a.useRef(""),X=a.useRef(null),Z=a.useMemo(()=>{if(!I)return fn;const y=I.toLowerCase();return fn.filter(E=>E.cmd.toLowerCase().includes(y)||E.desc.toLowerCase().includes(y))},[I]),q=a.useMemo(()=>{let y=we;if(U){const E=U.toLowerCase();y=y.filter(J=>J.name.toLowerCase().includes(E))}return[...y].sort((E,J)=>E.type==="directory"&&J.type!=="directory"?-1:E.type!=="directory"&&J.type==="directory"?1:E.name.localeCompare(J.name))},[we,U]),Q=D(y=>y.latency),be=`chat-draft-${r}`,Ee=a.useRef(!1),je=a.useRef(void 0);a.useEffect(()=>{try{const E=localStorage.getItem(be);E&&!h.current&&p(E)}catch{}let y=!1;return Fs(s,r).then(E=>{if(y||h.current){u.current=!0;return}if(E){p(E);try{localStorage.setItem(be,E)}catch{}}u.current=!0}).catch(()=>{u.current=!0}),()=>{y=!0}},[s,r,be]),a.useEffect(()=>{if(!u.current)return;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{try{localStorage.setItem(be,d)}catch{}},50),je.current&&clearTimeout(je.current);const y=Math.max(200,(Q??30)*3);return je.current=setTimeout(()=>{Ee.current||(Ee.current=!0,dn(s,r,d).catch(()=>{}).finally(()=>{Ee.current=!1}))},y),()=>{f.current&&clearTimeout(f.current),je.current&&clearTimeout(je.current)}},[d,s,r,Q,be]),a.useEffect(()=>{var y;(y=c.current)==null||y.focus()},[]),a.useEffect(()=>{if(!G)return;let y=!1;return A(!0),(async()=>{try{if(V){if(!W.current){const re=await Re(s,r);if(y)return;W.current=re.cwd}const E=`${W.current}/${V.replace(/\/$/,"")}`,J=await Re(s,r,E);if(y)return;ye(J.files)}else{const E=await Re(s,r);if(y)return;W.current=E.cwd,ye(E.files)}A(!1)}catch{if(y)return;ye([]),A(!1)}})(),()=>{y=!0}},[G,V,s,r]),a.useEffect(()=>{if(!G||!X.current)return;const y=X.current.querySelector(".file-item--active");y==null||y.scrollIntoView({block:"nearest"})},[K,G]);const Ae=a.useCallback(()=>{const y=j.current.trim();if(y){Bs(y),e(y),p("");try{localStorage.removeItem(be)}catch{}dn(s,r,"").catch(()=>{})}},[e,s,r,be]),le=a.useCallback(y=>{k(),p(y),h.current=!0},[k]),Se=a.useCallback(y=>{const E=c.current;k();const J=j.current;if(E){const re=E.selectionStart,oe=E.selectionEnd,ke=J.slice(0,re)+y+J.slice(oe);p(ke);const ce=re+y.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ce,E.focus()})}else p(J+y)},[k]);a.useImperativeHandle(i,()=>({send:Ae,fillContent:le,insertAtCursor:Se}),[Ae,le,Se]),a.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const ue=a.useCallback(()=>{const y=c.current;if(!y)return;const{selectionStart:E,selectionEnd:J}=y;if(E!==J){const re=y.value.substring(E,J);re&&navigator.clipboard.writeText(re).catch(()=>{})}},[]),He=a.useCallback(()=>{const y=zn();v(!1),T("");const E=c.current;if(E){const J=E.selectionStart,re=d.slice(0,J),oe=d.slice(J),ke=re.match(/(?:^|\s)(\/history)\s*$/);if(ke){const ce=re.length-ke[1].length;p(d.slice(0,ce)+oe)}}y.length!==0&&(O(y),S(0),ee(""),B(!0))},[d]),_e=a.useCallback(y=>{k(),p(y.text),B(!1),requestAnimationFrame(()=>{const E=c.current;E&&(E.selectionStart=E.selectionEnd=y.text.length,E.focus())})},[k]),Oe=a.useCallback(y=>{const E=P[y];if(!E)return;const J=F.filter(oe=>oe.ts!==E.ts||oe.text!==E.text);O(J),localStorage.setItem(Rt,JSON.stringify(J));const re=w?J.filter(oe=>oe.text.toLowerCase().includes(w.toLowerCase())):J;N>=re.length&&S(Math.max(0,re.length-1))},[P,F,N,w]);a.useEffect(()=>{if(!_||!Y.current)return;const y=Y.current.querySelector(".history-item--active");y==null||y.scrollIntoView({block:"nearest"})},[N,_]);const Ne=a.useCallback(y=>{if(y==="/history"){He();return}const E=c.current;if(!E)return;k();const J=E.selectionStart,re=d.slice(0,J),oe=d.slice(J),ce=re.lastIndexOf(`
|
|
31
|
+
`)+1,pe=re.slice(ce).match(/\/[a-zA-Z:-]*$/);if(pe){const de=ce+(pe.index??0),ve=y+" ",Ke=d.slice(0,de)+ve+oe;p(Ke);const Fe=de+ve.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=Fe,E.focus()})}else{const de=re+y+oe;p(de);const ve=J+y.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ve,E.focus()})}v(!1),T(""),z(0)},[d,k,He]),Le=a.useCallback(y=>{const E=c.current;if(!E)return;k();const J=E.selectionStart,re=d.slice(0,J),oe=d.slice(J),ke=re.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!ke)return;const ce=re.length-ke[0].length;if(y.type==="directory"){const he="@"+V+y.name+"/",pe=d.slice(0,ce)+he+oe;p(pe);const de=ce+he.length;ne(V+y.name+"/"),H(""),se(0),requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=de,E.focus()})}else{const he=y.name+" ",pe=d.slice(0,ce)+he+oe;p(pe);const de=ce+he.length;$(!1),H(""),ne(""),se(0),ye([]),W.current="",requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=de,E.focus()})}},[d,V,k]),Ye=a.useCallback(y=>{const E=y.target.value;if(p(E),_){const he=E.trim();he?(ee(he),S(0)):ee("");return}const J=y.target.selectionStart,re=E.slice(0,J),oe=re.lastIndexOf(`
|
|
32
|
+
`),ce=re.slice(oe+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(ce)v(!0),T(ce[1]),z(0),$(!1);else{v(!1);const he=re.match(/@([a-zA-Z0-9_.\-/]*)$/);if(he){const pe=he[1],de=pe.lastIndexOf("/"),ve=de>=0?pe.slice(0,de+1):"",Ke=de>=0?pe.slice(de+1):pe;H(Ke),se(0),ne(ve),$(!0)}else $(!1)}},[_]),pt=a.useCallback(y=>{if(C&&Z.length>0){if(y.key==="ArrowDown"){y.preventDefault(),z(E=>(E+1)%Z.length);return}if(y.key==="ArrowUp"){y.preventDefault(),z(E=>(E-1+Z.length)%Z.length);return}if(y.key==="Enter"||y.key==="Tab"){y.preventDefault(),Ne(Z[L].cmd);return}if(y.key==="Escape"){y.preventDefault(),v(!1);return}}if(G&&q.length>0){if(y.key==="ArrowDown"){y.preventDefault(),se(E=>(E+1)%q.length);return}if(y.key==="ArrowUp"){y.preventDefault(),se(E=>(E-1+q.length)%q.length);return}if(y.key==="Tab"||y.key==="Enter"){y.preventDefault(),Le(q[K]);return}if(y.key==="Escape"){y.preventDefault(),$(!1);return}}if(_&&P.length>0){if(y.key==="ArrowDown"){y.preventDefault(),S(E=>(E+1)%P.length);return}if(y.key==="ArrowUp"){y.preventDefault(),S(E=>(E-1+P.length)%P.length);return}if(y.key==="Enter"){y.preventDefault(),_e(P[N]);return}if(y.key==="Delete"||y.key==="Backspace"&&(y.ctrlKey||y.metaKey)){y.preventDefault(),Oe(N);return}if(y.key==="Escape"){y.preventDefault(),B(!1);return}}if(y.key==="Tab"){Et(y,p,g);return}y.key==="Enter"&&(y.ctrlKey||y.metaKey)&&(y.preventDefault(),Ae())},[Ae,C,Z,L,Ne,G,q,K,Le,g,b,_,P,N,_e,Oe]);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[C&&Z.length>0&&o.jsx("div",{className:"slash-dropdown",children:Z.map((y,E)=>o.jsxs("div",{className:`slash-item${E===L?" slash-item--active":""}`,onMouseDown:J=>{J.preventDefault(),Ne(y.cmd)},onMouseEnter:()=>z(E),children:[o.jsx("span",{className:"slash-cmd",children:y.cmd}),o.jsx("span",{className:"slash-desc",children:y.desc})]},y.cmd))}),G&&(De||q.length>0)&&o.jsx("div",{className:"file-dropdown",ref:X,children:De?o.jsx("div",{className:"file-item file-loading",children:"Loading..."}):q.map((y,E)=>o.jsxs("div",{className:`file-item${E===K?" file-item--active":""}`,onMouseDown:J=>{J.preventDefault(),Le(y)},onMouseEnter:()=>se(E),children:[o.jsx("span",{className:"file-icon",children:y.type==="directory"?"📁":"📄"}),o.jsx("span",{className:"file-name",children:y.name})]},y.name))}),_&&o.jsx("div",{className:"history-dropdown",ref:Y,children:P.length===0?o.jsx("div",{className:"history-item history-empty",children:"No history yet"}):P.map((y,E)=>o.jsxs("div",{className:`history-item${E===N?" history-item--active":""}`,onMouseDown:J=>{J.preventDefault(),_e(y)},onMouseEnter:()=>S(E),children:[o.jsx("span",{className:"history-text",children:y.text.length>120?y.text.slice(0,120)+"...":y.text}),o.jsx("span",{className:"history-time",children:new Date(y.ts).toLocaleString()}),o.jsx("button",{className:"history-delete",onMouseDown:J=>{J.preventDefault(),J.stopPropagation(),Oe(E)},title:"Delete (Del key)",children:"×"})]},`${y.ts}-${E}`))}),o.jsx("textarea",{ref:c,className:"md-editor-textarea",value:d,onChange:Ye,onKeyDown:pt,onMouseUp:ue,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${l}px`}})]})});function Ws({token:t,sessionId:e,onClose:n}){const[r,s]=a.useState([]),[i,l]=a.useState(""),[d,p]=a.useState([]),[c,f]=a.useState(!0),[u,h]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{let v=!1;return(async()=>{try{const I=await Re(t,e);v||(l(I.cwd),s(I.files))}catch{v||n()}finally{v||f(!1)}})(),()=>{v=!0}},[t,e,n]),a.useEffect(()=>{const v=L=>{L.key==="Escape"&&n()},I=L=>{g.current&&!g.current.contains(L.target)&&n()};document.addEventListener("keydown",v);const T=setTimeout(()=>document.addEventListener("mousedown",I),50);return()=>{document.removeEventListener("keydown",v),document.removeEventListener("mousedown",I),clearTimeout(T)}},[n]);const b=a.useCallback(async v=>{f(!0);try{const I=await Re(t,e,v);p(T=>[...T,i]),l(v),s(I.files)}catch{}finally{f(!1)}},[t,e,i]),j=a.useCallback(async()=>{if(d.length===0)return;const v=d[d.length-1];f(!0);try{const I=await Re(t,e,v);p(T=>T.slice(0,-1)),l(v),s(I.files)}catch{}finally{f(!1)}},[t,e,d]),k=a.useCallback(async v=>{try{await Ds(t,e,v)}catch(I){alert(`Download failed: ${I instanceof Error?I.message:"Unknown error"}`)}},[t,e]),C=a.useCallback(async()=>{h(!0),n();try{await Ms(t,e)}catch(v){alert(`Download failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{h(!1)}},[t,e,n]);return o.jsxs("div",{ref:g,style:{position:"absolute",top:"100%",right:0,marginTop:4,width:300,maxHeight:360,backgroundColor:"var(--bg-primary)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:100,display:"flex",flexDirection:"column",overflow:"hidden"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[d.length>0&&o.jsx("button",{className:"pane-btn",onClick:j,disabled:c,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),o.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:i.split("/").slice(-2).join("/")||i}),o.jsx("button",{className:"pane-btn",onClick:n,style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),o.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:c?o.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?o.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(v=>o.jsxs("div",{onClick:()=>{const I=i+"/"+v.name;v.type==="directory"?b(I):k(I)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[o.jsx("span",{style:{flexShrink:0,fontSize:13},children:v.type==="directory"?"📁":As(v.name,v.type)}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.type==="directory"?o.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):v.size!=null?o.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:Dn(v.size)}):null]},v.name))}),o.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:o.jsx("button",{className:"pane-btn",onClick:C,disabled:u,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:u?"Downloading...":"Download All (tar.gz)"})})]})}function pn(t,e,{containerRef:n,axis:r,offset:s=0,min:i,max:l,invert:d=!1,bodyClass:p}){const[c,f]=a.useState(()=>{const g=localStorage.getItem(t);if(g){const b=Number(g);if(Number.isFinite(b)&&b>=i&&b<=l)return b}return e}),u=a.useRef(c);if(c!==u.current){u.current=c;try{localStorage.setItem(t,String(Math.round(c)))}catch{}}const h=a.useCallback(g=>{g.preventDefault();const b=n.current;if(!b)return;const j=b.getBoundingClientRect(),k=r==="x"?j.width:j.height-s,C=r==="x"?j.left:j.top+s;document.body.classList.add(p);const v=T=>{let z=((r==="x"?T.clientX:T.clientY)-C)/k*100;d&&(z=100-z),f(Math.min(l,Math.max(i,z)))},I=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",I)},[n,r,s,i,l,d,p]);return[c,h]}const Us=600,We=typeof window<"u"?window.matchMedia(`(max-width: ${Us-1}px)`):null;function Hs(){const[t,e]=a.useState(()=>(We==null?void 0:We.matches)??!1);return a.useEffect(()=>{if(!We)return;const n=r=>e(r.matches);return We.addEventListener("change",n),()=>We.removeEventListener("change",n)},[]),t}const Ks=a.memo(function({terminal:e}){const n=Hs(),r=D($=>$.splitTerminal),s=D($=>$.token),i=D($=>$.toggleChat),l=D($=>$.togglePlan),{chatOpen:d,planOpen:p}=e.panels,c=a.useRef(null),f=a.useRef(null),u=a.useRef(null),h=a.useRef(null),g=a.useRef(null),[b,j]=pn(`plan-width-${e.id}`,50,{containerRef:f,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[k,C]=pn(`doc-height-${e.id}`,35,{containerRef:c,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[v,I]=a.useState("");a.useEffect(()=>{if(!s||!e.connected)return;let $=!1;const U=async()=>{try{const V=await ln(s,e.id);$||I(V)}catch{}};U();const H=setInterval(U,5e3);return()=>{$=!0,clearInterval(H)}},[s,e.id,e.connected]);const T=a.useCallback(async $=>{let U;if(s)try{U=await ln(s,e.id)}catch{}r(e.id,$,U)},[s,e.id,r]),[L,z]=a.useState(!1),[_,B]=a.useState(0),[F,O]=a.useState(!1),[N,S]=a.useState(!1),w=async $=>{const U=$.target.files;if(!(!U||U.length===0||!s)){z(!0),B(0);try{await Is(s,e.id,U,H=>{B(H)})}catch(H){alert(`Upload failed: ${H instanceof Error?H.message:"Unknown error"}`)}finally{z(!1),B(0),u.current&&(u.current.value="")}}},ee=a.useRef(void 0),Y=a.useCallback($=>{if(h.current){const U=$.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(U),ee.current=window.setTimeout(()=>{var H;return(H=h.current)==null?void 0:H.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{ee.current&&clearTimeout(ee.current)},[]);const P=a.useCallback($=>{if(h.current){const U=$.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(U),setTimeout(()=>{var H;return(H=h.current)==null?void 0:H.sendInput("\r")},50)}},[]),G=a.useCallback(()=>S(!1),[]);return o.jsxs("div",{ref:c,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[o.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),o.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]}),v&&o.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:v,children:v})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[o.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:w}),o.jsx("button",{className:"pane-btn",onClick:()=>{var $;return($=u.current)==null?void 0:$.click()},disabled:L,style:L?{color:"var(--accent-yellow)"}:void 0,title:L?`Uploading ${_}%`:"Upload files","aria-label":"Upload files",children:L?`${_}%`:"↑"}),o.jsxs("div",{style:{position:"relative"},children:[o.jsx("button",{className:"pane-btn",onClick:()=>S(!0),title:"Download files","aria-label":"Download files",children:"↓"}),N&&s&&o.jsx(Ws,{token:s,sessionId:e.id,onClose:G})]}),o.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),o.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),o.jsx("button",{className:"pane-btn",onClick:()=>T(n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),o.jsx("button",{className:"pane-btn",onClick:()=>T("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),o.jsxs("div",{ref:f,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[p&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:`${b}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:o.jsx(Os,{sessionId:e.id,token:s||"",connected:e.connected,onRequestFileStream:$=>{var U;return(U=h.current)==null?void 0:U.requestFileStream($)},onSendToTerminal:P})}),o.jsx("div",{className:"md-editor-divider-h",onMouseDown:j,style:{width:"3px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:$=>{$.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:$=>{$.currentTarget.style.backgroundColor="var(--border)"}})]}),o.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[o.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[o.jsx(os,{ref:h,sessionId:e.id}),!e.connected&&o.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:o.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"md-editor-divider",onMouseDown:C}),o.jsxs("div",{style:{height:`${k}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",height:"22px",flexShrink:0,backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[o.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),o.jsx("button",{className:"pane-btn",onClick:()=>{var $;return($=g.current)==null?void 0:$.send()},disabled:!F,title:"Send to terminal (Ctrl+Enter)",style:F?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),o.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),o.jsx("div",{style:{flex:1,overflow:"hidden"},children:o.jsx(Ps,{ref:g,onSend:Y,onContentChange:O,sessionId:e.id,token:s||""})})]})]})]})]}),e.error&&o.jsx("div",{style:{padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--accent-red)",color:"var(--accent-red)",fontSize:"11px",flexShrink:0},children:e.error})]})});class $n extends a.Component{constructor(){super(...arguments);$t(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?o.jsxs("div",{style:{height:"100%",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"var(--text-bright)",fontFamily:"monospace",padding:"16px"},children:[o.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),o.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textAlign:"center"},children:((n=this.state.error)==null?void 0:n.message)||"An unexpected error occurred"}),o.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-bright)",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):o.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"var(--text-bright)",fontFamily:"monospace"},children:[o.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),o.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),o.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",border:"none",color:"var(--bg-primary)",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const Js=4,mn=10;function Vs(){const t=D(s=>s.layout),e=D(s=>s.terminalIds.length),n=D(s=>s.addTerminal);if(!t)return o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:o.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed var(--border)",color:"var(--text-secondary)",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=e>1;return o.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:o.jsx(_n,{node:t,canClose:r})})}const _n=a.memo(function({node:e,canClose:n}){return e.type==="leaf"?o.jsx(Gs,{terminalId:e.terminalId,canClose:n}):o.jsx(qs,{node:e,canClose:n})}),Gs=a.memo(function({terminalId:e,canClose:n}){const r=D(i=>i.terminalsMap[e]),s=D(i=>i.reconnectTerminal);return r?o.jsx($n,{inline:!0,children:o.jsx(Ks,{terminal:r,canClose:n})}):o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:o.jsxs("button",{onClick:()=>s(e),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",e]})})}),qs=a.memo(function({node:e,canClose:n}){const r=D(c=>c.setSplitSizes),s=a.useRef(null),i=e.direction==="horizontal",l=a.useRef(e.sizes);l.current=e.sizes;const d=a.useCallback((c,f)=>{f.preventDefault();const u=i?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const h=i?f.clientX:f.clientY,g=[...l.current],b=s.current,j=i?(b==null?void 0:b.clientWidth)||1:(b==null?void 0:b.clientHeight)||1;let k=null;const C=I=>{k||(k=requestAnimationFrame(()=>{k=null;const z=((i?I.clientX:I.clientY)-h)/j*100,_=g[c]+z,B=g[c+1]-z;if(_>=mn&&B>=mn){const F=[...g];F[c]=_,F[c+1]=B,r(e.id,F)}}))},v=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(u),document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",C),document.addEventListener("mouseup",v)},[i,e.id,r]),p=[];return e.children.forEach((c,f)=>{const u=c.type==="leaf"?c.terminalId:c.id;p.push(o.jsx("div",{style:{flex:`${e.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:o.jsx(_n,{node:c,canClose:n})},u)),f<e.children.length-1&&p.push(o.jsx("div",{onMouseDown:h=>d(f,h),style:{flex:`0 0 ${Js}px`,cursor:i?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${f}`))}),o.jsx("div",{ref:s,style:{display:"flex",flexDirection:i?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function Ys({tabId:t}){const e=D(S=>S.tabs.find(w=>w.id===t)),n=D(S=>S.activeTabId),r=D(S=>S.switchTab),s=D(S=>S.closeTab),i=D(S=>S.reopenTab),l=D(S=>S.deleteTab),d=D(S=>S.renameTab),p=D(S=>e?e.terminalIds.map(w=>{const ee=S.terminalsMap[w];return ee?{id:w,connected:ee.connected,active:!0}:{id:w,connected:!1,active:!1}}):[]),c=D(S=>S.disconnectTerminal),f=D(S=>S.reconnectTerminal),u=D(S=>S.killServerSession),[h,g]=a.useState(!1),[b,j]=a.useState(""),[k,C]=a.useState(!1),v=a.useRef(null);if(!e)return null;const I=n===t,T=e.status==="open",L=()=>{T&&r(t)},z=S=>{T&&(S.stopPropagation(),j(e.name),g(!0),setTimeout(()=>{var w;return(w=v.current)==null?void 0:w.focus()},0))},_=()=>{const S=b.trim();S&&d(t,S),g(!1)},B=S=>{S.stopPropagation(),i(t)},F=S=>{S.stopPropagation(),s(t)},O=async S=>{S.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await l(t)},N=S=>{S.stopPropagation(),C(!k)};return o.jsxs("div",{children:[o.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:T?"pointer":"default",borderLeft:I?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:I?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:T?1:.5},onMouseEnter:S=>{T&&!I&&(S.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:S=>{I||(S.currentTarget.style.backgroundColor="transparent")},children:[T&&e.terminalIds.length>0&&o.jsx("button",{onClick:N,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:k?"▼":"▶"}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[h?o.jsx("input",{ref:v,value:b,onChange:S=>j(S.target.value),onBlur:_,onKeyDown:S=>{S.key==="Enter"&&_(),S.key==="Escape"&&g(!1)},style:{width:"100%",background:"var(--bg-primary)",border:"1px solid var(--accent-blue)",color:"var(--text-bright)",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):o.jsx("div",{onDoubleClick:z,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:T?"Double-click to rename":e.name,children:e.name}),o.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",An(Math.floor(e.createdAt/1e3))]})]}),T?o.jsx("button",{className:"pane-btn pane-btn--danger",onClick:F,style:{flexShrink:0},title:"Close tab",children:"×"}):o.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[o.jsx("button",{className:"pane-btn",onClick:B,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),o.jsx("button",{className:"pane-btn pane-btn--danger",onClick:O,title:"Delete tab",children:"×"})]})]}),T&&k&&p.length>0&&o.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(S=>o.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${S.connected}`,children:[o.jsx("span",{style:{fontFamily:"monospace"},children:S.id}),o.jsx("span",{style:{marginLeft:"8px",color:S.active?S.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:S.active?S.connected?"●":"◐":"○"}),S.active?o.jsx("button",{className:"pane-btn pane-btn--danger",onClick:w=>{w.stopPropagation(),c(S.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):o.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[o.jsx("button",{className:"pane-btn",onClick:w=>{w.stopPropagation(),f(S.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),o.jsx("button",{className:"pane-btn pane-btn--danger",onClick:w=>{w.stopPropagation(),window.confirm(`Kill terminal "${S.id}"? This will destroy the tmux session.`)&&u(S.id)},title:"Kill session",children:"×"})]})]},S.id))})]})}function Xs({sessionId:t,active:e,createdAt:n}){const r=D(d=>d.addTerminal),s=D(d=>d.killServerSession),i=()=>{r("horizontal",t)},l=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${t}"? This will kill the tmux session.`)&&s(t)};return o.jsxs("div",{onClick:i,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",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:[o.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),o.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:An(n)})]}),o.jsx("button",{className:"pane-btn pane-btn--danger",onClick:l,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function Zs(){const t=D(c=>c.sidebarOpen),e=D(c=>c.toggleSidebar),n=D(c=>c.fetchSessions),r=D(c=>t?c.serverSessions:[]),s=D(c=>t?c.tabs:[]),i=D(c=>c.terminalIds.length),l=D(c=>c.tabsLoading),d=new Set(s.flatMap(c=>c.terminalIds)),p=r.filter(c=>!d.has(c.sessionId));return a.useEffect(()=>{if(!t)return;n();let c=setInterval(n,5e3);const f=()=>{document.hidden?c&&(clearInterval(c),c=null):(n(),c||(c=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",f),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",f)}},[t,n]),a.useEffect(()=>{if(!t)return;const c=setTimeout(n,800);return()=>clearTimeout(c)},[i,t,n]),o.jsxs("div",{className:"session-sidebar",style:{width:t?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:t?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[o.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),o.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),o.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[o.jsxs("div",{children:[o.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),s.length===0?o.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):s.map(c=>o.jsx(Ys,{tabId:c.id},c.id))]}),!l&&p.length>0&&o.jsxs("div",{style:{marginTop:"16px"},children:[o.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-yellow)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid var(--border)"},children:"ORPHANED SESSIONS"}),p.map(c=>o.jsx(Xs,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const On=It.memo(()=>{const t=D(T=>T.tabs),e=D(T=>T.activeTabId),n=D(T=>T.addTab),r=D(T=>T.switchTab),s=D(T=>T.closeTab),i=D(T=>T.renameTab),[l,d]=a.useState(null),[p,c]=a.useState(""),f=a.useRef(null),u=t.filter(T=>T.status==="open");a.useEffect(()=>{l&&f.current&&(f.current.focus(),f.current.select())},[l]);const h=T=>{d(T.id),c(T.name)},g=()=>{l&&p.trim()&&i(l,p.trim()),d(null),c("")},b=()=>{d(null),c("")},j=T=>{T.key==="Enter"?g():T.key==="Escape"&&b()},k=T=>{l||r(T)},C=(T,L)=>{T.stopPropagation(),s(L)},v=(T,L)=>{T.button===1&&(T.preventDefault(),s(L))},I=u.length>1;return o.jsxs("div",{className:"tab-bar",children:[u.map(T=>{const L=T.id===e,z=l===T.id,_=T.terminalIds.length;return o.jsx("div",{className:`tab-item ${L?"tab-item--active":""}`,onClick:()=>k(T.id),onDoubleClick:()=>h(T),onMouseDown:B=>v(B,T.id),children:z?o.jsx("input",{ref:f,type:"text",value:p,onChange:B=>c(B.target.value),onBlur:g,onKeyDown:j,className:"tab-item__rename-input"}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"tab-item__name",children:[T.name," ",_>0&&`(${_})`]}),I&&o.jsx("button",{className:"tab-item__close",onClick:B=>C(B,T.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},T.id)}),o.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});On.displayName="TabBar";function Qs(){return localStorage.getItem("ai-cli-online-token")}function ea(){const t=D(f=>f.token),e=D(f=>f.setToken),n=D(f=>f.tabs),r=D(f=>f.addTab),s=D(f=>f.toggleSidebar),i=D(f=>f.fontSize),l=D(f=>f.setFontSize),d=D(f=>f.tabsLoading),p=D(f=>f.theme),c=D(f=>f.toggleTheme);return a.useEffect(()=>{const f=Qs();f&&!t&&e(f)},[]),a.useEffect(()=>{t&&!d&&n.filter(f=>f.status==="open").length===0&&r("Default")},[t,d]),t?o.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[o.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),o.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.11"]})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[o.jsx("button",{className:"header-btn",onClick:()=>l(i-1),disabled:i<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),o.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:i}),o.jsx("button",{className:"header-btn",onClick:()=>l(i+1),disabled:i>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),o.jsx(na,{}),o.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"☀":"🌙"}),o.jsx("button",{className:"header-btn",onClick:s,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),o.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),o.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[o.jsx("main",{style:{flex:1,overflow:"hidden"},children:o.jsx(Vs,{})}),o.jsx(Zs,{})]}),o.jsx(On,{})]}):o.jsx(Pr,{})}const ta=[1,2,3,4];function na(){const t=D(r=>r.latency);if(t===null)return o.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let e,n;return t<50?(e="var(--accent-green)",n=4):t<150?(e="var(--accent-yellow)",n=3):t<300?(e="var(--accent-orange)",n=2):(e="var(--accent-red)",n=1),o.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${t}ms`,children:[ta.map(r=>o.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),o.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[t,"ms"]})]})}kt.createRoot(document.getElementById("root")).render(o.jsx(It.StrictMode,{children:o.jsx($n,{children:o.jsx(ea,{})})}));
|
package/web/dist/index.html
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<!-- LXGW WenKai Mono (中文等宽字体, CDN unicode-range 按需加载) -->
|
|
11
11
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkaimono-regular.css" />
|
|
12
12
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkaimono-bold.css" />
|
|
13
|
-
<script type="module" crossorigin src="/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/assets/index-BHAsZRWj.js"></script>
|
|
14
14
|
<link rel="modulepreload" crossorigin href="/assets/react-vendor-BCIvbQoU.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/terminal-DnNpv9tw.js">
|
|
16
16
|
<link rel="modulepreload" crossorigin href="/assets/markdown-CU76q5qk.js">
|
package/web/package.json
CHANGED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
var Kn=Object.defineProperty;var Jn=(t,e,n)=>e in t?Kn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var zt=(t,e,n)=>Jn(t,typeof e!="symbol"?e+"":e,n);import{r as o,a as Vn,g as Gn,R as jt}from"./react-vendor-BCIvbQoU.js";import{D as hn,o as gn,L as qn,x as bn}from"./terminal-DnNpv9tw.js";import{p as wt,g as xn}from"./markdown-CU76q5qk.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var yn={exports:{}},lt={};/**
|
|
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 Yn=o,Xn=Symbol.for("react.element"),Zn=Symbol.for("react.fragment"),Qn=Object.prototype.hasOwnProperty,er=Yn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,tr={key:!0,ref:!0,__self:!0,__source:!0};function vn(t,e,n){var r,s={},i=null,l=null;n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),e.ref!==void 0&&(l=e.ref);for(r in e)Qn.call(e,r)&&!tr.hasOwnProperty(r)&&(s[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)s[r]===void 0&&(s[r]=e[r]);return{$$typeof:Xn,type:t,key:i,ref:l,props:s,_owner:er.current}}lt.Fragment=Zn;lt.jsx=vn;lt.jsxs=vn;yn.exports=lt;var a=yn.exports,St={},$t=Vn;St.createRoot=$t.createRoot,St.hydrateRoot=$t.hydrateRoot;const nr={},_t=t=>{let e;const n=new Set,r=(f,u)=>{const h=typeof f=="function"?f(e):f;if(!Object.is(h,e)){const g=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),n.forEach(b=>b(e,g))}},s=()=>e,p={setState:r,getState:s,getInitialState:()=>c,subscribe:f=>(n.add(f),()=>n.delete(f)),destroy:()=>{n.clear()}},c=e=t(r,s,p);return p},rr=t=>t?_t(t):_t;var wn={exports:{}},Sn={},kn={exports:{}},Tn={};/**
|
|
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 We=o;function sr(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var or=typeof Object.is=="function"?Object.is:sr,ar=We.useState,ir=We.useEffect,lr=We.useLayoutEffect,cr=We.useDebugValue;function dr(t,e){var n=e(),r=ar({inst:{value:n,getSnapshot:e}}),s=r[0].inst,i=r[1];return lr(function(){s.value=n,s.getSnapshot=e,bt(s)&&i({inst:s})},[t,n,e]),ir(function(){return bt(s)&&i({inst:s}),t(function(){bt(s)&&i({inst:s})})},[t]),cr(n),n}function bt(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!or(t,n)}catch{return!0}}function ur(t,e){return e()}var fr=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?ur:dr;Tn.useSyncExternalStore=We.useSyncExternalStore!==void 0?We.useSyncExternalStore:fr;kn.exports=Tn;var pr=kn.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 ct=o,mr=pr;function hr(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var gr=typeof Object.is=="function"?Object.is:hr,br=mr.useSyncExternalStore,xr=ct.useRef,yr=ct.useEffect,vr=ct.useMemo,wr=ct.useDebugValue;Sn.useSyncExternalStoreWithSelector=function(t,e,n,r,s){var i=xr(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=vr(function(){function p(g){if(!c){if(c=!0,f=g,g=r(g),s!==void 0&&l.hasValue){var b=l.value;if(s(b,g))return u=b}return u=g}if(b=u,gr(f,g))return b;var j=r(g);return s!==void 0&&s(b,j)?(f=g,b):(f=g,u=j)}var c=!1,f,u,h=n===void 0?null:n;return[function(){return p(e())},h===null?void 0:function(){return p(h())}]},[e,n,r,s]);var d=br(t,i[0],i[1]);return yr(function(){l.hasValue=!0,l.value=d},[d]),wr(d),d};wn.exports=Sn;var Sr=wn.exports;const kr=Gn(Sr),Cn={},{useDebugValue:Tr}=jt,{useSyncExternalStoreWithSelector:Cr}=kr;let Ot=!1;const Er=t=>t;function jr(t,e=Er,n){(Cn?"production":void 0)!=="production"&&n&&!Ot&&(Ot=!0);const r=Cr(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return Tr(r),r}const Ft=t=>{const e=typeof t=="function"?rr(t):t,n=(r,s)=>jr(e,r,s);return Object.assign(n,e),n},Ir=t=>t?Ft(t):Ft,De="";function me(t){return{Authorization:`Bearer ${t}`}}class Ve extends Error{constructor(e,n){super(n),this.status=e,this.name="ApiError"}}function Ae(t,e){return`${De}/api/sessions/${encodeURIComponent(t)}/${e}`}function Bt(t){return`${De}/api/settings/${t}`}async function Je(t){if(!t.ok){const e=await t.text().catch(()=>t.statusText);throw new Ve(t.status,e)}return t.json()}const pe={async get(t,e,n,r){const s=new URL(Ae(e,n),window.location.origin);if(r)for(const[l,d]of Object.entries(r))s.searchParams.set(l,d);const i=await fetch(s.toString(),{headers:me(t)});return Je(i)},async getOptional(t,e,n,r){const s=new URL(Ae(e,n),window.location.origin);if(r)for(const[l,d]of Object.entries(r))s.searchParams.set(l,d);const i=await fetch(s.toString(),{headers:me(t)});return i.status===304?null:Je(i)},async post(t,e,n,r){const s=await fetch(Ae(e,n),{method:"POST",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(r)});return Je(s)},async put(t,e,n,r){const s=await fetch(Ae(e,n),{method:"PUT",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const i=await s.text().catch(()=>s.statusText);throw new Ve(s.status,i)}},async putJson(t,e,n,r){const s=await fetch(Ae(e,n),{method:"PUT",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(r)});return Je(s)},async del(t,e,n,r){const s=await fetch(Ae(e,n),{method:"DELETE",headers:{...me(t),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!s.ok){const i=await s.text().catch(()=>s.statusText);throw new Ve(s.status,i)}},async getBlob(t,e,n,r){const s=new URL(Ae(e,n),window.location.origin);if(r)for(const[l,d]of Object.entries(r))s.searchParams.set(l,d);const i=await fetch(s.toString(),{headers:me(t)});if(!i.ok)throw new Ve(i.status,"Download failed");return i}},dt={async get(t,e){const n=await fetch(Bt(e),{headers:me(t)});return Je(n)},async put(t,e,n){const r=await fetch(Bt(e),{method:"PUT",headers:{...me(t),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const s=await r.text().catch(()=>r.statusText);throw new Ve(r.status,s)}}};async function Rr(t){try{return(await dt.get(t,"font-size")).fontSize}catch{return 14}}async function Nr(t,e){try{await dt.put(t,"font-size",{fontSize:e})}catch{}}let Ze=null;const Lr=(t,e)=>({fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));t({fontSize:r}),Ze&&clearTimeout(Ze),Ze=setTimeout(()=>{Ze=null;const s=e().token;s&&Nr(s,r)},500)},latency:null,setLatency:n=>t({latency:n}),theme:(()=>{try{const n=localStorage.getItem("ai-cli-online-theme");if(n==="light"||n==="dark")return n}catch{}return"dark"})(),setTheme:n=>{t({theme:n});try{localStorage.setItem("ai-cli-online-theme",n)}catch{}document.documentElement.setAttribute("data-theme",n)},toggleTheme:()=>{const n=e().theme==="dark"?"light":"dark";e().setTheme(n)},sidebarOpen:!1,toggleSidebar:()=>t(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=e().token;if(n)try{const r=await fetch(`${De}/api/sessions`,{headers:me(n)});if(!r.ok)return;const s=await r.json();t({serverSessions:s})}catch{}}});function rt(t,e){if(t.type==="leaf")return t.terminalId===e?null:t;const n=[],r=[];for(let l=0;l<t.children.length;l++){const d=rt(t.children[l],e);d!==null&&(n.push(d),r.push(t.sizes[l]))}if(n.length===0)return null;if(n.length===1)return n[0];const s=r.reduce((l,d)=>l+d,0),i=r.map(l=>l/s*100);return{...t,children:n,sizes:i}}function En(t,e,n,r,s){return t.type==="leaf"?t.terminalId===e?{id:s,type:"split",direction:n,children:[t,r],sizes:[50,50]}:t:{...t,children:t.children.map(i=>En(i,e,n,r,s))}}function jn(t,e,n){return t.type==="leaf"?t:t.id===e?{...t,sizes:n}:{...t,children:t.children.map(r=>jn(r,e,n))}}function xt(t){return t.tabs.find(e=>e.id===t.activeTabId)}function Ie(t,e,n){return t.map(r=>r.id===e?n(r):r)}function Pt(t,e){const n=t.tabs.find(c=>c.terminalIds.includes(e));if(!n){const{[e]:c,...f}=t.terminalsMap;return{terminalsMap:f}}const r=n.terminalIds.filter(c=>c!==e),s=n.layout?rt(n.layout,e):null,i=Ie(t.tabs,n.id,c=>({...c,terminalIds:r,layout:s})),{[e]:l,...d}=t.terminalsMap,p={terminalsMap:d,tabs:i};return n.id===t.activeTabId&&(p.terminalIds=r,p.layout=s),p}async function Dr(t){try{return(await dt.get(t,"tabs-layout")).layout}catch{return null}}async function Mr(t,e){try{await dt.put(t,"tabs-layout",{layout:e})}catch{}}function Wt(t,e){try{const n=`${De}/api/settings/tabs-layout`,r=JSON.stringify({layout:e,token:t});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const kt="ai-cli-online-tabs",Ut="ai-cli-online-layout",Ht="ai-cli-online-session-names";let ke=null;function Ar(t){ke=t,Br()}let Qe=null,ze=null,Ge=null;function zr(t){Ge=t,ze&&clearTimeout(ze),ze=setTimeout(()=>{ze=null,Ge=null;const e=ke==null?void 0:ke.getState().token;e&&Mr(e,t)},2e3)}function ue(t){const e={version:2,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId,tabs:t.tabs};try{localStorage.setItem(kt,JSON.stringify(e))}catch{}zr(e)}function $r(t){Qe&&clearTimeout(Qe),Qe=setTimeout(()=>{Qe=null,ue(t)},500)}function le(t){return{tabs:t.tabs,activeTabId:t.activeTabId,nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:t.nextTabId}}function _r(){try{const t=localStorage.getItem(kt);if(t){const e=JSON.parse(t);if(e.version===2)return e}}catch{}try{const t=localStorage.getItem(Ut);if(t){const e=JSON.parse(t);let n="Default";try{const i=localStorage.getItem(Ht);if(i){const l=JSON.parse(i),d=Object.values(l)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:e.terminalIds,layout:e.layout,createdAt:Date.now()},s={version:2,activeTabId:"tab1",nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(kt,JSON.stringify(s))}catch{}return localStorage.removeItem(Ut),localStorage.removeItem(Ht),s}}catch{}return null}function Or(t,e){const n=new Set(e.map(l=>l.sessionId)),r=[];for(const l of t.tabs){if(l.status!=="open"){const c=l.terminalIds.filter(f=>n.has(f));if(c.length>0){let f=l.layout;for(const u of l.terminalIds)!n.has(u)&&f&&(f=rt(f,u));r.push({...l,terminalIds:c,layout:f})}continue}const d=l.terminalIds.filter(c=>n.has(c));if(d.length===0)continue;let p=l.layout;for(const c of l.terminalIds)!n.has(c)&&p&&(p=rt(p,c));r.push({...l,terminalIds:d,layout:p})}if(r.filter(l=>l.status==="open").length===0)return null;let s=t.activeTabId;if(!r.find(l=>l.id===s&&l.status==="open")){const l=r.find(d=>d.status==="open");s=(l==null?void 0:l.id)||""}return{...t,activeTabId:s,tabs:r}}async function Fr(t,e){var s,i;if(!ke)return;const{setState:n,getState:r}=ke;try{const[l,d]=await Promise.all([Dr(t),fetch(`${De}/api/sessions`,{headers:me(t)}).then(b=>b.ok?b.json():[]).catch(()=>[])]);if(r().token!==t)return;const p=l&&((s=l.tabs)==null?void 0:s.length)>0?l:e;if(!p||p.tabs.length===0){n({tabsLoading:!1});return}const c=Or(p,d);if(!c){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:p.nextId,nextSplitId:p.nextSplitId,nextTabId:p.nextTabId,terminalIds:[],layout:null});return}const f=r().terminalsMap,u={};for(const b of c.tabs)if(b.status==="open")for(const j of b.terminalIds)u[j]=f[j]||{id:j,connected:!1,sessionResumed:!1,error:null,panels:((i=b.panelStates)==null?void 0:i[j])||{chatOpen:!1,planOpen:!1}};const h=c.tabs.find(b=>b.id===c.activeTabId&&b.status==="open")||c.tabs.find(b=>b.status==="open"),g=(h==null?void 0:h.id)||"";n({tabsLoading:!1,terminalsMap:u,tabs:c.tabs,activeTabId:g,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(h==null?void 0:h.terminalIds)||[],layout:(h==null?void 0:h.layout)||null}),ue(le(r()))}catch{r().token===t&&n({tabsLoading:!1})}}function Br(){typeof window>"u"||!ke||window.addEventListener("beforeunload",()=>{const t=ke==null?void 0:ke.getState().token;if(t)if(Ge)ze&&(clearTimeout(ze),ze=null),Wt(t,Ge),Ge=null;else{const e=ke.getState();e.tabs.length>0&&Wt(t,le(e))}})}const A=Ir((...t)=>{const[e,n]=t;return{...Lr(...t),token:null,tabsLoading:!1,setToken:r=>{var s;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}Rr(r).then(l=>{n().token===r&&e({fontSize:l})});const i=_r();if(i&&i.tabs.length>0){const l={};for(const c of i.tabs)if(c.status==="open")for(const f of c.terminalIds)l[f]={id:f,connected:!1,sessionResumed:!1,error:null,panels:((s=c.panelStates)==null?void 0:s[f])||{chatOpen:!1,planOpen:!1}};const d=i.tabs.find(c=>c.id===i.activeTabId&&c.status==="open")||i.tabs.find(c=>c.status==="open"),p=(d==null?void 0:d.id)||"";e({token:r,tabsLoading:!0,terminalsMap:l,tabs:i.tabs,activeTabId:p,nextId:i.nextId,nextSplitId:i.nextSplitId,nextTabId:i.nextTabId,terminalIds:(d==null?void 0:d.terminalIds)||[],layout:(d==null?void 0:d.layout)||null})}else e({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});Fr(r,i);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),e({token:r,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:r=>{const s=n(),i=`tab${s.nextTabId}`,l=`t${s.nextId}`,d={id:l,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},p={type:"leaf",terminalId:l},c={id:i,name:r||`Tab ${s.nextTabId}`,status:"open",terminalIds:[l],layout:p,createdAt:Date.now()};return e({tabs:[...s.tabs,c],activeTabId:i,nextTabId:s.nextTabId+1,nextId:s.nextId+1,terminalsMap:{...s.terminalsMap,[l]:d},terminalIds:c.terminalIds,layout:c.layout}),ue(le(n())),i},switchTab:r=>{const i=n().tabs.find(l=>l.id===r);!i||i.status!=="open"||(e({activeTabId:r,terminalIds:i.terminalIds,layout:i.layout}),ue(le(n())))},closeTab:r=>{const s=n(),i=s.tabs.find(h=>h.id===r);if(!i||i.status!=="open"||s.tabs.filter(h=>h.status==="open").length<=1)return;const d={...s.terminalsMap};for(const h of i.terminalIds)delete d[h];const p=Ie(s.tabs,r,h=>({...h,status:"closed"}));let c=s.activeTabId,f=s.terminalIds,u=s.layout;if(s.activeTabId===r){const h=s.tabs.findIndex(j=>j.id===r),g=p.filter(j=>j.status==="open"),b=g.find(j=>p.findIndex(C=>C.id===j.id)>h)||g[g.length-1];b&&(c=b.id,f=b.terminalIds,u=b.layout)}e({tabs:p,activeTabId:c,terminalsMap:d,terminalIds:f,layout:u}),ue(le(n()))},reopenTab:r=>{var p;const s=n(),i=s.tabs.find(c=>c.id===r);if(!i||i.status!=="closed")return;const l={...s.terminalsMap};for(const c of i.terminalIds)l[c]={id:c,connected:!1,sessionResumed:!1,error:null,panels:((p=i.panelStates)==null?void 0:p[c])||{chatOpen:!1,planOpen:!1}};const d=Ie(s.tabs,r,c=>({...c,status:"open"}));e({tabs:d,activeTabId:r,terminalsMap:l,terminalIds:i.terminalIds,layout:i.layout}),ue(le(n()))},deleteTab:async r=>{const s=n(),i=s.tabs.find(b=>b.id===r);if(!i)return;const l=s.token;l&&await Promise.all(i.terminalIds.map(b=>fetch(`${De}/api/sessions/${encodeURIComponent(b)}`,{method:"DELETE",headers:me(l)}).catch(()=>{})));const d=n(),p=d.tabs.find(b=>b.id===r);if(!p)return;const c={...d.terminalsMap};for(const b of p.terminalIds)delete c[b];const f=d.tabs.filter(b=>b.id!==r);let u=d.activeTabId,h=d.terminalIds,g=d.layout;if(d.activeTabId===r){const b=f.find(j=>j.status==="open");b?(u=b.id,h=b.terminalIds,g=b.layout):(u="",h=[],g=null)}e({tabs:f,activeTabId:u,terminalsMap:c,terminalIds:h,layout:g}),ue(le(n())),setTimeout(()=>n().fetchSessions(),500)},renameTab:(r,s)=>{const i=Ie(n().tabs,r,l=>({...l,name:s}));e({tabs:i}),ue(le(n()))},addTerminal:(r,s)=>{const i=n();if(s&&i.terminalsMap[s])return s;const l=xt(i);if(!l){const $=`tab${i.nextTabId}`,O=s||`t${i.nextId}`;let W=i.nextId;const B=O.match(/^t(\d+)$/);B&&(W=Math.max(W,parseInt(B[1],10)+1));const F=s?W:W+1,N={id:O,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},S={type:"leaf",terminalId:O},w={id:$,name:`Tab ${i.nextTabId}`,status:"open",terminalIds:[O],layout:S,createdAt:Date.now()};return e({tabs:[...i.tabs,w],activeTabId:$,nextTabId:i.nextTabId+1,nextId:F,terminalsMap:{...i.terminalsMap,[O]:N},terminalIds:[O],layout:S}),ue(le(n())),O}const{nextId:d,nextSplitId:p,terminalsMap:c}=i,{terminalIds:f,layout:u}=l,h=s||`t${d}`;let g=d;const b=h.match(/^t(\d+)$/);b&&(g=Math.max(g,parseInt(b[1],10)+1));const j={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},k={type:"leaf",terminalId:h};let C,v=p;if(!u)C=k;else if(u.type==="leaf"){const $=r||"horizontal";C={id:`s${v}`,type:"split",direction:$,children:[u,k],sizes:[50,50]},v++}else if(u.direction===(r||"horizontal")){const O=100/(u.children.length+1),W=(100-O)/100,B=[...u.sizes.map(F=>F*W),O];C={...u,children:[...u.children,k],sizes:B}}else{const $=r||"horizontal";C={id:`s${v}`,type:"split",direction:$,children:[u,k],sizes:[50,50]},v++}const I=[...f,h],T=s?g:g+1,L=Ie(i.tabs,l.id,$=>({...$,terminalIds:I,layout:C}));return e({terminalsMap:{...c,[h]:j},terminalIds:I,layout:C,tabs:L,nextId:T,nextSplitId:v}),ue(le(n())),h},splitTerminal:(r,s,i)=>{const l=n(),d=xt(l);if(!d||!d.layout)return"";const{nextId:p,nextSplitId:c,terminalsMap:f}=l,u=`t${p}`,h={id:u,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1},...i?{startCwd:i}:{}},g={type:"leaf",terminalId:u},b=`s${c}`,j=En(d.layout,r,s,g,b),k=[...d.terminalIds,u],C=p+1,v=c+1,I=Ie(l.tabs,d.id,T=>({...T,terminalIds:k,layout:j}));return e({terminalsMap:{...f,[u]:h},terminalIds:k,layout:j,tabs:I,nextId:C,nextSplitId:v}),ue(le(n())),u},removeTerminal:r=>{const s=Pt(n(),r);s&&(e(s),ue(le(n())))},disconnectTerminal:r=>{const s=n();if(!s.terminalsMap[r])return;const{[r]:l,...d}=s.terminalsMap;e({terminalsMap:d})},reconnectTerminal:r=>{var p;const s=n();if(s.terminalsMap[r])return;const i=s.tabs.find(c=>c.terminalIds.includes(r)),l=((p=i==null?void 0:i.panelStates)==null?void 0:p[r])||{chatOpen:!1,planOpen:!1},d={id:r,connected:!1,sessionResumed:!1,error:null,panels:l};e({terminalsMap:{...s.terminalsMap,[r]:d}})},setTerminalConnected:(r,s)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.connected===s?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,connected:s}}}})},setTerminalResumed:(r,s)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.sessionResumed===s?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,sessionResumed:s}}}})},setTerminalError:(r,s)=>{e(i=>{const l=i.terminalsMap[r];return!l||l.error===s?i:{terminalsMap:{...i.terminalsMap,[r]:{...l,error:s}}}})},toggleChat:r=>{const s=n(),i=s.terminalsMap[r];if(!i)return;const l={...i.panels,chatOpen:!i.panels.chatOpen},d={...s.terminalsMap,[r]:{...i,panels:l}},p=s.tabs.find(f=>f.terminalIds.includes(r));let c=s.tabs;if(p){const f={...p.panelStates,[r]:l};c=Ie(s.tabs,p.id,u=>({...u,panelStates:f}))}e({terminalsMap:d,tabs:c}),ue(le(n()))},togglePlan:r=>{const s=n(),i=s.terminalsMap[r];if(!i)return;const l={...i.panels,planOpen:!i.panels.planOpen},d={...s.terminalsMap,[r]:{...i,panels:l}},p=s.tabs.find(f=>f.terminalIds.includes(r));let c=s.tabs;if(p){const f={...p.panelStates,[r]:l};c=Ie(s.tabs,p.id,u=>({...u,panelStates:f}))}e({terminalsMap:d,tabs:c}),ue(le(n()))},setSplitSizes:(r,s)=>{const i=n(),l=xt(i);if(!l||!l.layout)return;const d=jn(l.layout,r,s),p=Ie(i.tabs,l.id,c=>({...c,layout:d}));e({layout:d,tabs:p}),$r(le(n()))},killServerSession:async r=>{const s=n().token;if(!s)return;try{await fetch(`${De}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:me(s)})}catch{}const i=Pt(n(),r);i&&(e(i),ue(le(n()))),setTimeout(()=>n().fetchSessions(),500)}}});Ar(A);typeof document<"u"&&document.documentElement.setAttribute("data-theme",A.getState().theme);function Pr(){const[t,e]=o.useState(""),n=A(s=>s.setToken),r=s=>{s.preventDefault(),t.trim()&&n(t.trim())};return a.jsx("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"radial-gradient(ellipse at 50% 0%, rgba(122, 162, 247, 0.08) 0%, var(--bg-primary) 70%)"},children:a.jsxs("div",{className:"login-card",style:{backgroundColor:"var(--bg-tertiary)",borderRadius:"12px",padding:"40px 36px",width:"100%",maxWidth:"400px",border:"1px solid var(--border)"},children:[a.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[a.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"24px",color:"var(--bg-primary)",fontWeight:"bold",boxShadow:"0 4px 16px rgba(122, 162, 247, 0.3)"},children:">_"}),a.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),a.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),a.jsxs("form",{onSubmit:r,children:[a.jsxs("div",{style:{marginBottom:"20px"},children:[a.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"var(--accent-blue)",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),a.jsx("input",{type:"password",id:"token",className:"login-input",value:t,onChange:s=>e(s.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"var(--bg-primary)",color:"var(--text-bright)",border:"1px solid var(--border)",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),a.jsx("button",{type:"submit",className:"login-submit",disabled:!t.trim(),style:{width:"100%",padding:"11px",background:t.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:t.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:t.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),a.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:a.jsxs("p",{children:["Token is configured in"," ",a.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const ut=new Map;function Wr(t,e,n){ut.set(t,{onChunk:e,onControl:n})}function Ur(t){ut.delete(t)}function Hr(t,e){var n;(n=ut.get(t))==null||n.onChunk(e)}function Kr(t,e){var n;(n=ut.get(t))==null||n.onControl(e)}const Jr=1,Kt=2,Vr=3,Gr=4,qr=5,Yr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,et=500,Xr=8e3,Zr=1e4,Jt=4e3,Qr=5e3,es=10,ts=64*1024,ns=new TextDecoder,rs=new TextEncoder;function Vt(t,e){const n=rs.encode(e),r=new Uint8Array(1+n.length);return r[0]=t,r.set(n,1),r.buffer}function ss(t,e,n){const r=o.useRef(null),s=o.useRef(et),i=o.useRef(null),l=o.useRef(null),d=o.useRef(null),p=o.useRef(null),c=o.useRef(!1),f=o.useRef(n),u=o.useRef(!1),h=o.useRef(0),g=o.useRef(!0),b=o.useRef(!navigator.onLine),j=o.useRef(""),k=o.useRef(null),C=o.useRef("");f.current=n;const v=o.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null),d.current&&(clearTimeout(d.current),d.current=null),i.current&&(clearTimeout(i.current),i.current=null),p.current&&(clearTimeout(p.current),p.current=null),k.current&&(clearTimeout(k.current),k.current=null)},[]),I=o.useCallback(()=>{var V;const{token:B,setTerminalError:F}=A.getState();if(!B||c.current)return;if(r.current){const U=r.current.readyState;if(U===WebSocket.OPEN||U===WebSocket.CONNECTING)return}u.current=!1;const N=(V=A.getState().terminalsMap[e])==null?void 0:V.startCwd;let S=`${Yr}?sessionId=${encodeURIComponent(e)}`;N&&(S+=`&cwd=${encodeURIComponent(N)}`);const w=new WebSocket(S);w.binaryType="arraybuffer",p.current=window.setTimeout(()=>{w.readyState===WebSocket.CONNECTING&&w.close()},Qr);const q=()=>{w.readyState===WebSocket.OPEN&&(h.current=performance.now(),w.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,w.close())},Jt))};w.onopen=()=>{p.current&&(clearTimeout(p.current),p.current=null),w.send(JSON.stringify({type:"auth",token:B})),F(e,null),s.current=et,g.current=!0},w.onclose=U=>{const{setTerminalConnected:J,setTerminalError:_,setToken:H}=A.getState();if(J(e,!1),v(),u.current)return;if(U.code===4001){c.current=!0,_(e,"Authentication failed"),H(null),localStorage.removeItem("ai-cli-online-token");return}if(U.code===4002)return;if(U.code===4005){_(e,"Connection limit reached");return}if(!navigator.onLine){b.current=!0;return}if(g.current){g.current=!1,i.current=window.setTimeout(()=>I(),50);return}const D=s.current;s.current=Math.min(D*2,Xr);const z=Math.round(D*(.5+Math.random()));i.current=window.setTimeout(()=>{I()},z)},w.onerror=()=>{},w.onmessage=U=>{var J;try{const _=t.current;if(U.data instanceof ArrayBuffer){const D=new Uint8Array(U.data);if(D.length<1)return;const z=D[0],Q=D.subarray(1);switch(z){case Jr:_==null||_.write(Q);break;case Vr:_==null||_.write(Q);break;case Gr:{(J=f.current)==null||J.call(f,ns.decode(Q));break}case qr:{Hr(e,Q);break}}return}const H=JSON.parse(U.data);switch(H.type){case"connected":{const D=A.getState();D.setTerminalConnected(e,!0),D.setTerminalResumed(e,H.resumed);const z=t.current;z&&w.readyState===WebSocket.OPEN&&w.send(JSON.stringify({type:"resize",cols:z.cols,rows:z.rows})),C.current&&(w.send(Vt(Kt,C.current)),C.current=""),q(),l.current=window.setInterval(q,Zr);break}case"error":A.getState().setTerminalError(e,H.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),h.current>0){const D=Math.round(performance.now()-h.current),z=A.getState();(z.terminalIds.length===0||z.terminalIds[0]===e)&&z.setLatency(D),h.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Kr(e,H);break}}catch{}},r.current=w},[e,t,v]),T=o.useCallback(B=>{const F=r.current;if(!F||F.readyState!==WebSocket.OPEN){C.current.length<ts&&(C.current+=B);return}j.current+=B,k.current||(k.current=window.setTimeout(()=>{const N=j.current;j.current="",k.current=null,N&&F.readyState===WebSocket.OPEN&&F.send(Vt(Kt,N))},es))},[]),L=o.useCallback((B,F)=>{var N;((N=r.current)==null?void 0:N.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:B,rows:F}))},[]),$=o.useCallback(()=>{var B;((B=r.current)==null?void 0:B.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),O=o.useCallback(B=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"stream-file",path:B}))},[]),W=o.useCallback(()=>{var B;((B=r.current)==null?void 0:B.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"cancel-stream"}))},[]);return o.useEffect(()=>{A.getState().token&&(c.current=!1,I());const F=()=>{b.current=!1,s.current=et,g.current=!0;const w=r.current;(!w||w.readyState===WebSocket.CLOSED||w.readyState===WebSocket.CLOSING)&&I()},N=()=>{b.current=!0},S=()=>{if(document.visibilityState!=="visible")return;const w=r.current;if(!w||w.readyState!==WebSocket.OPEN){!b.current&&!u.current&&(s.current=et,g.current=!0,I());return}h.current=performance.now(),w.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,w.close())},Jt)};return window.addEventListener("online",F),window.addEventListener("offline",N),document.addEventListener("visibilitychange",S),()=>{u.current=!0,v(),window.removeEventListener("online",F),window.removeEventListener("offline",N),document.removeEventListener("visibilitychange",S),r.current&&(r.current.close(),r.current=null)}},[I,v,e]),{sendInput:T,sendResize:L,requestScrollback:$,requestFileStream:O,cancelFileStream:W}}function os(t){const e=o.useRef(null),n=o.useRef(null),r=o.useRef(t);r.current=t;const s=o.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null),e.current&&(e.current.remove(),e.current=null)},[]),i=o.useCallback((l,d)=>{s();const p=document.createElement("div");p.style.cssText=`position:fixed;left:${l}px;top:${d}px;z-index:1000;display:flex;align-items:center;gap:4px;padding:4px 6px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.4);font-family:inherit;`;const c=document.createElement("textarea");c.style.cssText="width:90px;height:22px;resize:none;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-size:11px;font-family:inherit;padding:2px 4px;outline:none;",c.placeholder="Ctrl+V",c.addEventListener("paste",f=>{var h;f.preventDefault();const u=(h=f.clipboardData)==null?void 0:h.getData("text/plain");u&&r.current(u),s()}),c.addEventListener("keydown",f=>{f.key==="Escape"&&s()}),p.appendChild(c),document.body.appendChild(p),e.current=p,requestAnimationFrame(()=>{const f=p.getBoundingClientRect();f.right>window.innerWidth&&(p.style.left=`${window.innerWidth-f.width-8}px`),f.bottom>window.innerHeight&&(p.style.top=`${window.innerHeight-f.height-8}px`),c.focus()}),n.current=setTimeout(s,8e3)},[s]);return o.useEffect(()=>{const l=()=>{e.current&&s()};return document.addEventListener("click",l),()=>{document.removeEventListener("click",l),s()}},[s]),{showPasteFloat:i,removePasteFloat:s}}const st={background:"#000000",foreground:"#cccccc",cursor:"#aeafad",selectionBackground:"rgba(38, 79, 120, 0.5)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5"},ot={background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"rgba(9, 105, 218, 0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#2da44e",brightYellow:"#bf8803",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"},In="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",as=o.forwardRef(function({sessionId:e},n){const r=o.useRef(null),s=o.useRef(null),i=o.useRef(null),[l,d]=o.useState(!1),[p,c]=o.useState(""),f=A(L=>L.fontSize),u=A(L=>L.theme),h=o.useCallback(L=>{c(L),d(!0)},[]),{sendInput:g,sendResize:b,requestScrollback:j,requestFileStream:k,cancelFileStream:C}=ss(s,e,h);o.useImperativeHandle(n,()=>({sendInput:g,requestFileStream:k,cancelFileStream:C}),[g,k,C]);const v=o.useRef(g),I=o.useRef(b);v.current=g,I.current=b;const{removePasteFloat:T}=os(L=>v.current(L));return o.useEffect(()=>{if(!r.current)return;let L=!1,$=null,O=null,W=null,B=null;if(L||!r.current)return;const F=new hn({cursorBlink:!0,scrollback:1e4,fontSize:A.getState().fontSize,fontFamily:In,theme:A.getState().theme==="dark"?st:ot,allowProposedApi:!0}),N=new gn;F.loadAddon(N),F.loadAddon(new qn((H,D)=>{window.open(D,"_blank","noopener,noreferrer")})),F.open(r.current);try{const H=new bn;H.onContextLoss(()=>{H.dispose()}),F.loadAddon(H)}catch{}s.current=F,i.current=N,F.onSelectionChange(()=>{const H=F.getSelection();H&&navigator.clipboard.writeText(H).catch(()=>{})});const S=F.element,w=H=>{var D;H.preventDefault(),T(),(D=navigator.clipboard)!=null&&D.readText&&navigator.clipboard.readText().then(z=>{z&&v.current(z)}).catch(()=>{})};S&&S.addEventListener("contextmenu",w);const q=()=>{try{const H=r.current;if(H&&H.clientWidth>0&&H.clientHeight>0)return N.fit(),I.current(F.cols,F.rows),!0}catch{}return!1};requestAnimationFrame(()=>q());let V=0;$=setInterval(()=>{V++,(q()||V>=10)&&(clearInterval($),$=null)},100),document.fonts.ready.then(()=>{if(!L)try{N.fit(),I.current(F.cols,F.rows)}catch{}});let U=null;const J=()=>{L||(U&&clearTimeout(U),U=setTimeout(()=>{if(!L)try{N.fit(),I.current(F.cols,F.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",J),F.onData(H=>{v.current(H)});let _=!1;return B=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!_){_=!0;const D=()=>{document.removeEventListener("mouseup",D),_=!1,requestAnimationFrame(()=>{try{N.fit(),I.current(F.cols,F.rows)}catch{}})};document.addEventListener("mouseup",D)}return}O||(O=requestAnimationFrame(()=>{O=null;try{N.fit(),W&&clearTimeout(W),W=setTimeout(()=>{W=null,I.current(F.cols,F.rows)},50)}catch{}}))}),B.observe(r.current),()=>{L=!0,$&&clearInterval($),O&&cancelAnimationFrame(O),W&&clearTimeout(W),U&&clearTimeout(U),document.fonts.removeEventListener("loadingdone",J),B&&B.disconnect(),T(),S&&S.removeEventListener("contextmenu",w),s.current&&(s.current.dispose(),s.current=null),i.current=null}},[e]),o.useEffect(()=>{const L=s.current,$=i.current;if(!(!L||!$)&&L.options.fontSize!==f){L.options.fontSize=f;try{$.fit()}catch{}I.current(L.cols,L.rows)}},[f]),o.useEffect(()=>{s.current&&(s.current.options.theme=u==="dark"?st:ot)},[u]),a.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[a.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),a.jsx("button",{tabIndex:-1,onClick:L=>{L.currentTarget.blur(),l?(d(!1),c("")):j()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:l?"var(--accent-blue)":"var(--bg-hover)",color:"var(--text-bright)",border:"none",borderRadius:4,padding:"2px 8px",fontSize:14,cursor:"pointer",opacity:.8,lineHeight:"20px"},onMouseEnter:L=>{L.currentTarget.style.opacity="1"},onMouseLeave:L=>{L.currentTarget.style.opacity="0.8"},children:l?"✕":a.jsx("span",{style:{fontSize:14},children:"👁"})}),l&&a.jsx(is,{data:p,onClose:()=>{d(!1),c("")}})]})});function is({data:t,onClose:e}){const n=o.useRef(null),r=o.useRef(e);r.current=e;const s=A(c=>c.fontSize),i=A(c=>c.theme),l=o.useRef(null),d=o.useRef(null);o.useEffect(()=>{if(!n.current)return;const c=new hn({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:s,fontFamily:In,theme:i==="dark"?st:ot});l.current=c;const f=new gn;d.current=f,c.loadAddon(f),c.open(n.current);let u=null;try{u=new bn,u.onContextLoss(()=>{u==null||u.dispose(),u=null}),c.loadAddon(u)}catch{u=null}c.onSelectionChange(()=>{const C=c.getSelection();C&&navigator.clipboard.writeText(C).catch(()=>{})}),c.attachCustomKeyEventHandler(C=>(C.key==="Escape"&&r.current(),!1)),c.write(t);let h=null;const g=()=>{const C=n.current;if(!C||C.clientWidth<=0||C.clientHeight<=0)return!1;try{return f.fit(),c.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!g()){let C=0;h=setInterval(()=>{C++,(g()||C>=30)&&(clearInterval(h),h=null)},50)}});let b=null;const j=new ResizeObserver(()=>{b||(b=requestAnimationFrame(()=>{b=null,g()}))});j.observe(n.current);const k=C=>{C.key==="Escape"&&r.current()};return document.addEventListener("keydown",k),()=>{if(h&&clearInterval(h),b&&cancelAnimationFrame(b),document.removeEventListener("keydown",k),j.disconnect(),u){try{u.dispose()}catch{}u=null}c.dispose(),l.current=null,d.current=null}},[t]),o.useEffect(()=>{var c;if(l.current){l.current.options.fontSize=s;try{(c=d.current)==null||c.fit()}catch{}}},[s]),o.useEffect(()=>{l.current&&(l.current.options.theme=i==="dark"?st:ot)},[i]);const p=28;return a.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[a.jsx("div",{style:{height:p,boxSizing:"border-box",padding:"0 12px",background:"var(--bg-tertiary)",color:"var(--accent-blue)",fontSize:12,borderBottom:"1px solid var(--scrollbar-thumb-hover)",display:"flex",alignItems:"center"},children:a.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),a.jsx("div",{ref:n,style:{position:"absolute",top:p,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const ls=50;function Tt(){const t=o.useRef([]),e=o.useCallback(s=>{t.current.push(s),t.current.length>ls&&t.current.shift()},[]),n=o.useCallback(()=>t.current.pop(),[]),r=o.useCallback(()=>{t.current=[]},[]);return o.useMemo(()=>({pushUndo:e,popUndo:n,clearUndo:r}),[e,n,r])}function Ct(t,e,n){t.preventDefault();const r=t.currentTarget,s=r.selectionStart,i=r.selectionEnd,l=r.value;n==null||n(l);const d=l.slice(0,s)+" "+l.slice(i);e(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=s+2})}function at(t,e=20){var n;return Math.min(e,Math.max(1,(((n=t.match(/\n/g))==null?void 0:n.length)??0)+1))}let Be=null,Rn="dark";const cs=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],ds={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"},us={primaryColor:"#2e59a8",primaryTextColor:"#343b58",primaryBorderColor:"#9aa5ce",lineColor:"#8c8fa1",secondaryColor:"#7847bd",tertiaryColor:"#d5d6db",background:"#f5f5f5",mainBkg:"#e8e8ed",nodeBorder:"#9aa5ce",clusterBkg:"#ebebf0",titleColor:"#343b58",edgeLabelBackground:"#ebebf0",gridColor:"#d5d6db",doneTaskBkgColor:"#4e8a2f",doneTaskBorderColor:"#3d6e25",activeTaskBkgColor:"#2e59a8",activeTaskBorderColor:"#24478a",critBkgColor:"#c4384b",critBorderColor:"#a02e3e",taskBkgColor:"#c0c1c9",taskBorderColor:"#9aa5ce",taskTextColor:"#343b58",taskTextDarkColor:"#f5f5f5",sectionBkgColor:"#e8e8ed",sectionBkgColor2:"#d5d6db",altSectionBkgColor:"#e8e8ed",todayLineColor:"#b68d28"},fs={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function Gt(t,e){return Rn=e,t.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:e==="dark"?ds:us,gantt:fs}),t}function ps(t="dark"){return Be?Rn!==t?Be.then(e=>Gt(e,t)):Be:(Be=(async()=>{for(const e of cs)try{const n=await import(e);return Gt(n.default,t)}catch{}throw Be=null,new Error("All mermaid CDN sources failed")})(),Be)}let qt=0;function ms(t,e,n="dark"){const r=o.useRef(n);o.useEffect(()=>{const s=t.current;if(!s)return;const i=r.current!==n;r.current=n;const l=s.querySelectorAll("code.language-mermaid, code.language-gantt"),d=i?s.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(l.length===0&&d.length===0)return;let p=!1;return(async()=>{let c;try{c=await ps(n)}catch{if(p)return;for(const u of l){const h=u.parentElement;if(!h||h.tagName!=="PRE")continue;h.classList.add("mermaid-error");const g=document.createElement("div");g.className="mermaid-error__msg",g.textContent="Failed to load Mermaid library",h.appendChild(g)}return}if(!p){for(const f of d){if(p)break;const u=f.getAttribute("data-mermaid-source");if(!u)continue;const h=`mermaid-${++qt}`;try{const{svg:g}=await c.render(h,u);if(p)break;f.innerHTML=wt.sanitize(g,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const f of l){if(p)break;const u=f.parentElement;if(!u||u.tagName!=="PRE")continue;const h=f.textContent||"";if(!h.trim())continue;const g=`mermaid-${++qt}`;try{const{svg:b}=await c.render(g,h);if(p)break;const j=document.createElement("div");j.className="mermaid-diagram",j.setAttribute("data-mermaid-source",h),j.innerHTML=wt.sanitize(b,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),u.replaceWith(j)}catch{if(p)break;u.classList.add("mermaid-error");const b=document.createElement("div");b.className="mermaid-error__msg",b.textContent="Mermaid syntax error",u.appendChild(b)}}}})(),()=>{p=!0}},[e,n])}async function hs(t,e,n){const r=await pe.get(t,e,"annotations",{path:n});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function Nn(t,e,n,r,s){await pe.put(t,e,"annotations",{path:n,content:r,updatedAt:s})}async function Yt(t,e,n,r){return pe.post(t,e,"task-annotations",{modulePath:n,content:r})}const Et={additions:[],deletions:[],replacements:[],comments:[]};let gs=0;function Se(){return`ann_${++gs}_${Date.now()}`}function qe(t,e){return`plan-annotations-${t}-${e}`}function Xt(t,e){return`plan-scroll-${t}-${e}`}function bs(t){const e=String(xn.parser([t],{async:!1}));return wt.sanitize(e,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function tt(t,e){let n=1;for(let r=0;r<e&&r<t.length;r++){const s=t[r].raw??"";for(const i of s)i===`
|
|
26
|
-
`&&n++}return n}function nt(t,e,n,r){const s=t.join(`
|
|
27
|
-
`);let i=0;for(let g=0;g<e-1&&g<t.length;g++)i+=t[g].length+1;let l=0;for(let g=0;g<n&&g<t.length;g++)l+=t[g].length+1;let d=i,p=Math.min(s.length,l);if(r){const g=Math.max(0,i-10),b=Math.min(s.length,l+10),k=s.slice(g,b).indexOf(r);k>=0&&(d=g+k,p=d+r.length)}const c=Math.max(0,d-20),f=s.slice(c,d).replace(/\n/g,"↵"),u=Math.min(s.length,p+20),h=s.slice(p,u).replace(/\n/g,"↵");return{before:f,after:h}}function Zt(t,e){const n=[],r=[],s=[],i=[];for(const l of t.additions){const{before:d,after:p}=nt(e,l.sourceLine,l.sourceLine);n.push([`Line${l.sourceLine}:...${d}`,l.content,`${p}...`])}for(const l of t.deletions){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);r.push([`Line${l.startLine}:...${d}`,l.selectedText,`${p}...`])}for(const l of t.replacements){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);s.push([`Line${l.startLine}:...${d}`,l.selectedText,l.content,`${p}...`])}for(const l of t.comments){const{before:d,after:p}=nt(e,l.startLine,l.endLine,l.selectedText);i.push([`Line${l.startLine}:...${d}`,l.selectedText,l.content,`${p}...`])}return{"Insert Annotations":n,"Delete Annotations":r,"Replace Annotations":s,"Comment Annotations":i}}function Qt(t){return t.additions.length>0||t.deletions.length>0||t.replacements.length>0||t.comments.length>0}function en(t){return/^[a-zA-Z0-9_./:@=-]+$/.test(t)?t:"'"+t.replace(/'/g,"'\\''")+"'"}function tn(t,e){return`/ai-cli-task:ai-cli-task plan ${en(t)} ${en(e)} --silent`}function nn(t){const e=t.split("/"),n=e.indexOf("AiTasks");return n>=0&&n+1<e.length?e.slice(0,n+2).join("/"):t.substring(0,t.lastIndexOf("/"))}function it(t){const e=new Set;return t.additions.forEach(n=>e.add(n.id)),t.deletions.forEach(n=>e.add(n.id)),t.replacements.forEach(n=>e.add(n.id)),t.comments.forEach(n=>e.add(n.id)),e}function rn(t){return t.replacements||(t.replacements=[]),t.comments||(t.comments=[]),t}function xs({sessionId:t,filePath:e,token:n,annotations:r,annLoadedRef:s,setAnnotations:i,baselineIdsRef:l}){const d=A(u=>u.latency),p=o.useRef(void 0),c=o.useRef(void 0),f=o.useRef(!1);o.useEffect(()=>{if(!s.current)return;const u=qe(t,e),h=JSON.stringify(r);p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(u,h)}catch{}},50),c.current&&clearTimeout(c.current);const g=Math.max(200,(d??30)*3);return c.current=setTimeout(()=>{f.current||(f.current=!0,Nn(n,t,e,h,Date.now()).catch(()=>{}).finally(()=>{f.current=!1}))},g),()=>{p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current)}},[r,t,e,n,d,s]),o.useEffect(()=>{s.current=!1;let u=Et,h=0;try{const b=localStorage.getItem(qe(t,e));b&&(u=rn(JSON.parse(b)),h=Date.now())}catch{}i(u),l.current=it(u);let g=!1;return hs(n,t,e).then(b=>{if(!g&&b&&b.updatedAt>h)try{const j=rn(JSON.parse(b.content));i(j);try{localStorage.setItem(qe(t,e),b.content)}catch{}l.current=it(j)}catch{}}).catch(()=>{}).finally(()=>{s.current=!0}),s.current=!0,()=>{g=!0}},[t,e,n,s,i,l])}async function sn(t,e,n,r){const s={path:n};return r&&(s.since=String(r)),pe.getOptional(t,e,"file-content",s)}async function on(t,e,n,r){return pe.putJson(t,e,"file-content",{path:n,content:r})}function Ln(t,e){let n=t.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");n||(n="heading");const r=e.get(n)||0;return r>0&&(n=`${n}-${r}`),e.set(n,r+1),n}function Dn(t){return t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function ys(t){if(!t)return[];const e=[],n=new Map,r=t.split(`
|
|
28
|
-
`);let s=!1;for(const i of r){if(/^```/.test(i.trim())){s=!s;continue}if(s)continue;const l=i.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(l){const d=l[1].length,p=Dn(l[2]),c=Ln(p,n);e.push({id:c,text:p,level:d})}}return e}const vs=160,ws=22;function Ss({headings:t,scrollRef:e}){const[n,r]=o.useState(null),[s,i]=o.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),l=o.useRef(null),d=o.useRef(!1),p=o.useMemo(()=>Math.min(...t.map(u=>u.level)),[t]),c=o.useCallback(()=>{i(u=>{const h=!u;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);o.useEffect(()=>{const u=e.current;if(!u||t.length===0)return;const h=()=>{d.current=!1;const b=u.scrollTop,j=50;let k=null;for(const C of t){const v=u.querySelector(`[id="${CSS.escape(C.id)}"]`);v&&v.offsetTop<=b+j&&(k=C.id)}r(k)},g=()=>{d.current||(d.current=!0,requestAnimationFrame(h))};return h(),u.addEventListener("scroll",g,{passive:!0}),()=>u.removeEventListener("scroll",g)},[t,e]);const f=o.useCallback(u=>{const h=e.current;if(!h)return;const g=h.querySelector(`[id="${CSS.escape(u)}"]`);g&&(g.scrollIntoView({behavior:"smooth",block:"start"}),r(u))},[e]);return o.useEffect(()=>{if(!n||s)return;const u=l.current;if(!u)return;const h=u.querySelector(`[data-toc-id="${CSS.escape(n)}"]`);if(h){const g=h.offsetTop-u.offsetTop,b=g+h.offsetHeight;(g<u.scrollTop||b>u.scrollTop+u.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[n,s]),t.length<2?null:s?a.jsx("div",{style:{width:ws,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:a.jsx("button",{onClick:c,title:"Show table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:13,cursor:"pointer",padding:"2px",lineHeight:1},onMouseEnter:u=>{u.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:u=>{u.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):a.jsxs("div",{ref:l,style:{width:vs,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[a.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),a.jsx("button",{onClick:c,title:"Hide table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:"0 2px",lineHeight:1},onMouseEnter:u=>{u.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:u=>{u.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),a.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:t.map((u,h)=>a.jsx("div",{"data-toc-id":u.id,onClick:()=>f(u.id),style:{padding:`2px 6px 2px ${(u.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:n===u.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:n===u.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:u.level<=2?500:400,transition:"color 0.1s"},title:u.text,onMouseEnter:g=>{n!==u.id&&(g.currentTarget.style.color="var(--text-primary)"),g.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:g=>{n!==u.id&&(g.currentTarget.style.color="var(--text-secondary)"),g.currentTarget.style.backgroundColor="transparent"},children:u.text},`${u.id}-${h}`))})]})}const ks={add:{symbol:"+",color:"var(--accent-yellow)",field:"content"},del:{symbol:"−",color:"var(--accent-red)",field:"selectedText"},rep:{symbol:"⇄",color:"var(--accent-blue)",field:"content"},com:{symbol:"?",color:"var(--accent-green)",field:"content"}};function Ts({annotations:t,annCounts:e,isSent:n,onSendAll:r,onSendSingle:s,onDelete:i}){const[l,d]=o.useState(!1),p=o.useRef(null);o.useEffect(()=>{if(!l)return;const u=h=>{p.current&&!p.current.contains(h.target)&&d(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[l]);const c=o.useCallback((u,h,g)=>{const b=ks[h],j=n(u);return a.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[a.jsx("span",{className:"plan-anno-dropdown__type",style:{color:b.color},children:b.symbol}),a.jsxs("span",{className:"plan-anno-dropdown__text",children:[g.slice(0,60),g.length>60?"...":""]}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!j&&s(u,h),disabled:j,title:j?"Already sent":"Send to terminal",style:j?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(u,h),title:"Delete",children:"×"})]},u)},[n,s,i]),f=(()=>{const u=t.additions[0],h=t.deletions[0],g=t.replacements[0],b=t.comments[0],j=u?u.content:h?h.selectedText:g?g.content:b?b.content:"";return j?j.slice(0,40)+(j.length>40?"...":""):""})();return a.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[a.jsxs("div",{className:`plan-anno-dropdown-trigger${l?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>d(u=>!u),title:e.total>0?`${e.total} annotations (${e.unsent} unsent)`:"No annotations",children:[a.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:f}),a.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),l&&a.jsxs("div",{className:"plan-anno-dropdown",children:[e.unsent>0&&a.jsx("div",{className:"plan-anno-dropdown__header",children:a.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",e.unsent,")"]})}),a.jsxs("div",{className:"plan-anno-dropdown__list",children:[t.additions.map(u=>c(u.id,"add",u.content)),t.deletions.map(u=>c(u.id,"del",u.selectedText)),t.replacements.map(u=>c(u.id,"rep",u.content)),t.comments.map(u=>c(u.id,"com",u.content)),e.total===0&&a.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const Cs={del:{className:"plan-deletion-card",icon:"",color:"var(--accent-red)"},rep:{className:"plan-replace-card",icon:"⇄",color:"var(--accent-blue)"},com:{className:"plan-comment-card",icon:"?",color:"var(--accent-green)"}};function yt({type:t,annotation:e,fontSize:n,onEdit:r,onRemove:s,onSend:i,isSent:l}){const d=Cs[t],[p,c]=o.useState(!1),[f,u]=o.useState(""),h=o.useRef(null),g=t==="del"?e.selectedText:e.content,b=o.useCallback(()=>{c(!0),u(g)},[g]),j=o.useCallback(()=>{const k=f.trim();k?r(e.id,k):s(e.id),c(!1)},[f,e.id,r,s]);return o.useEffect(()=>{p&&requestAnimationFrame(()=>{const k=h.current;k&&(k.focus(),k.selectionStart=k.selectionEnd=k.value.length)})},[p]),p?a.jsx("div",{className:d.className,children:a.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:f,onChange:k=>u(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),j()),k.key==="Escape"&&(k.preventDefault(),c(!1))},onBlur:j,rows:at(f),style:{fontSize:`${n}px`,flex:1}})}):a.jsxs("div",{className:d.className,children:[d.icon&&a.jsx("span",{style:{color:d.color,flexShrink:0},children:d.icon}),t==="del"?a.jsx("span",{style:{flex:1,fontSize:`${n}px`,color:d.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:e.selectedText}):t==="rep"?a.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:[a.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:e.selectedText}),a.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),a.jsx("span",{style:{color:"var(--accent-blue)"},children:e.content})]}):a.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:b,title:"Double-click to edit",children:[a.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',e.selectedText,'"']}),a.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),a.jsx("span",{style:{color:"var(--accent-green)"},children:e.content})]}),i&&a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!l&&i(e.id),disabled:l,title:l?"Already sent":"Send to terminal",style:l?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:b,style:{color:"var(--accent-blue)"},title:`Edit ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"✎"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>s(e.id),title:`Remove ${t==="del"?"deletion":t==="rep"?"replacement":"comment"}`,children:"×"})]})}function Es({x:t,y:e,onDelete:n,onReplace:r,onComment:s}){return a.jsxs("div",{className:"plan-selection-float",style:{top:e,left:t},children:[a.jsx("button",{className:"plan-selection-float__delete",onMouseDown:i=>{i.preventDefault(),n()},title:"Delete selection",children:"−"}),a.jsx("button",{className:"plan-selection-float__replace",onMouseDown:i=>{i.preventDefault(),r()},title:"Replace selection",children:"⇄"}),a.jsx("button",{className:"plan-selection-float__comment",onMouseDown:i=>{i.preventDefault(),s()},title:"Comment on selection",children:"?"})]})}const js=o.forwardRef(function({markdown:e,filePath:n,sessionId:r,token:s,onExecute:i,onSend:l,onRefresh:d,onClose:p,onContentSaved:c,expanded:f,readOnly:u},h){const g=A(m=>m.fontSize),[b,j]=o.useState(null),k=o.useRef(void 0),C=o.useCallback((m,x)=>{clearTimeout(k.current),j({type:m,msg:x}),k.current=setTimeout(()=>j(null),m==="ok"?2500:5e3)},[]);o.useEffect(()=>()=>clearTimeout(k.current),[]);const[v,I]=o.useState(!1),[T,L]=o.useState(""),[$,O]=o.useState(!1),W=o.useRef(null),B=A(m=>m.latency),F=`plan-edit:${r}:${n}`,N=o.useRef(void 0),S=o.useRef(void 0),w=o.useRef(!1);o.useEffect(()=>{if(!v)return;clearTimeout(N.current),N.current=setTimeout(()=>{try{localStorage.setItem(F,T)}catch{}},50),clearTimeout(S.current);const m=Math.max(200,(B??30)*3);return S.current=setTimeout(()=>{w.current||(w.current=!0,on(s,r,n,T).then(x=>{c==null||c(T,x.mtime)}).catch(()=>{}).finally(()=>{w.current=!1}))},m),()=>{clearTimeout(N.current),clearTimeout(S.current)}},[T,v,F,s,r,n,B,c]),o.useEffect(()=>{I(!1)},[n]),o.useEffect(()=>{v&&requestAnimationFrame(()=>{var m;return(m=W.current)==null?void 0:m.focus()})},[v]);const q=o.useCallback(()=>{if(u||v)return;const m=localStorage.getItem(`plan-edit:${r}:${n}`);L(m??e),I(!0)},[u,v,e,r,n]),V=o.useCallback(()=>{I(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${n}`)},[r,n]),U=o.useCallback(async()=>{if(!$){O(!0);try{const m=await on(s,r,n,T);c==null||c(T,m.mtime),I(!1),L(""),localStorage.removeItem(`plan-edit:${r}:${n}`),C("ok","Saved")}catch(m){const x=m instanceof Error?m.message:"Failed to save";C("err",x)}finally{O(!1)}}},[$,s,r,n,T,c,C]),J=o.useMemo(()=>e?xn.lexer(e):[],[e]),_=o.useMemo(()=>e.split(`
|
|
29
|
-
`),[e]),H=o.useMemo(()=>ys(e),[e]),D=o.useMemo(()=>{const m=new Map,x=new Map;return J.forEach((M,R)=>{if(M.type==="heading"){const ee=Dn(M.text||""),Y=Ln(ee,x);m.set(R,Y)}}),m},[J]),z=o.useRef(new Set),Q=o.useRef(!1),[P,G]=o.useState(()=>{try{const m=localStorage.getItem(qe(r,n)),x=m?JSON.parse(m):Et;return z.current=it(x),x.replacements||(x.replacements=[]),x.comments||(x.comments=[]),x}catch{return Et}});xs({sessionId:r,filePath:n,token:s,annotations:P,annLoadedRef:Q,setAnnotations:G,baselineIdsRef:z});const[be,je]=o.useState(0),Ue=o.useMemo(()=>{const m=z.current,x=P.additions.length+P.deletions.length+P.replacements.length+P.comments.length;let M=0;return P.additions.forEach(R=>{m.has(R.id)&&M++}),P.deletions.forEach(R=>{m.has(R.id)&&M++}),P.replacements.forEach(R=>{m.has(R.id)&&M++}),P.comments.forEach(R=>{m.has(R.id)&&M++}),{total:x,sent:M,unsent:x-M}},[P,be]),[ae,Te]=o.useState(null),[xe,ce]=o.useState(""),he=o.useRef(null),[X,ye]=o.useState(null),[Ce,Ee]=o.useState(""),Me=o.useRef(null),[re,ve]=o.useState(null),ie=o.useRef(null),He=o.useRef(0),$e=o.useRef(null);o.useEffect(()=>{const m=ie.current;if(!m)return;let x;const M=()=>{clearTimeout(x),x=setTimeout(()=>{const R=Xt(r,n);if(m.scrollTop>0)try{localStorage.setItem(R,String(m.scrollTop))}catch{}else localStorage.removeItem(R)},50)};return m.addEventListener("scroll",M,{passive:!0}),()=>{clearTimeout(x),m.removeEventListener("scroll",M)}},[r,n]),o.useEffect(()=>{if(!J.length)return;const m=localStorage.getItem(Xt(r,n));if(!m)return;const x=Number(m),M=ie.current;if(!M||(M.scrollTop=x,M.scrollTop>=x-10))return;let R;const ee=()=>{M.scrollTop=x,Y.disconnect()},Y=new MutationObserver(()=>{clearTimeout(R),R=setTimeout(ee,80)});Y.observe(M,{childList:!0,subtree:!0});const ne=setTimeout(ee,500);return()=>{clearTimeout(R),clearTimeout(ne),Y.disconnect()}},[r,n,J.length]),o.useEffect(()=>{ae!=null&&requestAnimationFrame(()=>{var m;return(m=he.current)==null?void 0:m.focus()})},[ae]),o.useEffect(()=>{X&&requestAnimationFrame(()=>{var m;return(m=Me.current)==null?void 0:m.focus()})},[X]);const _e=o.useRef({annotations:P,activeInsert:ae,insertText:xe,pendingAction:X,pendingText:Ce,tokens:J,filePath:n,sessionId:r,token:s});_e.current={annotations:P,activeInsert:ae,insertText:xe,pendingAction:X,pendingText:Ce,tokens:J,filePath:n,sessionId:r,token:s},o.useEffect(()=>()=>{const m=_e.current;let x=m.annotations,M=!1;if(m.activeInsert!=null&&m.insertText.trim()){const R=tt(m.tokens,m.activeInsert+1);x={...x,additions:[...x.additions,{id:Se(),afterTokenIndex:m.activeInsert,sourceLine:R,content:m.insertText.trim()}]},M=!0}if(m.pendingAction&&m.pendingText.trim()){const R=m.pendingAction,ee=m.pendingText.trim();R.type==="replace"?x={...x,replacements:[...x.replacements,{id:Se(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ee}]}:x={...x,comments:[...x.comments,{id:Se(),tokenIndices:R.tokenIndices,startLine:R.startLine,endLine:R.endLine,selectedText:R.text,content:ee}]},M=!0}if(M){const R=JSON.stringify(x);try{localStorage.setItem(qe(m.sessionId,m.filePath),R)}catch{}Nn(m.token,m.sessionId,m.filePath,R,Date.now()).catch(()=>{})}},[]);const Ne=o.useCallback(m=>{if(!xe.trim()){Te(null),ce("");return}const x=tt(J,m+1);G(M=>({...M,additions:[...M.additions,{id:Se(),afterTokenIndex:m,sourceLine:x,content:xe.trim()}]})),Te(null),ce("")},[xe,J]),Le=o.useCallback(m=>{G(x=>({...x,additions:x.additions.filter(M=>M.id!==m)}))},[]),Ye=o.useCallback((m,x)=>{G(M=>({...M,additions:M.additions.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),ft=o.useCallback(()=>{var m;re&&(G(x=>({...x,deletions:[...x.deletions,{id:Se(),tokenIndices:re.tokenIndices,startLine:re.startLine,endLine:re.endLine,selectedText:re.text.slice(0,80)}]})),ve(null),(m=window.getSelection())==null||m.removeAllRanges())},[re]),y=o.useCallback(m=>{var x;re&&(ye({type:m,tokenIndices:re.tokenIndices,startLine:re.startLine,endLine:re.endLine,text:re.text.slice(0,80)}),Ee(""),ve(null),(x=window.getSelection())==null||x.removeAllRanges())},[re]),E=o.useCallback(()=>{if(!X)return;const m=Ce.trim();if(!m){ye(null),Ee("");return}X.type==="replace"?G(x=>({...x,replacements:[...x.replacements,{id:Se(),tokenIndices:X.tokenIndices,startLine:X.startLine,endLine:X.endLine,selectedText:X.text,content:m}]})):G(x=>({...x,comments:[...x.comments,{id:Se(),tokenIndices:X.tokenIndices,startLine:X.startLine,endLine:X.endLine,selectedText:X.text,content:m}]})),ye(null),Ee("")},[X,Ce]),K=o.useCallback(m=>{G(x=>({...x,replacements:x.replacements.filter(M=>M.id!==m)}))},[]),Z=o.useCallback((m,x)=>{G(M=>({...M,replacements:M.replacements.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),te=o.useCallback(m=>{G(x=>({...x,comments:x.comments.filter(M=>M.id!==m)}))},[]),we=o.useCallback((m,x)=>{G(M=>({...M,comments:M.comments.map(R=>R.id===m?{...R,id:Se(),content:x}:R)}))},[]),se=o.useCallback(m=>{G(x=>({...x,deletions:x.deletions.filter(M=>M.id!==m)}))},[]),fe=o.useCallback((m,x)=>{G(M=>({...M,deletions:M.deletions.map(R=>R.id===m?{...R,id:Se(),selectedText:x}:R)}))},[]),de=o.useCallback(m=>{let x=m instanceof Element?m:m.parentElement;for(;x&&x!==ie.current;){if(x.hasAttribute("data-token-index"))return x;x=x.parentElement}return null},[]),oe=o.useCallback(()=>{const m=window.getSelection();if(!m||m.isCollapsed||!ie.current){ve(null);return}const x=m.toString().trim();if(!x){ve(null);return}const M=m.getRangeAt(0);if(!ie.current.contains(M.commonAncestorContainer)){ve(null);return}const R=de(M.startContainer),ee=de(M.endContainer);if(!R||!ee){ve(null);return}const Y=parseInt(R.getAttribute("data-token-index")||"0",10),ne=parseInt(ee.getAttribute("data-token-index")||"0",10),Lt=[];for(let gt=Math.min(Y,ne);gt<=Math.max(Y,ne);gt++)Lt.push(gt);const Un=tt(J,Math.min(Y,ne)),Hn=tt(J,Math.max(Y,ne)+1),Dt=M.getBoundingClientRect(),ht=ie.current,Mt=ht.getBoundingClientRect();navigator.clipboard.writeText(x).catch(()=>{});const Xe=$e.current,At=Xe&&Date.now()-Xe.time<500;He.current=Date.now(),ve({x:(At?Xe.x:Dt.right)-Mt.left+ht.scrollLeft+6,y:(At?Xe.y:Dt.top)-Mt.top+ht.scrollTop-44,tokenIndices:Lt,startLine:Un,endLine:Hn,text:x})},[J,de]),ge=o.useRef(void 0);o.useEffect(()=>{const m=()=>{ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{const x=window.getSelection();if(!x||x.isCollapsed||!ie.current){if(Date.now()-He.current<300)return;ve(null);return}const M=x.anchorNode;M&&ie.current.contains(M)&&oe()},120)};return document.addEventListener("selectionchange",m),()=>{document.removeEventListener("selectionchange",m),ge.current&&clearTimeout(ge.current)}},[oe]);const Ke=A(m=>m.theme);ms(ie,J,Ke);const Oe=o.useCallback(()=>{const m=z.current;return{additions:P.additions.filter(x=>!m.has(x.id)),deletions:P.deletions.filter(x=>!m.has(x.id)),replacements:P.replacements.filter(x=>!m.has(x.id)),comments:P.comments.filter(x=>!m.has(x.id))}},[P]),pt=o.useCallback(async()=>{const m=Oe();if(!Qt(m))return;const x=Zt(m,_),M=nn(n);try{const{path:R}=await Yt(s,r,M,x),ee=tn(n,R);i(ee),z.current=it(P),je(ne=>ne+1);const Y=m.additions.length+m.deletions.length+m.replacements.length+m.comments.length;C("ok",`Sent ${Y} annotation(s)`)}catch(R){const ee=R instanceof Error?R.message:"Failed to send";C("err",ee)}},[Oe,P,_,i,n,s,r,C]),Fe=o.useCallback(async(m,x)=>{if(!l)return;const M={additions:[],deletions:[],replacements:[],comments:[]};if(x==="add"){const Y=P.additions.find(ne=>ne.id===m);if(!Y)return;M.additions.push(Y)}else if(x==="del"){const Y=P.deletions.find(ne=>ne.id===m);if(!Y)return;M.deletions.push(Y)}else if(x==="rep"){const Y=P.replacements.find(ne=>ne.id===m);if(!Y)return;M.replacements.push(Y)}else{const Y=P.comments.find(ne=>ne.id===m);if(!Y)return;M.comments.push(Y)}const R=Zt(M,_),ee=nn(n);try{const{path:Y}=await Yt(s,r,ee,R);l(tn(n,Y)),z.current.add(m),je(ne=>ne+1),C("ok","Sent 1 annotation")}catch(Y){const ne=Y instanceof Error?Y.message:"Failed to send";C("err",ne)}},[l,n,P,_,s,r,C]),Fn=o.useCallback((m,x)=>{x==="add"?Le(m):x==="del"?se(m):x==="rep"?K(m):te(m)},[Le,se,K,te]);o.useImperativeHandle(h,()=>({getSummary:()=>{const m=Oe();return Qt(m)?"[pending annotations]":""},handleEscape:()=>v?(V(),!0):X?(E(),!0):ae!=null?(Ne(ae),!0):!1,getScrollTop:()=>{var m;return((m=ie.current)==null?void 0:m.scrollTop)??0},setScrollTop:m=>{requestAnimationFrame(()=>{ie.current&&(ie.current.scrollTop=m)})}}),[Oe,v,V,ae,Ne,X,E]);const Bn=o.useMemo(()=>{const m=new Set;return P.deletions.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.deletions]),Pn=o.useMemo(()=>{const m=new Set;return P.replacements.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.replacements]),Wn=o.useMemo(()=>{const m=new Set;return P.comments.forEach(x=>x.tokenIndices.forEach(M=>m.add(M))),m},[P.comments]),Rt=o.useMemo(()=>{const m=new Map;return P.additions.forEach(x=>{const M=m.get(x.afterTokenIndex)||[];M.push(x),m.set(x.afterTokenIndex,M)}),m},[P.additions]),Nt=Ue.unsent>0,mt=o.useCallback(m=>z.current.has(m),[]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[a.jsxs("div",{className:"plan-anno-toolbar",children:[a.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:n,children:n.split("/").pop()||n}),b&&a.jsx("span",{style:{fontSize:"10px",color:b.type==="ok"?"var(--accent-green)":"var(--accent-red)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:160,cursor:b.type==="err"?"pointer":void 0},title:b.type==="err"?"Click to copy":b.msg,onClick:b.type==="err"?()=>{navigator.clipboard.writeText(b.msg).catch(()=>{}),C("ok","Copied")}:void 0,children:b.msg}),v?a.jsxs(a.Fragment,{children:[a.jsx("button",{className:"pane-btn",onClick:U,disabled:$,style:{color:"var(--accent-green)"},title:"Save (Ctrl+S)",children:$?"Saving...":"Save"}),a.jsx("button",{className:"pane-btn",onClick:V,disabled:$,title:"Cancel (Esc)",children:"Cancel"})]}):a.jsxs(a.Fragment,{children:[d&&a.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),!u&&a.jsx("button",{className:"pane-btn",onClick:q,title:"Edit file (double-click content)",children:"Edit"}),a.jsx("button",{className:"pane-btn",onClick:pt,disabled:!Nt,title:"Send all annotations",style:Nt?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),a.jsx(Ts,{annotations:P,annCounts:Ue,isSent:mt,onSendAll:pt,onSendSingle:Fe,onDelete:Fn}),p&&a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await pt(),p()},title:"Send annotations & close file",children:"×"})]})]}),a.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[v?a.jsx("textarea",{ref:W,className:"plan-edit-textarea",style:{fontSize:`${g}px`},value:T,onChange:m=>L(m.target.value),onKeyDown:m=>{if(m.key==="s"&&(m.ctrlKey||m.metaKey)){m.preventDefault(),U();return}if(m.key==="Escape"){m.preventDefault(),V();return}},spellCheck:!1}):a.jsxs("div",{ref:ie,className:`plan-anno-content md-preview${ae!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${g}px`,minWidth:0},onMouseUp:m=>{$e.current={x:m.clientX,y:m.clientY,time:Date.now()},oe()},onDoubleClick:m=>{u||m.target.closest("textarea, button, .plan-annotation-card, .plan-insert-btn, .plan-selection-float")||q()},children:[!u&&a.jsx(an,{index:-1,active:ae===-1,additions:Rt.get(-1),onOpen:()=>{Te(-1),ce("")},onSubmit:()=>Ne(-1),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?m=>Fe(m,"add"):void 0,isSent:mt,insertText:xe,setInsertText:ce,textareaRef:ae===-1?he:void 0,expanded:f,alwaysShow:J.length===0,fontSize:g}),J.map((m,x)=>{const M=bs(m);return a.jsxs("div",{children:[a.jsx("div",{"data-token-index":x,id:D.get(x),className:Bn.has(x)?"plan-block--deleted":Pn.has(x)?"plan-block--replaced":Wn.has(x)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:M}}),P.deletions.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"del",annotation:R,fontSize:g,onEdit:fe,onRemove:se,onSend:l?ee=>Fe(ee,"del"):void 0,isSent:z.current.has(R.id)},R.id)),P.replacements.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"rep",annotation:R,fontSize:g,onEdit:Z,onRemove:K,onSend:l?ee=>Fe(ee,"rep"):void 0,isSent:z.current.has(R.id)},R.id)),P.comments.filter(R=>R.tokenIndices[0]===x).map(R=>a.jsx(yt,{type:"com",annotation:R,fontSize:g,onEdit:we,onRemove:te,onSend:l?ee=>Fe(ee,"com"):void 0,isSent:z.current.has(R.id)},R.id)),X&&X.tokenIndices[0]===x&&a.jsxs("div",{className:X.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[a.jsx("span",{style:{color:X.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:X.type==="replace"?"⇄":"?"}),a.jsx("textarea",{ref:Me,className:"plan-annotation-textarea",value:Ce,onChange:R=>Ee(R.target.value),onKeyDown:R=>{if(R.key==="Enter"&&(R.ctrlKey||R.metaKey)){R.preventDefault(),E();return}if(R.key==="Escape"){R.preventDefault(),E();return}},onBlur:E,placeholder:X.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:at(Ce),style:{fontSize:`${g}px`,flex:1}})]}),!u&&a.jsx(an,{index:x,active:ae===x,additions:Rt.get(x),onOpen:()=>{Te(x),ce("")},onSubmit:()=>Ne(x),onRemoveAddition:Le,onEditAddition:Ye,onSendSingle:l?R=>Fe(R,"add"):void 0,isSent:mt,insertText:xe,setInsertText:ce,textareaRef:ae===x?he:void 0,expanded:f,fontSize:g})]},x)}),!u&&re&&a.jsx(Es,{x:re.x,y:re.y,onDelete:ft,onReplace:()=>y("replace"),onComment:()=>y("comment")})]}),!v&&a.jsx(Ss,{headings:H,scrollRef:ie})]})]})});function an({index:t,active:e,additions:n,onOpen:r,onSubmit:s,onRemoveAddition:i,onEditAddition:l,onSendSingle:d,isSent:p,insertText:c,setInsertText:f,textareaRef:u,expanded:h,alwaysShow:g,fontSize:b=14}){const[j,k]=o.useState(null),[C,v]=o.useState(""),I=o.useRef(null),T=Tt(),L=Tt();o.useEffect(()=>{j&&(T.clearUndo(),requestAnimationFrame(()=>{const N=I.current;N&&(N.focus(),N.selectionStart=N.selectionEnd=N.value.length)}))},[j]),o.useEffect(()=>{e&&L.clearUndo()},[e]);const $=o.useCallback(N=>{v(S=>(T.pushUndo(S),N))},[T]),O=o.useCallback(N=>{L.pushUndo(c),f(N)},[c,f,L]),W=o.useCallback(N=>{k(N.id),v(N.content)},[]),B=o.useCallback(()=>{if(!j)return;const N=C.trim();N?l(j,N):i(j),k(null),v("")},[j,C,l,i]),F=o.useCallback(()=>{k(null),v("")},[]);return a.jsxs("div",{className:`plan-insert-zone${g?" plan-insert-zone--empty":""}`,"data-zone-index":t,children:[n==null?void 0:n.map(N=>a.jsx("div",{className:"plan-annotation-card",children:j===N.id?a.jsx("textarea",{ref:I,className:"plan-annotation-textarea",value:C,onChange:S=>$(S.target.value),onKeyDown:S=>{if(S.key==="Enter"&&(S.ctrlKey||S.metaKey)){S.preventDefault(),B();return}if(S.key==="Escape"){S.preventDefault(),F();return}if(S.key==="Tab"){Ct(S,$);return}},onBlur:B,rows:at(C),style:{fontSize:`${b}px`,flex:1,...h?{minWidth:300}:void 0}}):a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{flex:1,fontSize:`${b}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>W(N),title:"Double-click to edit",children:N.content}),d&&(()=>{const S=(p==null?void 0:p(N.id))??!1;return a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!S&&d(N.id),disabled:S,title:S?"Already sent":"Send to terminal",style:S?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>W(N),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>i(N.id),children:"×"})]})},N.id)),e?a.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:a.jsx("textarea",{ref:u,className:"plan-annotation-textarea",value:c,onChange:N=>O(N.target.value),onKeyDown:N=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)){N.preventDefault(),s();return}if(N.key==="Escape"){N.preventDefault(),s();return}if(N.key==="Tab"){Ct(N,O);return}},onBlur:s,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:at(c),style:{fontSize:`${b}px`,...h?{minWidth:300}:void 0}})}):g&&!(n!=null&&n.length)?a.jsx("div",{className:"plan-empty-placeholder",onDoubleClick:r,title:"Double-click or Ctrl+Enter to edit",children:"Write down your plans here. Double-click or Ctrl+Enter to edit."}):a.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function Re(t,e,n){const r=n?{path:n}:void 0;return pe.get(t,e,"files",r)}function Is(t,e,n,r){return new Promise((s,i)=>{const l=new FormData;for(const p of n)l.append("files",p);const d=new XMLHttpRequest;d.open("POST",`${De}/api/sessions/${encodeURIComponent(e)}/upload`),d.setRequestHeader("Authorization",`Bearer ${t}`),d.upload.addEventListener("progress",p=>{p.lengthComputable&&r&&r(Math.round(p.loaded/p.total*100))}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?s():i(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>i(new Error("Upload network error"))),d.addEventListener("abort",()=>i(new Error("Upload aborted"))),d.send(l)})}async function ln(t,e){return(await pe.get(t,e,"cwd")).cwd}async function Rs(t,e,n){return pe.post(t,e,"touch",{name:n})}async function Ns(t,e,n){return pe.post(t,e,"mkdir",{path:n})}async function Ls(t,e,n){return pe.del(t,e,"rm",{path:n})}async function Ds(t,e){const n=await pe.getBlob(t,e,"download-cwd"),r=await n.blob(),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s;const l=n.headers.get("Content-Disposition"),d=l==null?void 0:l.match(/filename="(.+)"/);i.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(s)}async function Ms(t,e,n){const s=await(await pe.getBlob(t,e,"download",{path:n})).blob(),i=URL.createObjectURL(s),l=document.createElement("a");l.href=i,l.download=n.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}function Mn(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function As(t,e){if(e==="directory")return"📁";const n=t.slice(t.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function An(t){const e=new Date(t*1e3),n=r=>String(r).padStart(2,"0");return`${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}`}function zs({sessionId:t,token:e,planDir:n,selectedFile:r,onSelectFile:s,onCreateFile:i,onDeleteFile:l}){const[d,p]=o.useState([]),[c,f]=o.useState(!0),[u,h]=o.useState(""),[g,b]=o.useState(!1),j=o.useRef(null),[k,C]=o.useState(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n))return w}return n});o.useEffect(()=>{if(r&&r.startsWith(n+"/")){const w=r.substring(0,r.lastIndexOf("/"));if(w.startsWith(n)){C(w);return}}C(n)},[r,n]);const v=o.useCallback(async()=>{if(!(!e||!k)){f(!0);try{const q=(await Re(e,t,k)).files.filter(V=>V.type==="file"&&(V.name.toLowerCase().endsWith(".md")||V.name===".index.json")||V.type==="directory").sort((V,U)=>{const J=V.type==="file"&&V.name===".index.json",_=U.type==="file"&&U.name===".index.json";return J&&!_?-1:!J&&_?1:V.type==="directory"&&U.type!=="directory"?-1:V.type!=="directory"&&U.type==="directory"?1:V.name.localeCompare(U.name)});p(q)}catch{p([])}finally{f(!1)}}},[e,t,k]);o.useEffect(()=>{v()},[v]),o.useEffect(()=>{const w=setInterval(v,5e3);return()=>clearInterval(w)},[v]);const I=o.useCallback(()=>{const w=n.substring(0,n.lastIndexOf("/")+1);return k.startsWith(w)?k.substring(w.length):k},[n,k]),T=o.useCallback(async()=>{const w=u.trim();if(!w)return;const q=w.endsWith(".md")?w:`${w}.md`;b(!0);try{const V=await Rs(e,t,`${I()}/${q}`);V.ok&&(h(""),await v(),i(V.path))}catch{}finally{b(!1)}},[u,e,t,I,v,i]),L=o.useCallback(async()=>{const w=u.trim().replace(/\/+$/,"");if(w){b(!0);try{await Ns(e,t,`${I()}/${w}`),h(""),await v()}catch{}finally{b(!1)}}},[u,e,t,I,v]),$=o.useCallback(async w=>{const q=`${k}/${w.name}`,V=w.type==="directory"?`folder "${w.name}" and all its contents`:`"${w.name}"`;if(window.confirm(`Delete ${V}?`))try{await Ls(e,t,q),l==null||l(q),await v()}catch{}},[e,t,k,v,l]),O=o.useCallback(w=>{C(q=>`${q}/${w}`)},[]),W=o.useCallback(()=>{k!==n&&C(w=>w.substring(0,w.lastIndexOf("/")))},[k,n]),B=n.split("/").pop()||"AiTasks",F=(()=>{const w=n.split("/");return w.length>=2?w[w.length-2]+"/":""})(),N=k===n?F+B+"/":F+B+"/"+k.substring(n.length+1)+"/",S=r?r.split("/").pop():null;return a.jsxs("div",{className:"plan-file-browser",children:[a.jsxs("div",{className:"plan-file-browser__header",children:[a.jsx("span",{className:"plan-file-browser__title",title:N,children:N}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:v,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),a.jsxs("div",{className:"plan-file-browser__create",children:[a.jsx("input",{ref:j,className:"plan-file-browser__input",value:u,onChange:w=>h(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),T())},placeholder:"name",disabled:g}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:T,disabled:g||!u.trim(),title:"Create new .md file",style:u.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),a.jsx("button",{className:"pane-btn pane-btn--sm",onClick:L,disabled:g||!u.trim(),title:"Create new folder",style:u.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),a.jsxs("div",{className:"plan-file-browser__list",children:[c&&d.length===0&&a.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!c&&d.length===0&&a.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),k!==n&&a.jsxs("div",{className:"plan-file-browser__item",onClick:W,title:"Go up to parent directory",style:{cursor:"pointer"},children:[a.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),a.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(w=>{const q=`${k}/${w.name}`,V=w.type==="file"&&w.name===S,U=w.type==="directory";return a.jsxs("div",{className:`plan-file-browser__item${V?" plan-file-browser__item--active":""}`,onClick:()=>U?O(w.name):s(q),title:U?`Open folder ${w.name}`:w.name,style:{cursor:"pointer"},children:[a.jsx("span",{className:"plan-file-browser__icon",children:U?"📁":w.name===".index.json"?"🔒":"□"}),a.jsxs("span",{className:"plan-file-browser__name",children:[w.name,U?"/":""]}),!U&&a.jsx("span",{className:"plan-file-browser__size",children:Mn(w.size)}),!w.name.startsWith(".")&&a.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:J=>{J.stopPropagation(),$(w)},title:`Delete ${w.name}`,children:"×"})]},w.name)})]})]})}const vt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},$s=200;function _s(){const[t,e]=o.useState(vt),n=o.useRef("lines"),r=o.useRef([]),s=o.useRef(""),i=o.useRef(""),l=o.useRef([]),d=o.useRef(0),p=o.useRef(0),c=o.useRef(null),f=o.useRef(null),u=o.useCallback(()=>{const C=n.current;e(v=>({...v,receivedBytes:d.current,...C==="lines"?{lines:[...r.current]}:{},...C==="content"?{content:i.current}:{}}))},[]),h=o.useCallback(()=>{c.current===null&&(c.current=window.setTimeout(()=>{c.current=null,u()},$s))},[u]),g=o.useCallback(C=>{n.current=C,r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=new TextDecoder,c.current!==null&&(clearTimeout(c.current),c.current=null),e({...vt,mode:C,status:"streaming"})},[]),b=o.useCallback(C=>{d.current+=C.length;const v=n.current;if(v==="lines"){const T=f.current.decode(C,{stream:!0}).split(`
|
|
30
|
-
`);T[0]=s.current+T[0],s.current=T.pop(),T.length>0&&r.current.push(...T)}else if(v==="content"){const I=f.current.decode(C,{stream:!0});i.current+=I}else l.current.push(new Uint8Array(C));h()},[h]),j=o.useCallback(C=>{switch(C.type){case"file-stream-start":p.current=C.size,e(v=>({...v,totalSize:C.size,mtime:C.mtime}));break;case"file-stream-end":{c.current!==null&&(clearTimeout(c.current),c.current=null);const v=n.current;let I=r.current,T=i.current,L=null;if(v==="lines"){const $=f.current.decode(),O=s.current+$;O&&(I=[...I,O],r.current=I),s.current=""}else if(v==="content"){const $=f.current.decode();T=i.current+$,i.current=T}else{const $=l.current.reduce((W,B)=>W+B.length,0);L=new Uint8Array($);let O=0;for(const W of l.current)L.set(W,O),O+=W.length;l.current=[]}e({status:"complete",mode:v,lines:v==="lines"?[...I]:[],content:v==="content"?T:"",buffer:v==="binary"?L:null,totalSize:p.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":c.current!==null&&(clearTimeout(c.current),c.current=null),e(v=>({...v,status:"error",error:C.error}));break}},[]),k=o.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),r.current=[],s.current="",i.current="",l.current=[],d.current=0,p.current=0,f.current=null,e(vt)},[]);return{state:t,startStream:g,handleChunk:b,handleControl:j,reset:k}}function cn({label:t,percent:e}){return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:t}),e!=null&&a.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[a.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:a.jsx("div",{style:{height:"100%",width:`${e}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),a.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[e,"%"]})]})]})}function Os({sessionId:t,token:e,connected:n,onRequestFileStream:r,onSendToTerminal:s}){const i=_s(),[l,d]=o.useState(!1),[p,c]=o.useState(null),[f,u]=o.useState(null),[h,g]=o.useState(""),[b,j]=o.useState(!1),[k,C]=o.useState(!1),v=o.useRef(null),I="plan-selected-file",T=o.useRef(void 0);o.useEffect(()=>{if(f)return clearTimeout(T.current),T.current=setTimeout(()=>{try{localStorage.setItem(I,f)}catch{}},50),()=>clearTimeout(T.current)},[f]);const L=o.useRef(null);o.useEffect(()=>{L.current=null;let D=!1;return j(!0),C(!1),(async()=>{let z="";try{const Q=await Re(e,t);if(D)return;if(z=Q.home||"",Q.files.find(G=>G.name==="AiTasks"&&G.type==="directory")){const G=Q.cwd+"/AiTasks";c(G);const be=localStorage.getItem(I);be&&be.startsWith(G+"/")&&u(be)}else c(null),u(null),C(!0)}catch{c(null)}finally{D||j(!1)}try{if(D)return;if(z){const Q=`${z}/.claude/plugins/installed_plugins.json`,P=await sn(e,t,Q,0);if(!D&&P)try{const G=JSON.parse(P.content);"ai-cli-task@moonview"in(G.plugins||G)||d(!0)}catch{d(!0)}}}catch{}})(),()=>{D=!0}},[t,e]),o.useEffect(()=>{if(!k||!n)return;const D=setInterval(async()=>{try{const z=await Re(e,t);if(z.files.find(P=>P.name==="AiTasks"&&P.type==="directory")){const P=z.cwd+"/AiTasks";c(P),C(!1);const G=localStorage.getItem(I);G&&G.startsWith(P+"/")&&u(G)}}catch{}},3e3);return()=>clearInterval(D)},[k,n,e,t,I]),o.useEffect(()=>(Wr(t,i.handleChunk,i.handleControl),()=>Ur(t)),[t,i.handleChunk,i.handleControl]),o.useEffect(()=>{!f||!n||L.current===f&&h||(L.current=f,i.reset(),i.startStream("content"),r==null||r(f))},[f,n]);const $=o.useRef(0);o.useEffect(()=>{i.state.status==="complete"&&f&&(g(i.state.content),$.current=Date.now())},[i.state.status,i.state.content,f]),o.useEffect(()=>{if(!f||!n||!h)return;const D=setInterval(async()=>{if($.current)try{const z=await sn(e,t,f,$.current);z&&(g(z.content),$.current=z.mtime)}catch{}},3e3);return()=>clearInterval(D)},[f,n,h,e,t]);const O=o.useRef(new Map),W=o.useCallback(()=>{var z,Q;if(!f)return;const D=((Q=(z=v.current)==null?void 0:z.getScrollTop)==null?void 0:Q.call(z))??0;D>0&&O.current.set(f,D)},[f]);o.useEffect(()=>{if(!f||!h)return;const D=O.current.get(f);D!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var z,Q;(Q=(z=v.current)==null?void 0:z.setScrollTop)==null||Q.call(z,D)})})},[f,h]);const B=o.useCallback(D=>{D!==f&&(W(),u(D),g(""),L.current=null)},[f,W]),F=o.useCallback(D=>{f&&(f===D||f.startsWith(D+"/"))&&(u(null),g(""),L.current=null)},[f]),N=o.useCallback(D=>{u(D),g(""),L.current=null},[]),S=o.useCallback(D=>{D&&(s==null||s(D))},[s]),w=o.useCallback((D,z)=>{g(D),$.current=z},[]),q=o.useCallback(()=>{W(),u(null),g(""),L.current=null},[W]),V=o.useCallback(()=>{!f||!n||(L.current=null,g(""),i.reset(),i.startStream("content"),r==null||r(f),L.current=f)},[f,n,i,r]),[U,J]=o.useState(()=>{const D=localStorage.getItem(`plan-fb-width-${t}`);if(D){const z=Number(D);if(Number.isFinite(z)&&z>=60&&z<=300)return z}return 130}),_=o.useRef(U);if(U!==_.current){_.current=U;try{localStorage.setItem(`plan-fb-width-${t}`,String(Math.round(U)))}catch{}}const H=o.useCallback(D=>{D.preventDefault();const z=D.clientX,Q=U;document.body.classList.add("resizing-panes");const P=be=>{const je=be.clientX-z;J(Math.min(300,Math.max(60,Q+je)))},G=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",G)};document.addEventListener("mousemove",P),document.addEventListener("mouseup",G)},[U]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[l&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",fontSize:12,flexShrink:0},children:[a.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),a.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{s&&s("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),d(!1)},children:"Install"}),a.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>d(!1),children:"×"})]}),a.jsxs("div",{className:"plan-overlay-body",children:[p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{width:U,flexShrink:0,overflow:"hidden"},children:a.jsx(zs,{sessionId:t,token:e,planDir:p,selectedFile:f,onSelectFile:B,onCreateFile:N,onDeleteFile:F})}),a.jsx("div",{onMouseDown:H,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:D=>{D.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:D=>{D.currentTarget.style.backgroundColor="var(--border)"}})]}),a.jsx("div",{className:"plan-overlay-center",children:b?a.jsx(cn,{label:"Loading AiTasks/..."}):k?a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),a.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",a.jsx("code",{style:{color:"var(--accent-blue)",backgroundColor:"var(--bg-secondary)",padding:"2px 6px",borderRadius:3},children:"/ai-cli-task:init <name>"})," in the terminal to create a task"]})]}):f&&!h&&(i.state.status==="streaming"||i.state.status==="idle")?a.jsx(cn,{label:`Loading ${f.split("/").pop()}...`,percent:i.state.totalSize>0?Math.round(i.state.receivedBytes/i.state.totalSize*100):void 0}):f?a.jsx(js,{ref:v,markdown:h,filePath:f,sessionId:t,token:e,onExecute:S,onSend:s,onRefresh:V,onClose:q,onContentSaved:w,readOnly:f.endsWith("/.index.json")}):a.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]})]})}async function Fs(t,e){try{return(await pe.get(t,e,"draft")).content??""}catch{return""}}async function dn(t,e,n){try{await pe.put(t,e,"draft",{content:n})}catch{}}const It="chat-history",un=50;function zn(){try{const t=localStorage.getItem(It);return t?JSON.parse(t):[]}catch{return[]}}function Bs(t){const n=zn().filter(r=>r.text!==t);n.unshift({text:t,ts:Date.now()}),n.length>un&&(n.length=un),localStorage.setItem(It,JSON.stringify(n))}const fn=[{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:"/ai-cli-task:ai-cli-task",desc:"Task lifecycle management (8 skills)"},{cmd:"/ai-cli-task:init",desc:"Initialize task module + branch"},{cmd:"/ai-cli-task:plan",desc:"Generate plan or process annotations"},{cmd:"/ai-cli-task:check",desc:"Check feasibility (post-plan/mid/post-exec)"},{cmd:"/ai-cli-task:exec",desc:"Execute implementation plan"},{cmd:"/ai-cli-task:merge",desc:"Merge task branch to main"},{cmd:"/ai-cli-task:report",desc:"Generate completion report"},{cmd:"/ai-cli-task:auto",desc:"Autonomous full lifecycle loop"},{cmd:"/ai-cli-task:cancel",desc:"Cancel task + optional cleanup"}],Ps=o.forwardRef(function({onSend:e,onContentChange:n,sessionId:r,token:s},i){const l=A(y=>y.fontSize),[d,p]=o.useState(""),c=o.useRef(null),f=o.useRef(void 0),u=o.useRef(!1),h=o.useRef(!1),{pushUndo:g,popUndo:b}=Tt(),j=o.useRef(d);j.current=d;const k=o.useCallback(()=>g(j.current),[g]),[C,v]=o.useState(!1),[I,T]=o.useState(""),[L,$]=o.useState(0),[O,W]=o.useState(!1),[B,F]=o.useState([]),[N,S]=o.useState(0),[w,q]=o.useState(""),V=o.useRef(null),U=o.useMemo(()=>{if(!w)return B;const y=w.toLowerCase();return B.filter(E=>E.text.toLowerCase().includes(y))},[B,w]),[J,_]=o.useState(!1),[H,D]=o.useState(""),[z,Q]=o.useState(""),[P,G]=o.useState(0),[be,je]=o.useState([]),[Ue,ae]=o.useState(!1),Te=o.useRef(""),xe=o.useRef(null),ce=o.useMemo(()=>{if(!I)return fn;const y=I.toLowerCase();return fn.filter(E=>E.cmd.toLowerCase().includes(y)||E.desc.toLowerCase().includes(y))},[I]),he=o.useMemo(()=>{let y=be;if(H){const E=H.toLowerCase();y=y.filter(K=>K.name.toLowerCase().includes(E))}return[...y].sort((E,K)=>E.type==="directory"&&K.type!=="directory"?-1:E.type!=="directory"&&K.type==="directory"?1:E.name.localeCompare(K.name))},[be,H]),X=A(y=>y.latency),ye=`chat-draft-${r}`,Ce=o.useRef(!1),Ee=o.useRef(void 0);o.useEffect(()=>{try{const E=localStorage.getItem(ye);E&&!h.current&&p(E)}catch{}let y=!1;return Fs(s,r).then(E=>{if(y||h.current){u.current=!0;return}if(E){p(E);try{localStorage.setItem(ye,E)}catch{}}u.current=!0}).catch(()=>{u.current=!0}),()=>{y=!0}},[s,r,ye]),o.useEffect(()=>{if(!u.current)return;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{try{localStorage.setItem(ye,d)}catch{}},50),Ee.current&&clearTimeout(Ee.current);const y=Math.max(200,(X??30)*3);return Ee.current=setTimeout(()=>{Ce.current||(Ce.current=!0,dn(s,r,d).catch(()=>{}).finally(()=>{Ce.current=!1}))},y),()=>{f.current&&clearTimeout(f.current),Ee.current&&clearTimeout(Ee.current)}},[d,s,r,X,ye]),o.useEffect(()=>{var y;(y=c.current)==null||y.focus()},[]),o.useEffect(()=>{if(!J)return;let y=!1;return ae(!0),(async()=>{try{if(z){if(!Te.current){const Z=await Re(s,r);if(y)return;Te.current=Z.cwd}const E=`${Te.current}/${z.replace(/\/$/,"")}`,K=await Re(s,r,E);if(y)return;je(K.files)}else{const E=await Re(s,r);if(y)return;Te.current=E.cwd,je(E.files)}ae(!1)}catch{if(y)return;je([]),ae(!1)}})(),()=>{y=!0}},[J,z,s,r]),o.useEffect(()=>{if(!J||!xe.current)return;const y=xe.current.querySelector(".file-item--active");y==null||y.scrollIntoView({block:"nearest"})},[P,J]);const Me=o.useCallback(()=>{const y=j.current.trim();if(y){Bs(y),e(y),p("");try{localStorage.removeItem(ye)}catch{}dn(s,r,"").catch(()=>{})}},[e,s,r,ye]),re=o.useCallback(y=>{k(),p(y),h.current=!0},[k]),ve=o.useCallback(y=>{const E=c.current;k();const K=j.current;if(E){const Z=E.selectionStart,te=E.selectionEnd,we=K.slice(0,Z)+y+K.slice(te);p(we);const se=Z+y.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=se,E.focus()})}else p(K+y)},[k]);o.useImperativeHandle(i,()=>({send:Me,fillContent:re,insertAtCursor:ve}),[Me,re,ve]),o.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const ie=o.useCallback(()=>{const y=c.current;if(!y)return;const{selectionStart:E,selectionEnd:K}=y;if(E!==K){const Z=y.value.substring(E,K);Z&&navigator.clipboard.writeText(Z).catch(()=>{})}},[]),He=o.useCallback(()=>{const y=zn();v(!1),T("");const E=c.current;if(E){const K=E.selectionStart,Z=d.slice(0,K),te=d.slice(K),we=Z.match(/(?:^|\s)(\/history)\s*$/);if(we){const se=Z.length-we[1].length;p(d.slice(0,se)+te)}}y.length!==0&&(F(y),S(0),q(""),W(!0))},[d]),$e=o.useCallback(y=>{k(),p(y.text),W(!1),requestAnimationFrame(()=>{const E=c.current;E&&(E.selectionStart=E.selectionEnd=y.text.length,E.focus())})},[k]),_e=o.useCallback(y=>{const E=U[y];if(!E)return;const K=B.filter(te=>te.ts!==E.ts||te.text!==E.text);F(K),localStorage.setItem(It,JSON.stringify(K));const Z=w?K.filter(te=>te.text.toLowerCase().includes(w.toLowerCase())):K;N>=Z.length&&S(Math.max(0,Z.length-1))},[U,B,N,w]);o.useEffect(()=>{if(!O||!V.current)return;const y=V.current.querySelector(".history-item--active");y==null||y.scrollIntoView({block:"nearest"})},[N,O]);const Ne=o.useCallback(y=>{if(y==="/history"){He();return}const E=c.current;if(!E)return;k();const K=E.selectionStart,Z=d.slice(0,K),te=d.slice(K),se=Z.lastIndexOf(`
|
|
31
|
-
`)+1,de=Z.slice(se).match(/\/[a-zA-Z:-]*$/);if(de){const oe=se+(de.index??0),ge=y+" ",Ke=d.slice(0,oe)+ge+te;p(Ke);const Oe=oe+ge.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=Oe,E.focus()})}else{const oe=Z+y+te;p(oe);const ge=K+y.length;requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=ge,E.focus()})}v(!1),T(""),$(0)},[d,k,He]),Le=o.useCallback(y=>{const E=c.current;if(!E)return;k();const K=E.selectionStart,Z=d.slice(0,K),te=d.slice(K),we=Z.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!we)return;const se=Z.length-we[0].length;if(y.type==="directory"){const fe="@"+z+y.name+"/",de=d.slice(0,se)+fe+te;p(de);const oe=se+fe.length;Q(z+y.name+"/"),D(""),G(0),requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=oe,E.focus()})}else{const fe=y.name+" ",de=d.slice(0,se)+fe+te;p(de);const oe=se+fe.length;_(!1),D(""),Q(""),G(0),je([]),Te.current="",requestAnimationFrame(()=>{E.selectionStart=E.selectionEnd=oe,E.focus()})}},[d,z,k]),Ye=o.useCallback(y=>{const E=y.target.value;if(p(E),O){const fe=E.trim();fe?(q(fe),S(0)):q("");return}const K=y.target.selectionStart,Z=E.slice(0,K),te=Z.lastIndexOf(`
|
|
32
|
-
`),se=Z.slice(te+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(se)v(!0),T(se[1]),$(0),_(!1);else{v(!1);const fe=Z.match(/@([a-zA-Z0-9_.\-/]*)$/);if(fe){const de=fe[1],oe=de.lastIndexOf("/"),ge=oe>=0?de.slice(0,oe+1):"",Ke=oe>=0?de.slice(oe+1):de;D(Ke),G(0),Q(ge),_(!0)}else _(!1)}},[O]),ft=o.useCallback(y=>{if(C&&ce.length>0){if(y.key==="ArrowDown"){y.preventDefault(),$(E=>(E+1)%ce.length);return}if(y.key==="ArrowUp"){y.preventDefault(),$(E=>(E-1+ce.length)%ce.length);return}if(y.key==="Enter"||y.key==="Tab"){y.preventDefault(),Ne(ce[L].cmd);return}if(y.key==="Escape"){y.preventDefault(),v(!1);return}}if(J&&he.length>0){if(y.key==="ArrowDown"){y.preventDefault(),G(E=>(E+1)%he.length);return}if(y.key==="ArrowUp"){y.preventDefault(),G(E=>(E-1+he.length)%he.length);return}if(y.key==="Tab"||y.key==="Enter"){y.preventDefault(),Le(he[P]);return}if(y.key==="Escape"){y.preventDefault(),_(!1);return}}if(O&&U.length>0){if(y.key==="ArrowDown"){y.preventDefault(),S(E=>(E+1)%U.length);return}if(y.key==="ArrowUp"){y.preventDefault(),S(E=>(E-1+U.length)%U.length);return}if(y.key==="Enter"){y.preventDefault(),$e(U[N]);return}if(y.key==="Delete"||y.key==="Backspace"&&(y.ctrlKey||y.metaKey)){y.preventDefault(),_e(N);return}if(y.key==="Escape"){y.preventDefault(),W(!1);return}}if(y.key==="Tab"){Ct(y,p,g);return}y.key==="Enter"&&(y.ctrlKey||y.metaKey)&&(y.preventDefault(),Me())},[Me,C,ce,L,Ne,J,he,P,Le,g,b,O,U,N,$e,_e]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[C&&ce.length>0&&a.jsx("div",{className:"slash-dropdown",children:ce.map((y,E)=>a.jsxs("div",{className:`slash-item${E===L?" slash-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Ne(y.cmd)},onMouseEnter:()=>$(E),children:[a.jsx("span",{className:"slash-cmd",children:y.cmd}),a.jsx("span",{className:"slash-desc",children:y.desc})]},y.cmd))}),J&&(Ue||he.length>0)&&a.jsx("div",{className:"file-dropdown",ref:xe,children:Ue?a.jsx("div",{className:"file-item file-loading",children:"Loading..."}):he.map((y,E)=>a.jsxs("div",{className:`file-item${E===P?" file-item--active":""}`,onMouseDown:K=>{K.preventDefault(),Le(y)},onMouseEnter:()=>G(E),children:[a.jsx("span",{className:"file-icon",children:y.type==="directory"?"📁":"📄"}),a.jsx("span",{className:"file-name",children:y.name})]},y.name))}),O&&a.jsx("div",{className:"history-dropdown",ref:V,children:U.length===0?a.jsx("div",{className:"history-item history-empty",children:"No history yet"}):U.map((y,E)=>a.jsxs("div",{className:`history-item${E===N?" history-item--active":""}`,onMouseDown:K=>{K.preventDefault(),$e(y)},onMouseEnter:()=>S(E),children:[a.jsx("span",{className:"history-text",children:y.text.length>120?y.text.slice(0,120)+"...":y.text}),a.jsx("span",{className:"history-time",children:new Date(y.ts).toLocaleString()}),a.jsx("button",{className:"history-delete",onMouseDown:K=>{K.preventDefault(),K.stopPropagation(),_e(E)},title:"Delete (Del key)",children:"×"})]},`${y.ts}-${E}`))}),a.jsx("textarea",{ref:c,className:"md-editor-textarea",value:d,onChange:Ye,onKeyDown:ft,onMouseUp:ie,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${l}px`}})]})});function Ws({token:t,sessionId:e,onClose:n}){const[r,s]=o.useState([]),[i,l]=o.useState(""),[d,p]=o.useState([]),[c,f]=o.useState(!0),[u,h]=o.useState(!1),g=o.useRef(null);o.useEffect(()=>{let v=!1;return(async()=>{try{const I=await Re(t,e);v||(l(I.cwd),s(I.files))}catch{v||n()}finally{v||f(!1)}})(),()=>{v=!0}},[t,e,n]),o.useEffect(()=>{const v=L=>{L.key==="Escape"&&n()},I=L=>{g.current&&!g.current.contains(L.target)&&n()};document.addEventListener("keydown",v);const T=setTimeout(()=>document.addEventListener("mousedown",I),50);return()=>{document.removeEventListener("keydown",v),document.removeEventListener("mousedown",I),clearTimeout(T)}},[n]);const b=o.useCallback(async v=>{f(!0);try{const I=await Re(t,e,v);p(T=>[...T,i]),l(v),s(I.files)}catch{}finally{f(!1)}},[t,e,i]),j=o.useCallback(async()=>{if(d.length===0)return;const v=d[d.length-1];f(!0);try{const I=await Re(t,e,v);p(T=>T.slice(0,-1)),l(v),s(I.files)}catch{}finally{f(!1)}},[t,e,d]),k=o.useCallback(async v=>{try{await Ms(t,e,v)}catch(I){alert(`Download failed: ${I instanceof Error?I.message:"Unknown error"}`)}},[t,e]),C=o.useCallback(async()=>{h(!0),n();try{await Ds(t,e)}catch(v){alert(`Download failed: ${v instanceof Error?v.message:"Unknown error"}`)}finally{h(!1)}},[t,e,n]);return a.jsxs("div",{ref:g,style:{position:"absolute",top:"100%",right:0,marginTop:4,width:300,maxHeight:360,backgroundColor:"var(--bg-primary)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:100,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",flexShrink:0},children:[d.length>0&&a.jsx("button",{className:"pane-btn",onClick:j,disabled:c,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),a.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:i.split("/").slice(-2).join("/")||i}),a.jsx("button",{className:"pane-btn",onClick:n,style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),a.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:c?a.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?a.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(v=>a.jsxs("div",{onClick:()=>{const I=i+"/"+v.name;v.type==="directory"?b(I):k(I)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[a.jsx("span",{style:{flexShrink:0,fontSize:13},children:v.type==="directory"?"📁":As(v.name,v.type)}),a.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.type==="directory"?a.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):v.size!=null?a.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:Mn(v.size)}):null]},v.name))}),a.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:a.jsx("button",{className:"pane-btn",onClick:C,disabled:u,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:u?"Downloading...":"Download All (tar.gz)"})})]})}function pn(t,e,{containerRef:n,axis:r,offset:s=0,min:i,max:l,invert:d=!1,bodyClass:p}){const[c,f]=o.useState(()=>{const g=localStorage.getItem(t);if(g){const b=Number(g);if(Number.isFinite(b)&&b>=i&&b<=l)return b}return e}),u=o.useRef(c);if(c!==u.current){u.current=c;try{localStorage.setItem(t,String(Math.round(c)))}catch{}}const h=o.useCallback(g=>{g.preventDefault();const b=n.current;if(!b)return;const j=b.getBoundingClientRect(),k=r==="x"?j.width:j.height-s,C=r==="x"?j.left:j.top+s;document.body.classList.add(p);const v=T=>{let $=((r==="x"?T.clientX:T.clientY)-C)/k*100;d&&($=100-$),f(Math.min(l,Math.max(i,$)))},I=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",I)},[n,r,s,i,l,d,p]);return[c,h]}const Us=600,Pe=typeof window<"u"?window.matchMedia(`(max-width: ${Us-1}px)`):null;function Hs(){const[t,e]=o.useState(()=>(Pe==null?void 0:Pe.matches)??!1);return o.useEffect(()=>{if(!Pe)return;const n=r=>e(r.matches);return Pe.addEventListener("change",n),()=>Pe.removeEventListener("change",n)},[]),t}const Ks=o.memo(function({terminal:e}){const n=Hs(),r=A(_=>_.splitTerminal),s=A(_=>_.token),i=A(_=>_.toggleChat),l=A(_=>_.togglePlan),{chatOpen:d,planOpen:p}=e.panels,c=o.useRef(null),f=o.useRef(null),u=o.useRef(null),h=o.useRef(null),g=o.useRef(null),[b,j]=pn(`plan-width-${e.id}`,50,{containerRef:f,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[k,C]=pn(`doc-height-${e.id}`,35,{containerRef:c,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[v,I]=o.useState("");o.useEffect(()=>{if(!s||!e.connected)return;let _=!1;const H=async()=>{try{const z=await ln(s,e.id);_||I(z)}catch{}};H();const D=setInterval(H,5e3);return()=>{_=!0,clearInterval(D)}},[s,e.id,e.connected]);const T=o.useCallback(async _=>{let H;if(s)try{H=await ln(s,e.id)}catch{}r(e.id,_,H)},[s,e.id,r]),[L,$]=o.useState(!1),[O,W]=o.useState(0),[B,F]=o.useState(!1),[N,S]=o.useState(!1),w=async _=>{const H=_.target.files;if(!(!H||H.length===0||!s)){$(!0),W(0);try{await Is(s,e.id,H,D=>{W(D)})}catch(D){alert(`Upload failed: ${D instanceof Error?D.message:"Unknown error"}`)}finally{$(!1),W(0),u.current&&(u.current.value="")}}},q=o.useRef(void 0),V=o.useCallback(_=>{if(h.current){const H=_.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(H),q.current=window.setTimeout(()=>{var D;return(D=h.current)==null?void 0:D.sendInput("\r")},50)}},[]);o.useEffect(()=>()=>{q.current&&clearTimeout(q.current)},[]);const U=o.useCallback(_=>{if(h.current){const H=_.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(H),setTimeout(()=>{var D;return(D=h.current)==null?void 0:D.sendInput("\r")},50)}},[]),J=o.useCallback(()=>S(!1),[]);return a.jsxs("div",{ref:c,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[a.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:e.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),a.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[e.id,e.connected?e.sessionResumed?" (resumed)":"":" (disconnected)"]}),v&&a.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:v,children:v})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[a.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:w}),a.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=u.current)==null?void 0:_.click()},disabled:L,style:L?{color:"var(--accent-yellow)"}:void 0,title:L?`Uploading ${O}%`:"Upload files","aria-label":"Upload files",children:L?`${O}%`:"↑"}),a.jsxs("div",{style:{position:"relative"},children:[a.jsx("button",{className:"pane-btn",onClick:()=>S(!0),title:"Download files","aria-label":"Download files",children:"↓"}),N&&s&&a.jsx(Ws,{token:s,sessionId:e.id,onClose:J})]}),a.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>i(e.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),a.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>l(e.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),a.jsx("button",{className:"pane-btn",onClick:()=>T(n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),a.jsx("button",{className:"pane-btn",onClick:()=>T("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),a.jsxs("div",{ref:f,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{width:`${b}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:a.jsx(Os,{sessionId:e.id,token:s||"",connected:e.connected,onRequestFileStream:_=>{var H;return(H=h.current)==null?void 0:H.requestFileStream(_)},onSendToTerminal:U})}),a.jsx("div",{className:"md-editor-divider-h",onMouseDown:j,style:{width:"3px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:_=>{_.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:_=>{_.currentTarget.style.backgroundColor="var(--border)"}})]}),a.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[a.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[a.jsx(as,{ref:h,sessionId:e.id}),!e.connected&&a.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:a.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"md-editor-divider",onMouseDown:C}),a.jsxs("div",{style:{height:`${k}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 8px",height:"22px",flexShrink:0,backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),a.jsx("button",{className:"pane-btn",onClick:()=>{var _;return(_=g.current)==null?void 0:_.send()},disabled:!B,title:"Send to terminal (Ctrl+Enter)",style:B?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),a.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),a.jsx("div",{style:{flex:1,overflow:"hidden"},children:a.jsx(Ps,{ref:g,onSend:V,onContentChange:F,sessionId:e.id,token:s||""})})]})]})]})]}),e.error&&a.jsx("div",{style:{padding:"2px 8px",backgroundColor:"var(--bg-secondary)",borderTop:"1px solid var(--accent-red)",color:"var(--accent-red)",fontSize:"11px",flexShrink:0},children:e.error})]})});class $n extends o.Component{constructor(){super(...arguments);zt(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?a.jsxs("div",{style:{height:"100%",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"var(--text-bright)",fontFamily:"monospace",padding:"16px"},children:[a.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),a.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textAlign:"center"},children:((n=this.state.error)==null?void 0:n.message)||"An unexpected error occurred"}),a.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-bright)",padding:"4px 12px",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"Retry"})]}):a.jsxs("div",{style:{minHeight:"100vh",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px",color:"var(--text-bright)",fontFamily:"monospace"},children:[a.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),a.jsx("div",{style:{fontSize:"13px",color:"var(--text-secondary)",maxWidth:"500px",textAlign:"center"},children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),a.jsx("button",{onClick:()=>window.location.reload(),style:{background:"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%)",border:"none",color:"var(--bg-primary)",padding:"8px 24px",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:"Reload"})]}):this.props.children}}const Js=4,mn=10;function Vs(){const t=A(s=>s.layout),e=A(s=>s.terminalIds.length),n=A(s=>s.addTerminal);if(!t)return a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:a.jsx("button",{onClick:()=>n(),style:{background:"none",border:"1px dashed var(--border)",color:"var(--text-secondary)",padding:"16px 32px",borderRadius:"8px",cursor:"pointer",fontSize:"14px"},children:"+ Add Terminal"})});const r=e>1;return a.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:a.jsx(_n,{node:t,canClose:r})})}const _n=o.memo(function({node:e,canClose:n}){return e.type==="leaf"?a.jsx(Gs,{terminalId:e.terminalId,canClose:n}):a.jsx(qs,{node:e,canClose:n})}),Gs=o.memo(function({terminalId:e,canClose:n}){const r=A(i=>i.terminalsMap[e]),s=A(i=>i.reconnectTerminal);return r?a.jsx($n,{inline:!0,children:a.jsx(Ks,{terminal:r,canClose:n})}):a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:a.jsxs("button",{onClick:()=>s(e),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",e]})})}),qs=o.memo(function({node:e,canClose:n}){const r=A(c=>c.setSplitSizes),s=o.useRef(null),i=e.direction==="horizontal",l=o.useRef(e.sizes);l.current=e.sizes;const d=o.useCallback((c,f)=>{f.preventDefault();const u=i?"resizing-panes":"resizing-panes-v";document.body.classList.add(u);const h=i?f.clientX:f.clientY,g=[...l.current],b=s.current,j=i?(b==null?void 0:b.clientWidth)||1:(b==null?void 0:b.clientHeight)||1;let k=null;const C=I=>{k||(k=requestAnimationFrame(()=>{k=null;const $=((i?I.clientX:I.clientY)-h)/j*100,O=g[c]+$,W=g[c+1]-$;if(O>=mn&&W>=mn){const B=[...g];B[c]=O,B[c+1]=W,r(e.id,B)}}))},v=()=>{k&&cancelAnimationFrame(k),document.body.classList.remove(u),document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",C),document.addEventListener("mouseup",v)},[i,e.id,r]),p=[];return e.children.forEach((c,f)=>{const u=c.type==="leaf"?c.terminalId:c.id;p.push(a.jsx("div",{style:{flex:`${e.sizes[f]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:a.jsx(_n,{node:c,canClose:n})},u)),f<e.children.length-1&&p.push(a.jsx("div",{onMouseDown:h=>d(f,h),style:{flex:`0 0 ${Js}px`,cursor:i?"col-resize":"row-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="var(--border)"}},`divider-${e.id}-${f}`))}),a.jsx("div",{ref:s,style:{display:"flex",flexDirection:i?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function Ys({tabId:t}){const e=A(S=>S.tabs.find(w=>w.id===t)),n=A(S=>S.activeTabId),r=A(S=>S.switchTab),s=A(S=>S.closeTab),i=A(S=>S.reopenTab),l=A(S=>S.deleteTab),d=A(S=>S.renameTab),p=A(S=>e?e.terminalIds.map(w=>{const q=S.terminalsMap[w];return q?{id:w,connected:q.connected,active:!0}:{id:w,connected:!1,active:!1}}):[]),c=A(S=>S.disconnectTerminal),f=A(S=>S.reconnectTerminal),u=A(S=>S.killServerSession),[h,g]=o.useState(!1),[b,j]=o.useState(""),[k,C]=o.useState(!1),v=o.useRef(null);if(!e)return null;const I=n===t,T=e.status==="open",L=()=>{T&&r(t)},$=S=>{T&&(S.stopPropagation(),j(e.name),g(!0),setTimeout(()=>{var w;return(w=v.current)==null?void 0:w.focus()},0))},O=()=>{const S=b.trim();S&&d(t,S),g(!1)},W=S=>{S.stopPropagation(),i(t)},B=S=>{S.stopPropagation(),s(t)},F=async S=>{S.stopPropagation(),window.confirm(`Delete tab "${e.name}"? This will kill all tmux sessions in this tab.`)&&await l(t)},N=S=>{S.stopPropagation(),C(!k)};return a.jsxs("div",{children:[a.jsxs("div",{onClick:L,style:{padding:"8px 12px",cursor:T?"pointer":"default",borderLeft:I?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:I?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:T?1:.5},onMouseEnter:S=>{T&&!I&&(S.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:S=>{I||(S.currentTarget.style.backgroundColor="transparent")},children:[T&&e.terminalIds.length>0&&a.jsx("button",{onClick:N,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"10px",padding:0,width:14,height:14,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:k?"▼":"▶"}),a.jsxs("div",{style:{flex:1,minWidth:0},children:[h?a.jsx("input",{ref:v,value:b,onChange:S=>j(S.target.value),onBlur:O,onKeyDown:S=>{S.key==="Enter"&&O(),S.key==="Escape"&&g(!1)},style:{width:"100%",background:"var(--bg-primary)",border:"1px solid var(--accent-blue)",color:"var(--text-bright)",borderRadius:"3px",padding:"1px 4px",fontSize:"14px",outline:"none"}}):a.jsx("div",{onDoubleClick:$,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:T?"Double-click to rename":e.name,children:e.name}),a.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[e.terminalIds.length," terminal",e.terminalIds.length!==1?"s":""," · ",An(Math.floor(e.createdAt/1e3))]})]}),T?a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:B,style:{flexShrink:0},title:"Close tab",children:"×"}):a.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[a.jsx("button",{className:"pane-btn",onClick:W,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:F,title:"Delete tab",children:"×"})]})]}),T&&k&&p.length>0&&a.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(S=>a.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${S.connected}`,children:[a.jsx("span",{style:{fontFamily:"monospace"},children:S.id}),a.jsx("span",{style:{marginLeft:"8px",color:S.active?S.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:S.active?S.connected?"●":"◐":"○"}),S.active?a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:w=>{w.stopPropagation(),c(S.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):a.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[a.jsx("button",{className:"pane-btn",onClick:w=>{w.stopPropagation(),f(S.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:w=>{w.stopPropagation(),window.confirm(`Kill terminal "${S.id}"? This will destroy the tmux session.`)&&u(S.id)},title:"Kill session",children:"×"})]})]},S.id))})]})}function Xs({sessionId:t,active:e,createdAt:n}){const r=A(d=>d.addTerminal),s=A(d=>d.killServerSession),i=()=>{r("horizontal",t)},l=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${t}"? This will kill the tmux session.`)&&s(t)};return a.jsxs("div",{onClick:i,style:{padding:"8px 12px",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",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:[a.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),a.jsxs("div",{style:{flex:1,minWidth:0},children:[a.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),a.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:An(n)})]}),a.jsx("button",{className:"pane-btn pane-btn--danger",onClick:l,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function Zs(){const t=A(c=>c.sidebarOpen),e=A(c=>c.toggleSidebar),n=A(c=>c.fetchSessions),r=A(c=>t?c.serverSessions:[]),s=A(c=>t?c.tabs:[]),i=A(c=>c.terminalIds.length),l=A(c=>c.tabsLoading),d=new Set(s.flatMap(c=>c.terminalIds)),p=r.filter(c=>!d.has(c.sessionId));return o.useEffect(()=>{if(!t)return;n();let c=setInterval(n,5e3);const f=()=>{document.hidden?c&&(clearInterval(c),c=null):(n(),c||(c=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",f),()=>{c&&clearInterval(c),document.removeEventListener("visibilitychange",f)}},[t,n]),o.useEffect(()=>{if(!t)return;const c=setTimeout(n,800);return()=>clearTimeout(c)},[i,t,n]),a.jsxs("div",{className:"session-sidebar",style:{width:t?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:t?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[a.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),a.jsx("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),a.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),s.length===0?a.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):s.map(c=>a.jsx(Ys,{tabId:c.id},c.id))]}),!l&&p.length>0&&a.jsxs("div",{style:{marginTop:"16px"},children:[a.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-yellow)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(224, 175, 104, 0.05)",borderBottom:"1px solid var(--border)"},children:"ORPHANED SESSIONS"}),p.map(c=>a.jsx(Xs,{sessionId:c.sessionId,active:c.active,createdAt:c.createdAt},c.sessionId))]})]})]})}const On=jt.memo(()=>{const t=A(T=>T.tabs),e=A(T=>T.activeTabId),n=A(T=>T.addTab),r=A(T=>T.switchTab),s=A(T=>T.closeTab),i=A(T=>T.renameTab),[l,d]=o.useState(null),[p,c]=o.useState(""),f=o.useRef(null),u=t.filter(T=>T.status==="open");o.useEffect(()=>{l&&f.current&&(f.current.focus(),f.current.select())},[l]);const h=T=>{d(T.id),c(T.name)},g=()=>{l&&p.trim()&&i(l,p.trim()),d(null),c("")},b=()=>{d(null),c("")},j=T=>{T.key==="Enter"?g():T.key==="Escape"&&b()},k=T=>{l||r(T)},C=(T,L)=>{T.stopPropagation(),s(L)},v=(T,L)=>{T.button===1&&(T.preventDefault(),s(L))},I=u.length>1;return a.jsxs("div",{className:"tab-bar",children:[u.map(T=>{const L=T.id===e,$=l===T.id,O=T.terminalIds.length;return a.jsx("div",{className:`tab-item ${L?"tab-item--active":""}`,onClick:()=>k(T.id),onDoubleClick:()=>h(T),onMouseDown:W=>v(W,T.id),children:$?a.jsx("input",{ref:f,type:"text",value:p,onChange:W=>c(W.target.value),onBlur:g,onKeyDown:j,className:"tab-item__rename-input"}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"tab-item__name",children:[T.name," ",O>0&&`(${O})`]}),I&&a.jsx("button",{className:"tab-item__close",onClick:W=>C(W,T.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},T.id)}),a.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});On.displayName="TabBar";function Qs(){return localStorage.getItem("ai-cli-online-token")}function eo(){const t=A(f=>f.token),e=A(f=>f.setToken),n=A(f=>f.tabs),r=A(f=>f.addTab),s=A(f=>f.toggleSidebar),i=A(f=>f.fontSize),l=A(f=>f.setFontSize),d=A(f=>f.tabsLoading),p=A(f=>f.theme),c=A(f=>f.toggleTheme);return o.useEffect(()=>{const f=Qs();f&&!t&&e(f)},[]),o.useEffect(()=>{t&&!d&&n.filter(f=>f.status==="open").length===0&&r("Default")},[t,d]),t?a.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[a.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 16px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),a.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.3"]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[a.jsx("button",{className:"header-btn",onClick:()=>l(i-1),disabled:i<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),a.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:i}),a.jsx("button",{className:"header-btn",onClick:()=>l(i+1),disabled:i>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),a.jsx(no,{}),a.jsx("button",{className:"header-btn",onClick:c,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"☀":"🌙"}),a.jsx("button",{className:"header-btn",onClick:s,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),a.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&e(null)},children:"Logout"})]})]}),a.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[a.jsx("main",{style:{flex:1,overflow:"hidden"},children:a.jsx(Vs,{})}),a.jsx(Zs,{})]}),a.jsx(On,{})]}):a.jsx(Pr,{})}const to=[1,2,3,4];function no(){const t=A(r=>r.latency);if(t===null)return a.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let e,n;return t<50?(e="var(--accent-green)",n=4):t<150?(e="var(--accent-yellow)",n=3):t<300?(e="var(--accent-orange)",n=2):(e="var(--accent-red)",n=1),a.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${t}ms`,children:[to.map(r=>a.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?e:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),a.jsxs("span",{style:{fontSize:"10px",color:e,marginLeft:"4px",fontWeight:500},children:[t,"ms"]})]})}St.createRoot(document.getElementById("root")).render(a.jsx(jt.StrictMode,{children:a.jsx($n,{children:a.jsx(eo,{})})}));
|