ai-cli-online 3.0.2 → 3.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -73,12 +73,15 @@ One command triggers the entire lifecycle. A single Claude session runs plan →
73
73
 
74
74
  ```
75
75
  AiTasks/
76
- ├── .index.md # Module listing
77
- ├── .experience/ # Cross-task knowledge base (by domain type)
78
- │ ├── software.md
76
+ ├── .index.json # Module listing
77
+ ├── .experiences/ # Cross-task knowledge base (by domain type)
78
+ │ ├── .summary.md # Experience file index
79
79
  │ └── <type>.md
80
+ ├── .references/ # External reference materials (collected during plan/exec)
81
+ │ ├── .summary.md # Reference file index
82
+ │ └── <topic>.md
80
83
  └── my-feature/
81
- ├── .index.md # Status, phase, timestamps, dependencies (YAML)
84
+ ├── .index.json # Status, phase, timestamps, dependencies (JSON)
82
85
  ├── .target.md # Requirements (human-authored)
83
86
  ├── .summary.md # Condensed context (prevents context overflow)
84
87
  ├── .analysis/ # Evaluation history
@@ -86,12 +89,12 @@ AiTasks/
86
89
  ├── .bugfix/ # Issue history
87
90
  ├── .notes/ # Research findings
88
91
  ├── .report.md # Completion report
89
- └── plan.md # Implementation plan
92
+ └── .plan.md # Implementation plan
90
93
  ```
91
94
 
92
95
  ### Type-Aware Execution
93
96
 
94
- Tasks are classified by domain type (`software`, `dsp`, `ml`, `literary`, `science:physics`, etc.). Each type adapts planning methodology, execution tools, and verification criteria. Completed task lessons are stored in `.experience/<type>.md` and referenced by future tasks of the same type.
97
+ Tasks are classified by domain type (`software`, `dsp`, `ml`, `literary`, `science:physics`, etc.). Each type adapts planning methodology, execution tools, and verification criteria. Completed task lessons are stored in `.experiences/<type>.md` and referenced by future tasks of the same type.
95
98
 
96
99
  ## Terminal Features
97
100
 
package/README.zh-CN.md CHANGED
@@ -73,12 +73,15 @@ init → plan → check → exec → check → merge → report
73
73
 
74
74
  ```
75
75
  AiTasks/
76
- ├── .index.md # 模块索引
77
- ├── .experience/ # 跨任务知识库(按领域类型分类)
78
- │ ├── software.md
76
+ ├── .index.json # 模块索引
77
+ ├── .experiences/ # 跨任务知识库(按领域类型分类)
78
+ │ ├── .summary.md # 经验文件索引
79
79
  │ └── <type>.md
80
+ ├── .references/ # 外部参考资料(执行中收集)
81
+ │ ├── .summary.md # 参考文件索引
82
+ │ └── <topic>.md
80
83
  └── my-feature/
81
- ├── .index.md # 状态、阶段、时间戳、依赖 (YAML)
84
+ ├── .index.json # 状态、阶段、时间戳、依赖 (JSON)
82
85
  ├── .target.md # 需求描述(人工编写)
83
86
  ├── .summary.md # 浓缩上下文(防止上下文溢出)
84
87
  ├── .analysis/ # 评估历史
@@ -86,12 +89,12 @@ AiTasks/
86
89
  ├── .bugfix/ # 问题历史
87
90
  ├── .notes/ # 研究发现
88
91
  ├── .report.md # 完成报告
89
- └── plan.md # 实施计划
92
+ └── .plan.md # 实施计划
90
93
  ```
91
94
 
92
95
  ### 类型感知执行
93
96
 
94
- 任务按领域类型分类(`software`、`dsp`、`ml`、`literary`、`science:physics` 等)。每种类型会调整规划方法、执行工具和验证标准。已完成任务的经验存储在 `.experience/<type>.md` 中,供同类型的后续任务参考。
97
+ 任务按领域类型分类(`software`、`dsp`、`ml`、`literary`、`science:physics` 等)。每种类型会调整规划方法、执行工具和验证标准。已完成任务的经验存储在 `.experiences/<type>.md` 中,供同类型的后续任务参考。
95
98
 
96
99
  ## 终端特性
97
100
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online",
3
- "version": "3.0.2",
3
+ "version": "3.0.5",
4
4
  "description": "AI-Cli Online - Web Terminal for Claude Code via xterm.js + tmux",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -29,8 +29,8 @@ 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
31
  const SESSION_TTL_HOURS = parseInt(process.env.SESSION_TTL_HOURS || '24', 10);
32
- const RATE_LIMIT_READ = parseInt(process.env.RATE_LIMIT_READ || '180', 10);
33
- const RATE_LIMIT_WRITE = parseInt(process.env.RATE_LIMIT_WRITE || '60', 10);
32
+ const RATE_LIMIT_READ = parseInt(process.env.RATE_LIMIT_READ || '300', 10);
33
+ const RATE_LIMIT_WRITE = parseInt(process.env.RATE_LIMIT_WRITE || '100', 10);
34
34
  const CERT_PATH = join(__dirname, '../certs/server.crt');
35
35
  const KEY_PATH = join(__dirname, '../certs/server.key');
36
36
  process.on('unhandledRejection', (reason) => {
@@ -65,14 +65,22 @@ async function main() {
65
65
  },
66
66
  frameguard: { action: 'deny' },
67
67
  }));
68
- app.use('/api/', rateLimit({
69
- windowMs: 60 * 1000,
70
- max: (req) => req.method === 'GET' ? RATE_LIMIT_READ : RATE_LIMIT_WRITE,
71
- standardHeaders: true,
72
- legacyHeaders: false,
73
- message: { error: 'Too many requests' },
74
- }));
75
- app.use(express.json({ limit: '256kb' }));
68
+ // Separate rate limiters for read (GET) and write (POST/PUT/DELETE) so polling doesn't starve writes
69
+ const rlOpts = { windowMs: 60 * 1000, standardHeaders: true, legacyHeaders: false, message: { error: 'Too many requests' } };
70
+ const readLimiter = rateLimit({ ...rlOpts, max: RATE_LIMIT_READ });
71
+ const writeLimiter = rateLimit({ ...rlOpts, max: RATE_LIMIT_WRITE });
72
+ app.use('/api/', (req, res, next) => {
73
+ if (req.method === 'GET' || req.method === 'HEAD')
74
+ return readLimiter(req, res, next);
75
+ return writeLimiter(req, res, next);
76
+ });
77
+ // Default JSON body parser; file-content PUT has its own larger-limit parser in editor router
78
+ const defaultJsonParser = express.json({ limit: '256kb' });
79
+ app.use((req, res, next) => {
80
+ if (req.method === 'PUT' && req.path.endsWith('/file-content'))
81
+ return next();
82
+ defaultJsonParser(req, res, next);
83
+ });
76
84
  if (CORS_ORIGIN) {
77
85
  app.use((_req, res, next) => {
78
86
  res.header('Access-Control-Allow-Origin', CORS_ORIGIN);
@@ -1,10 +1,9 @@
1
- import { Router } from 'express';
2
- import { writeFile } from 'fs/promises';
3
- import { join, basename } from 'path';
1
+ import express, { Router } from 'express';
2
+ import { writeFile, stat } from 'fs/promises';
3
+ import { join, basename, isAbsolute, resolve } from 'path';
4
4
  import { resolveSession } from '../middleware/auth.js';
5
- import { getCwd } from '../tmux.js';
6
5
  import { getDraft, saveDraft as saveDraftDb, getAnnotation, saveAnnotation } from '../db.js';
7
- import { validateNewPath } from '../files.js';
6
+ const MAX_FILE_CONTENT_SIZE = 10 * 1024 * 1024; // 10MB (aligned with GET file-content in files.ts)
8
7
  const router = Router();
9
8
  // Get draft for a session
10
9
  router.get('/api/sessions/:sessionId/draft', (req, res) => {
@@ -58,6 +57,8 @@ router.put('/api/sessions/:sessionId/annotations', (req, res) => {
58
57
  res.json({ ok: true });
59
58
  });
60
59
  // Write .tmp-annotations.json for ai-cli-task plan
60
+ // modulePath is an absolute path from the frontend file browser (e.g. /home/user/project/AiTasks/task-name)
61
+ // Does NOT depend on tmux session — works even if the terminal session is disconnected
61
62
  router.post('/api/sessions/:sessionId/task-annotations', async (req, res) => {
62
63
  const sessionName = resolveSession(req, res);
63
64
  if (!sessionName)
@@ -72,23 +73,94 @@ router.post('/api/sessions/:sessionId/task-annotations', async (req, res) => {
72
73
  res.status(400).json({ error: 'content must be an object' });
73
74
  return;
74
75
  }
75
- const cwd = await getCwd(sessionName);
76
- const targetFile = join(modulePath, '.tmp-annotations.json');
77
- const resolved = await validateNewPath(targetFile, cwd);
78
- if (!resolved) {
79
- res.status(400).json({ error: 'Invalid path' });
76
+ // Validate: must be absolute, must be under an AiTasks/ directory
77
+ if (!isAbsolute(modulePath)) {
78
+ res.status(400).json({ error: 'modulePath must be absolute' });
80
79
  return;
81
80
  }
82
- if (basename(resolved) !== '.tmp-annotations.json') {
83
- res.status(400).json({ error: 'Only .tmp-annotations.json is allowed' });
81
+ const parts = modulePath.split('/');
82
+ if (!parts.includes('AiTasks')) {
83
+ res.status(400).json({ error: 'modulePath must be under AiTasks/' });
84
84
  return;
85
85
  }
86
- await writeFile(resolved, JSON.stringify(content, null, 2), 'utf-8');
87
- res.json({ ok: true, path: resolved });
86
+ // Resolve to prevent path traversal (.. etc)
87
+ const targetFile = resolve(join(modulePath, '.tmp-annotations.json'));
88
+ if (basename(targetFile) !== '.tmp-annotations.json' || !targetFile.includes('/AiTasks/')) {
89
+ res.status(400).json({ error: 'Invalid target path' });
90
+ return;
91
+ }
92
+ // Verify parent directory exists
93
+ try {
94
+ await stat(modulePath);
95
+ }
96
+ catch {
97
+ res.status(400).json({ error: `Directory not found: ${modulePath}` });
98
+ return;
99
+ }
100
+ await writeFile(targetFile, JSON.stringify(content, null, 2), 'utf-8');
101
+ res.json({ ok: true, path: targetFile });
88
102
  }
89
103
  catch (err) {
90
104
  console.error(`[api:task-annotations] ${sessionName}:`, err);
91
105
  res.status(500).json({ error: 'Failed to write annotation file' });
92
106
  }
93
107
  });
108
+ // Write file content (for Plan panel inline editing)
109
+ // Only allows writing to files under AiTasks/ directories
110
+ router.put('/api/sessions/:sessionId/file-content', express.json({ limit: '11mb' }), async (req, res) => {
111
+ const sessionName = resolveSession(req, res);
112
+ if (!sessionName)
113
+ return;
114
+ try {
115
+ const { path: filePath, content } = req.body;
116
+ if (!filePath || typeof filePath !== 'string') {
117
+ res.status(400).json({ error: 'path must be a string' });
118
+ return;
119
+ }
120
+ if (typeof content !== 'string') {
121
+ res.status(400).json({ error: 'content must be a string' });
122
+ return;
123
+ }
124
+ if (content.length > MAX_FILE_CONTENT_SIZE) {
125
+ res.status(413).json({ error: 'Content too large (max 2MB)' });
126
+ return;
127
+ }
128
+ // Must be absolute path
129
+ if (!isAbsolute(filePath)) {
130
+ res.status(400).json({ error: 'path must be absolute' });
131
+ return;
132
+ }
133
+ // Must be under an AiTasks/ directory
134
+ const parts = filePath.split('/');
135
+ if (!parts.includes('AiTasks')) {
136
+ res.status(400).json({ error: 'path must be under AiTasks/' });
137
+ return;
138
+ }
139
+ // Resolve to prevent path traversal
140
+ const resolved = resolve(filePath);
141
+ if (!resolved.includes('/AiTasks/')) {
142
+ res.status(400).json({ error: 'Invalid target path' });
143
+ return;
144
+ }
145
+ // Verify the file exists (don't create new files through this endpoint)
146
+ try {
147
+ const fileStat = await stat(resolved);
148
+ if (!fileStat.isFile()) {
149
+ res.status(400).json({ error: 'Not a file' });
150
+ return;
151
+ }
152
+ }
153
+ catch {
154
+ res.status(404).json({ error: 'File not found' });
155
+ return;
156
+ }
157
+ await writeFile(resolved, content, 'utf-8');
158
+ const newStat = await stat(resolved);
159
+ res.json({ ok: true, mtime: newStat.mtimeMs });
160
+ }
161
+ catch (err) {
162
+ console.error(`[api:file-content:write] ${sessionName}:`, err);
163
+ res.status(500).json({ error: 'Failed to write file' });
164
+ }
165
+ });
94
166
  export default router;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-server",
3
- "version": "3.0.2",
3
+ "version": "3.0.3",
4
4
  "description": "CLI-Online Backend Server",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-shared",
3
- "version": "3.0.2",
3
+ "version": "3.0.3",
4
4
  "description": "Shared types for CLI-Online",
5
5
  "type": "module",
6
6
  "main": "dist/types.js",
@@ -29,4 +29,4 @@
29
29
  * The original design remains. The terminal itself
30
30
  * has been extended to include xterm CSI codes, among
31
31
  * other features.
32
- */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Regular.woff2) format("woff2");font-weight:400;font-style:normal;font-display:swap}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Bold.woff2) format("woff2");font-weight:700;font-style:normal;font-display:swap}:root,[data-theme=dark]{--bg-primary: #000000;--bg-secondary: #0c0c0c;--bg-tertiary: #171717;--bg-hover: #1c1c1c;--border: #2d2d2d;--text-primary: #cccccc;--text-secondary: #858585;--text-bright: #e8e8e8;--accent-blue: #569cd6;--accent-purple: #c586c0;--accent-cyan: #4ec9b0;--accent-green: #89d185;--accent-yellow: #cca700;--accent-red: #f44747;--accent-orange: #ce9178;--scrollbar-thumb: rgba(121, 121, 121, .4);--scrollbar-thumb-hover: rgba(121, 121, 121, .7);--selection-bg: rgba(38, 79, 120, .5)}[data-theme=light]{--bg-primary: #ffffff;--bg-secondary: #f6f8fa;--bg-tertiary: #ffffff;--bg-hover: #eff2f5;--border: #d1d9e0;--text-primary: #1f2328;--text-secondary: #59636e;--text-bright: #1f2328;--accent-blue: #0969da;--accent-purple: #8250df;--accent-cyan: #1b7c83;--accent-green: #1a7f37;--accent-yellow: #9a6700;--accent-red: #d1242f;--accent-orange: #bc4c00;--scrollbar-thumb: rgba(31, 35, 40, .15);--scrollbar-thumb-hover: rgba(31, 35, 40, .3);--selection-bg: rgba(9, 105, 218, .2)}*{margin:0;padding:0;box-sizing:border-box}html,body,#root{width:100%;height:100%;overflow:hidden;background-color:var(--bg-primary);font-family:JetBrains Mono,LXGW WenKai Mono,Menlo,Monaco,Courier New,monospace;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}body.resizing-panes,body.resizing-panes *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.session-sidebar{transition:width .2s ease;overflow:hidden;flex-shrink:0;z-index:10;position:relative}body.resizing-panes-v,body.resizing-panes-v *{cursor:row-resize!important;-webkit-user-select:none!important;user-select:none!important}button{transition:all .15s ease;font-family:inherit}button:hover{filter:brightness(1.2)}button:active{transform:scale(.97)}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--scrollbar-thumb);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--scrollbar-thumb-hover)}::selection{background:var(--selection-bg);color:var(--text-bright)}input:focus-visible,button:focus-visible{outline:1px solid var(--accent-blue);outline-offset:1px}.header-btn{background:none;border:1px solid var(--border);color:var(--accent-blue);padding:3px 10px;border-radius:5px;cursor:pointer;font-size:13px;line-height:1.4;transition:all .15s ease}.header-btn:hover{background:#7aa2f71f;border-color:var(--accent-blue);box-shadow:0 0 8px #7aa2f726}.header-btn--muted{color:var(--text-secondary);font-size:12px}.header-btn--muted:hover{color:var(--text-primary);border-color:var(--text-secondary);background:#565f891a}.pane-btn{background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:12px;line-height:1;padding:2px 5px;border-radius:4px;transition:all .15s ease}.pane-btn:hover{color:var(--accent-blue);background:#7aa2f71f}.pane-btn--danger:hover{color:var(--accent-red);background:#f7768e1f}.login-input{transition:border-color .2s ease,box-shadow .2s ease}.login-input:focus{border-color:var(--accent-blue)!important;box-shadow:0 0 0 3px #7aa2f726}.login-card{box-shadow:0 8px 32px #0006,0 0 0 1px #7aa2f714;transition:box-shadow .3s ease}.login-submit{transition:all .2s ease}.login-submit:not(:disabled):hover{filter:brightness(1.1);box-shadow:0 4px 12px #7aa2f74d}.md-editor-textarea{flex:1;min-width:0;resize:none;border:none;outline:none;padding:8px 12px;font-family:JetBrains Mono,LXGW WenKai Mono,Menlo,Monaco,Courier New,monospace;font-size:13px;line-height:1.5;color:var(--text-primary);background-color:var(--bg-primary);-moz-tab-size:2;tab-size:2}.md-editor-textarea::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}.md-editor-divider{height:2px;background:var(--border);cursor:row-resize;flex-shrink:0;transition:background .15s ease,box-shadow .15s ease}.md-editor-divider:hover{background:var(--accent-blue);box-shadow:0 0 6px #7aa2f766}.pane-btn--active{color:var(--accent-blue)}.plan-panel-body{display:flex;flex-direction:row;flex:1;min-height:0;overflow:hidden}.plan-renderer{position:relative;overflow:hidden;padding:0;min-width:0;-webkit-user-select:text;user-select:text}.plan-divider-h{width:2px;background:var(--border);cursor:col-resize;flex-shrink:0;transition:background .15s ease,box-shadow .15s ease}.plan-divider-h:hover{background:var(--accent-blue);box-shadow:0 0 6px #7aa2f766}.plan-editor-wrap{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}.plan-filename-input{background:var(--bg-primary);border:1px solid var(--border);color:var(--text-primary);padding:2px 6px;border-radius:3px;font-family:inherit;font-size:11px;width:120px;outline:none;transition:border-color .15s ease}.plan-filename-input:focus{border-color:var(--accent-blue)}body.resizing-panes-h,body.resizing-panes-h *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.md-preview{color:var(--text-primary);font-size:13px;line-height:1.6;word-wrap:break-word}.md-preview h1{color:var(--accent-blue);font-size:1.4em;margin:.6em 0 .3em;padding-bottom:.2em;border-bottom:1px solid var(--border)}.md-preview h2{color:var(--accent-purple);font-size:1.2em;margin:.5em 0 .3em}.md-preview h3{color:var(--accent-cyan);font-size:1.05em;margin:.4em 0 .2em}.md-preview p{margin:.4em 0}.md-preview code{background:var(--bg-tertiary);color:var(--text-bright);padding:1px 4px;border-radius:3px;font-size:.9em;font-family:JetBrains Mono,LXGW WenKai Mono,monospace}.md-preview pre{background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;padding:10px 12px;overflow-x:auto;margin:.5em 0}.md-preview pre code{background:none;padding:0;border-radius:0}.md-preview blockquote{border-left:3px solid var(--accent-blue);padding:2px 12px;margin:.4em 0;color:var(--text-secondary)}.md-preview ul,.md-preview ol{padding-left:1.5em;margin:.3em 0}.md-preview li{margin:.15em 0}.md-preview table{border-collapse:collapse;width:100%;margin:.5em 0;font-size:12px}.md-preview th,.md-preview td{border:1px solid var(--border);padding:4px 8px;text-align:left}.md-preview th{background:var(--bg-tertiary);color:var(--accent-blue);font-weight:600}.md-preview a{color:var(--accent-blue);text-decoration:none}.md-preview a:hover{text-decoration:underline}.md-preview hr{border:none;border-top:1px solid var(--border);margin:.6em 0}.slash-dropdown{flex-shrink:0;max-height:200px;overflow-y:auto;background:var(--bg-secondary);border-bottom:1px solid var(--border);z-index:10;font-size:13px}.slash-item{display:flex;align-items:center;gap:10px;padding:6px 12px;cursor:pointer;transition:background .12s ease}.slash-item:hover,.slash-item--active{background:var(--bg-hover)}.slash-cmd{color:var(--accent-blue);font-weight:600;min-width:120px;font-family:JetBrains Mono,LXGW WenKai Mono,monospace}.slash-desc{color:var(--accent-purple);font-size:11px}.file-dropdown{flex-shrink:0;max-height:180px;overflow-y:auto;background:var(--bg-secondary);border-bottom:1px solid var(--border);z-index:10;font-size:12px}.file-item{display:flex;align-items:center;gap:8px;padding:5px 10px;cursor:pointer;transition:background .1s ease}.file-item:hover,.file-item--active{background:var(--bg-hover)}.file-loading{color:var(--text-secondary);cursor:default}.file-icon{flex-shrink:0;width:16px;text-align:center;font-size:13px}.file-name{color:var(--text-bright);font-family:JetBrains Mono,LXGW WenKai Mono,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.history-dropdown{flex-shrink:0;max-height:260px;overflow-y:auto;background:var(--bg-secondary);border-bottom:1px solid var(--border);z-index:10;font-size:12px}.history-item{display:flex;align-items:flex-start;gap:8px;padding:6px 10px;cursor:pointer;transition:background .1s ease;position:relative}.history-item:hover,.history-item--active{background:var(--bg-hover)}.history-empty{color:var(--text-secondary);cursor:default;justify-content:center;padding:12px}.history-text{flex:1;color:var(--text-bright);font-family:JetBrains Mono,LXGW WenKai Mono,monospace;white-space:pre-wrap;overflow-wrap:break-word;line-height:1.4}.history-time{flex-shrink:0;color:var(--text-secondary);font-size:10px;white-space:nowrap;margin-top:2px}.history-delete{flex-shrink:0;background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:14px;padding:0 2px;line-height:1;opacity:0;transition:opacity .1s ease,color .1s ease}.history-item:hover .history-delete,.history-item--active .history-delete{opacity:1}.history-delete:hover{color:var(--accent-red)}.tab-bar{display:flex;align-items:center;padding:0 10px;height:32px;background:var(--bg-secondary);border-top:1px solid var(--border);flex-shrink:0;overflow-x:auto;gap:3px}.tab-bar::-webkit-scrollbar{height:0}.tab-item{display:flex;align-items:center;gap:6px;padding:4px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;border-bottom:2px solid transparent;white-space:nowrap;transition:color .15s ease,border-color .15s ease,background .15s ease,box-shadow .15s ease;border-radius:5px 5px 0 0;-webkit-user-select:none;user-select:none;flex-shrink:0}.tab-item:hover{color:var(--text-primary);background:#7aa2f70f}.tab-item--active{color:var(--text-bright);border-bottom-color:var(--accent-blue);background:#7aa2f71a;box-shadow:inset 0 -1px 0 var(--accent-blue)}.tab-item__name{max-width:150px;overflow:hidden;text-overflow:ellipsis}.tab-item__count{font-size:10px;color:var(--scrollbar-thumb-hover)}.tab-item__close{font-size:14px;line-height:1;color:inherit;opacity:0;background:none;border:none;cursor:pointer;padding:0 2px;border-radius:3px;transition:opacity .1s ease}.tab-item:hover .tab-item__close{opacity:.5}.tab-item__close:hover{opacity:1!important;color:var(--accent-red);background:#f7768e1a}.tab-item__rename-input{background:transparent;border:1px solid var(--accent-blue);color:var(--text-bright);font-size:13px;font-family:inherit;padding:0 6px;border-radius:3px;outline:none;width:100px}.tab-bar-add{background:none;border:1px solid transparent;color:var(--text-secondary);font-size:18px;line-height:1;padding:2px 8px;border-radius:5px;cursor:pointer;margin-left:4px;flex-shrink:0}.tab-bar-add:hover{color:var(--accent-blue);border-color:var(--border);background:#7aa2f71a}.md-editor-actions{display:flex;align-items:center;gap:8px;padding:4px 8px;flex-shrink:0;background:var(--bg-secondary);border-top:1px solid var(--border)}.plan-anno-toolbar{display:flex;align-items:center;gap:6px;padding:3px 10px;height:28px;flex-shrink:0;background:var(--bg-secondary);border-bottom:1px solid var(--border)}.plan-anno-content{-webkit-user-select:text;user-select:text}.plan-insert-zone{position:relative;min-height:12px}.plan-insert-btn{display:none;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:20px;height:20px;border-radius:50%;border:1px solid var(--scrollbar-thumb-hover);background:var(--bg-secondary);color:var(--accent-blue);font-size:15px;line-height:1;cursor:pointer;padding:0 0 1px;z-index:2;transition:background .12s ease,border-color .12s ease,transform .12s ease;align-items:center;justify-content:center}.plan-insert-zone:hover .plan-insert-btn{display:flex}.plan-anno-content--editing .plan-insert-zone:hover .plan-insert-btn{display:none}.plan-empty-placeholder{display:flex;align-items:center;justify-content:center;min-height:120px;color:var(--text-secondary);font-size:13px;font-style:italic;cursor:pointer;-webkit-user-select:none;user-select:none;text-align:center;padding:16px}.plan-empty-placeholder:hover{color:var(--accent-blue)}.plan-insert-btn:hover{background:var(--bg-hover);border-color:var(--accent-blue);transform:translate(-50%,-50%) scale(1.15)}.plan-annotation-card{display:flex;align-items:flex-start;gap:6px;padding:6px 10px;margin:4px 0;background:#e0af681f;border-left:3px solid var(--accent-yellow);border-radius:0 4px 4px 0}.plan-annotation-card--editing{border-left-color:var(--accent-blue);background:#7aa2f70f}.plan-annotation-textarea{flex:1;min-height:36px;max-height:30em;field-sizing:content;resize:vertical;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-family:JetBrains Mono,LXGW WenKai Mono,monospace;font-size:12px;padding:4px 6px;outline:none;transition:border-color .15s ease}.plan-annotation-textarea:focus{border-color:var(--accent-blue)}.plan-annotation-textarea::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}.plan-deletion-card{display:flex;align-items:center;gap:6px;padding:2px 8px;margin:2px 0;background:#f7768e0f;border-left:3px solid var(--accent-red);border-radius:0 4px 4px 0;font-size:11px}.plan-selection-float{position:absolute;z-index:1000;display:flex;flex-direction:row;gap:2px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;padding:2px;box-shadow:0 2px 8px #0000004d}.plan-selection-float button{width:24px;height:24px;border-radius:4px;border:none;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;background:transparent;transition:background .15s,transform .1s}.plan-selection-float button:hover{transform:scale(1.1)}.plan-selection-float__delete{color:var(--accent-red)}.plan-selection-float__delete:hover{background:#f7768e33}.plan-selection-float__replace{color:var(--accent-blue)}.plan-selection-float__replace:hover{background:#7aa2f733}.plan-selection-float__comment{color:var(--accent-green)}.plan-selection-float__comment:hover{background:#9ece6a33}.plan-replace-card{display:flex;align-items:flex-start;gap:6px;padding:2px 8px;margin:2px 0;border-left:3px solid rgba(122,162,247,.6);background:#7aa2f70a;border-radius:0 4px 4px 0;font-size:11px}.plan-comment-card{display:flex;align-items:flex-start;gap:6px;padding:2px 8px;margin:2px 0;border-left:3px solid rgba(158,206,106,.6);background:#9ece6a0a;border-radius:0 4px 4px 0;font-size:11px}.plan-block--deleted{border-left:3px solid rgba(247,118,142,.5);padding-left:8px;border-radius:2px;position:relative}.plan-block--replaced{border-left:3px solid rgba(122,162,247,.5);padding-left:8px;border-radius:2px;position:relative}.plan-block--commented{border-left:3px solid rgba(158,206,106,.5);padding-left:8px;border-radius:2px;position:relative}.mermaid-diagram{margin:8px 0;padding:12px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;overflow-x:auto}.mermaid-diagram svg{display:block;margin:0 auto;max-width:100%;height:auto}.mermaid-error{border-left:3px solid var(--accent-red);padding-left:8px}.mermaid-error__msg{color:var(--accent-red);font-size:11px;margin-top:4px}.pane-btn--sm{font-size:11px;flex-shrink:0}.plan-file-browser{display:flex;flex-direction:column;height:100%;width:100%;background:var(--bg-secondary);overflow:hidden}.plan-file-browser__header{display:flex;align-items:center;justify-content:space-between;padding:4px 8px;height:28px;flex-shrink:0;border-bottom:1px solid var(--border)}.plan-file-browser__title{font-size:11px;color:var(--accent-blue);font-weight:600;letter-spacing:.3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;direction:rtl;text-align:left}.plan-file-browser__list{flex:1;overflow-y:auto;overflow-x:hidden;padding:2px 0}.plan-file-browser__status{padding:8px 10px;font-size:11px;color:var(--text-secondary);font-style:italic}.plan-file-browser__item{display:flex;align-items:center;padding:3px 8px;font-size:12px;cursor:pointer;gap:5px;transition:background .1s ease;border-left:2px solid transparent}.plan-file-browser__item:hover{background:var(--bg-tertiary)}.plan-file-browser__item--active{background:#7aa2f71a;border-left-color:var(--accent-blue)}.plan-file-browser__item--active .plan-file-browser__name{color:var(--text-bright)}.plan-file-browser__icon{flex-shrink:0;width:14px;font-size:10px;color:var(--text-secondary);text-align:center}.plan-file-browser__name{flex:1;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.plan-file-browser__size{flex-shrink:1;font-size:9px;color:var(--scrollbar-thumb-hover);white-space:nowrap;overflow:hidden;min-width:0}.plan-file-browser__create{display:flex;align-items:center;gap:4px;padding:4px 6px;border-top:1px solid var(--border);flex-shrink:0}.plan-file-browser__input{flex:1;min-width:0;background:var(--bg-primary);border:1px solid var(--border);color:var(--text-primary);padding:2px 6px;border-radius:3px;font-family:inherit;font-size:11px;outline:none;transition:border-color .15s ease}.plan-file-browser__input:focus{border-color:var(--accent-blue)}.plan-file-browser__input::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}.plan-overlay-body{display:flex;flex:1;min-height:0;overflow:hidden}.plan-overlay-center{flex:1;min-width:0;overflow:hidden}.plan-anno-counts{display:inline-flex;align-items:center;gap:4px;font-size:10px;margin-left:4px}.plan-anno-counts__unsent{color:var(--accent-yellow)}.plan-anno-counts__sent{color:var(--accent-green)}.plan-anno-dropdown-trigger{display:flex;align-items:center;gap:4px;padding:2px 6px;border:1px solid var(--border);border-radius:3px;cursor:pointer;background:var(--bg-primary);transition:border-color .15s ease,background .15s ease;min-width:0}.plan-anno-dropdown-trigger:hover,.plan-anno-dropdown-trigger--active{border-color:var(--accent-blue);background:var(--bg-hover)}.plan-anno-dropdown-trigger__text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:var(--text-secondary)}.plan-anno-dropdown-trigger__arrow{flex-shrink:0;font-size:9px;color:var(--text-secondary);transition:transform .15s ease}.plan-anno-dropdown-trigger--active .plan-anno-dropdown-trigger__arrow{transform:rotate(180deg)}.plan-anno-dropdown{position:absolute;top:100%;right:0;z-index:100;width:320px;max-height:300px;display:flex;flex-direction:column;background:var(--bg-secondary);border:1px solid var(--border);border-radius:4px;box-shadow:0 4px 12px #0000004d;overflow:hidden}.plan-anno-dropdown__header{display:flex;align-items:center;justify-content:center;padding:4px 6px;border-bottom:1px solid var(--border);flex-shrink:0}.plan-anno-dropdown__list{flex:1;overflow-y:auto;padding:2px 0}.plan-anno-dropdown__item{display:flex;align-items:center;gap:4px;padding:3px 6px;font-size:11px;border-bottom:1px solid var(--border-subtle, rgba(128,128,128,.1))}.plan-anno-dropdown__item:last-child{border-bottom:none}.plan-anno-dropdown__item--add{border-left:2px solid var(--accent-yellow)}.plan-anno-dropdown__item--del{border-left:2px solid var(--accent-red)}.plan-anno-dropdown__item--rep{border-left:2px solid var(--accent-blue)}.plan-anno-dropdown__item--com{border-left:2px solid var(--accent-green)}.plan-anno-dropdown__type{flex-shrink:0;width:14px;font-weight:700;text-align:center}.plan-anno-dropdown__text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-primary)}.plan-anno-dropdown__badge{flex-shrink:0;font-size:9px;padding:0 4px;border-radius:3px;background:var(--accent-green);color:var(--bg-primary)}.plan-anno-dropdown__empty{padding:8px;text-align:center;font-size:11px;color:var(--text-secondary);font-style:italic}
32
+ */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Regular.woff2) format("woff2");font-weight:400;font-style:normal;font-display:swap}@font-face{font-family:JetBrains Mono;src:url(/fonts/JetBrainsMono-Bold.woff2) format("woff2");font-weight:700;font-style:normal;font-display:swap}:root,[data-theme=dark]{--bg-primary: #000000;--bg-secondary: #0c0c0c;--bg-tertiary: #171717;--bg-hover: #1c1c1c;--border: #2d2d2d;--text-primary: #cccccc;--text-secondary: #858585;--text-bright: #e8e8e8;--accent-blue: #569cd6;--accent-purple: #c586c0;--accent-cyan: #4ec9b0;--accent-green: #89d185;--accent-yellow: #cca700;--accent-red: #f44747;--accent-orange: #ce9178;--scrollbar-thumb: rgba(121, 121, 121, .4);--scrollbar-thumb-hover: rgba(121, 121, 121, .7);--selection-bg: rgba(38, 79, 120, .5)}[data-theme=light]{--bg-primary: #ffffff;--bg-secondary: #f6f8fa;--bg-tertiary: #ffffff;--bg-hover: #eff2f5;--border: #d1d9e0;--text-primary: #1f2328;--text-secondary: #59636e;--text-bright: #1f2328;--accent-blue: #0969da;--accent-purple: #8250df;--accent-cyan: #1b7c83;--accent-green: #1a7f37;--accent-yellow: #9a6700;--accent-red: #d1242f;--accent-orange: #bc4c00;--scrollbar-thumb: rgba(31, 35, 40, .15);--scrollbar-thumb-hover: rgba(31, 35, 40, .3);--selection-bg: rgba(9, 105, 218, .2)}*{margin:0;padding:0;box-sizing:border-box}html,body,#root{width:100%;height:100%;overflow:hidden;background-color:var(--bg-primary);font-family:JetBrains Mono,LXGW WenKai Mono,Menlo,Monaco,Courier New,monospace;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}body.resizing-panes,body.resizing-panes *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.session-sidebar{transition:width .2s ease;overflow:hidden;flex-shrink:0;z-index:10;position:relative}body.resizing-panes-v,body.resizing-panes-v *{cursor:row-resize!important;-webkit-user-select:none!important;user-select:none!important}button{transition:all .15s ease;font-family:inherit}button:hover{filter:brightness(1.2)}button:active{transform:scale(.97)}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--scrollbar-thumb);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--scrollbar-thumb-hover)}::selection{background:var(--selection-bg);color:var(--text-bright)}input:focus-visible,button:focus-visible{outline:1px solid var(--accent-blue);outline-offset:1px}.header-btn{background:none;border:1px solid var(--border);color:var(--accent-blue);padding:3px 10px;border-radius:5px;cursor:pointer;font-size:13px;line-height:1.4;transition:all .15s ease}.header-btn:hover{background:#7aa2f71f;border-color:var(--accent-blue);box-shadow:0 0 8px #7aa2f726}.header-btn--muted{color:var(--text-secondary);font-size:12px}.header-btn--muted:hover{color:var(--text-primary);border-color:var(--text-secondary);background:#565f891a}.pane-btn{background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:12px;line-height:1;padding:2px 5px;border-radius:4px;transition:all .15s ease}.pane-btn:hover{color:var(--accent-blue);background:#7aa2f71f}.pane-btn--danger:hover{color:var(--accent-red);background:#f7768e1f}.login-input{transition:border-color .2s ease,box-shadow .2s ease}.login-input:focus{border-color:var(--accent-blue)!important;box-shadow:0 0 0 3px #7aa2f726}.login-card{box-shadow:0 8px 32px #0006,0 0 0 1px #7aa2f714;transition:box-shadow .3s ease}.login-submit{transition:all .2s ease}.login-submit:not(:disabled):hover{filter:brightness(1.1);box-shadow:0 4px 12px #7aa2f74d}.md-editor-textarea{flex:1;min-width:0;resize:none;border:none;outline:none;padding:8px 12px;font-family:JetBrains Mono,LXGW WenKai Mono,Menlo,Monaco,Courier New,monospace;font-size:13px;line-height:1.5;color:var(--text-primary);background-color:var(--bg-primary);-moz-tab-size:2;tab-size:2}.md-editor-textarea::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}.md-editor-divider{height:3px;background:var(--border);cursor:row-resize;flex-shrink:0;transition:background .15s ease,box-shadow .15s ease}.md-editor-divider:hover{background:var(--accent-blue);box-shadow:0 0 6px #7aa2f766}.pane-btn--active{color:var(--accent-blue)}.plan-panel-body{display:flex;flex-direction:row;flex:1;min-height:0;overflow:hidden}.plan-renderer{position:relative;overflow:hidden;padding:0;min-width:0;-webkit-user-select:text;user-select:text}.plan-divider-h{width:2px;background:var(--border);cursor:col-resize;flex-shrink:0;transition:background .15s ease,box-shadow .15s ease}.plan-divider-h:hover{background:var(--accent-blue);box-shadow:0 0 6px #7aa2f766}.plan-editor-wrap{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}.plan-filename-input{background:var(--bg-primary);border:1px solid var(--border);color:var(--text-primary);padding:2px 6px;border-radius:3px;font-family:inherit;font-size:11px;width:120px;outline:none;transition:border-color .15s ease}.plan-filename-input:focus{border-color:var(--accent-blue)}body.resizing-panes-h,body.resizing-panes-h *{cursor:col-resize!important;-webkit-user-select:none!important;user-select:none!important}.md-preview{color:var(--text-primary);font-size:13px;line-height:1.6;word-wrap:break-word}.md-preview h1{color:var(--accent-blue);font-size:1.4em;margin:.6em 0 .3em;padding-bottom:.2em;border-bottom:1px solid var(--border)}.md-preview h2{color:var(--accent-purple);font-size:1.2em;margin:.5em 0 .3em}.md-preview h3{color:var(--accent-cyan);font-size:1.05em;margin:.4em 0 .2em}.md-preview p{margin:.4em 0}.md-preview code{background:var(--bg-tertiary);color:var(--text-bright);padding:1px 4px;border-radius:3px;font-size:.9em;font-family:JetBrains Mono,LXGW WenKai Mono,monospace}.md-preview pre{background:var(--bg-tertiary);border:1px solid var(--border);border-radius:4px;padding:10px 12px;overflow-x:auto;margin:.5em 0}.md-preview pre code{background:none;padding:0;border-radius:0}.md-preview blockquote{border-left:3px solid var(--accent-blue);padding:2px 12px;margin:.4em 0;color:var(--text-secondary)}.md-preview ul,.md-preview ol{padding-left:1.5em;margin:.3em 0}.md-preview li{margin:.15em 0}.md-preview table{border-collapse:collapse;width:100%;margin:.5em 0;font-size:12px}.md-preview th,.md-preview td{border:1px solid var(--border);padding:4px 8px;text-align:left}.md-preview th{background:var(--bg-tertiary);color:var(--accent-blue);font-weight:600}.md-preview a{color:var(--accent-blue);text-decoration:none}.md-preview a:hover{text-decoration:underline}.md-preview hr{border:none;border-top:1px solid var(--border);margin:.6em 0}.slash-dropdown{flex-shrink:0;max-height:200px;overflow-y:auto;background:var(--bg-secondary);border-bottom:1px solid var(--border);z-index:10;font-size:13px}.slash-item{display:flex;align-items:center;gap:10px;padding:6px 12px;cursor:pointer;transition:background .12s ease}.slash-item:hover,.slash-item--active{background:var(--bg-hover)}.slash-cmd{color:var(--accent-blue);font-weight:600;min-width:180px;font-family:JetBrains Mono,LXGW WenKai Mono,monospace}.slash-desc{color:var(--accent-purple);font-size:11px}.file-dropdown{flex-shrink:0;max-height:180px;overflow-y:auto;background:var(--bg-secondary);border-bottom:1px solid var(--border);z-index:10;font-size:12px}.file-item{display:flex;align-items:center;gap:8px;padding:5px 10px;cursor:pointer;transition:background .1s ease}.file-item:hover,.file-item--active{background:var(--bg-hover)}.file-loading{color:var(--text-secondary);cursor:default}.file-icon{flex-shrink:0;width:16px;text-align:center;font-size:13px}.file-name{color:var(--text-bright);font-family:JetBrains Mono,LXGW WenKai Mono,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.history-dropdown{flex-shrink:0;max-height:260px;overflow-y:auto;background:var(--bg-secondary);border-bottom:1px solid var(--border);z-index:10;font-size:12px}.history-item{display:flex;align-items:flex-start;gap:8px;padding:6px 10px;cursor:pointer;transition:background .1s ease;position:relative}.history-item:hover,.history-item--active{background:var(--bg-hover)}.history-empty{color:var(--text-secondary);cursor:default;justify-content:center;padding:12px}.history-text{flex:1;color:var(--text-bright);font-family:JetBrains Mono,LXGW WenKai Mono,monospace;white-space:pre-wrap;overflow-wrap:break-word;line-height:1.4}.history-time{flex-shrink:0;color:var(--text-secondary);font-size:10px;white-space:nowrap;margin-top:2px}.history-delete{flex-shrink:0;background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:14px;padding:0 2px;line-height:1;opacity:0;transition:opacity .1s ease,color .1s ease}.history-item:hover .history-delete,.history-item--active .history-delete{opacity:1}.history-delete:hover{color:var(--accent-red)}.tab-bar{display:flex;align-items:center;padding:0 10px;height:32px;background:var(--bg-secondary);border-top:1px solid var(--border);flex-shrink:0;overflow-x:auto;gap:3px}.tab-bar::-webkit-scrollbar{height:0}.tab-item{display:flex;align-items:center;gap:6px;padding:4px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;border-bottom:2px solid transparent;white-space:nowrap;transition:color .15s ease,border-color .15s ease,background .15s ease,box-shadow .15s ease;border-radius:5px 5px 0 0;-webkit-user-select:none;user-select:none;flex-shrink:0}.tab-item:hover{color:var(--text-primary);background:#7aa2f70f}.tab-item--active{color:var(--text-bright);border-bottom-color:var(--accent-blue);background:#7aa2f71a;box-shadow:inset 0 -1px 0 var(--accent-blue)}.tab-item__name{max-width:150px;overflow:hidden;text-overflow:ellipsis}.tab-item__count{font-size:10px;color:var(--scrollbar-thumb-hover)}.tab-item__close{font-size:14px;line-height:1;color:inherit;opacity:0;background:none;border:none;cursor:pointer;padding:0 2px;border-radius:3px;transition:opacity .1s ease}.tab-item:hover .tab-item__close{opacity:.5}.tab-item__close:hover{opacity:1!important;color:var(--accent-red);background:#f7768e1a}.tab-item__rename-input{background:transparent;border:1px solid var(--accent-blue);color:var(--text-bright);font-size:13px;font-family:inherit;padding:0 6px;border-radius:3px;outline:none;width:100px}.tab-bar-add{background:none;border:1px solid transparent;color:var(--text-secondary);font-size:18px;line-height:1;padding:2px 8px;border-radius:5px;cursor:pointer;margin-left:4px;flex-shrink:0}.tab-bar-add:hover{color:var(--accent-blue);border-color:var(--border);background:#7aa2f71a}.md-editor-actions{display:flex;align-items:center;gap:8px;padding:4px 8px;flex-shrink:0;background:var(--bg-secondary);border-top:1px solid var(--border)}.plan-anno-toolbar{display:flex;align-items:center;gap:6px;padding:3px 10px;height:28px;flex-shrink:0;background:var(--bg-secondary);border-bottom:1px solid var(--border)}.plan-anno-content{-webkit-user-select:text;user-select:text}.plan-insert-zone{position:relative;min-height:12px}.plan-insert-btn{display:none;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:20px;height:20px;border-radius:50%;border:1px solid var(--scrollbar-thumb-hover);background:var(--bg-secondary);color:var(--accent-blue);font-size:15px;line-height:1;cursor:pointer;padding:0 0 1px;z-index:2;transition:background .12s ease,border-color .12s ease,transform .12s ease;align-items:center;justify-content:center}.plan-insert-zone:hover .plan-insert-btn{display:flex}.plan-anno-content--editing .plan-insert-zone:hover .plan-insert-btn{display:none}.plan-empty-placeholder{display:flex;align-items:center;justify-content:center;min-height:120px;color:var(--text-secondary);font-size:13px;font-style:italic;cursor:pointer;-webkit-user-select:none;user-select:none;text-align:center;padding:16px}.plan-empty-placeholder:hover{color:var(--accent-blue)}.plan-insert-btn:hover{background:var(--bg-hover);border-color:var(--accent-blue);transform:translate(-50%,-50%) scale(1.15)}.plan-annotation-card{display:flex;align-items:flex-start;gap:6px;padding:6px 10px;margin:4px 0;background:#e0af681f;border-left:3px solid var(--accent-yellow);border-radius:0 4px 4px 0}.plan-annotation-card--editing{border-left-color:var(--accent-blue);background:#7aa2f70f}.plan-annotation-textarea{flex:1;min-height:36px;max-height:30em;field-sizing:content;resize:vertical;border:1px solid var(--border);border-radius:3px;background:var(--bg-primary);color:var(--text-primary);font-family:JetBrains Mono,LXGW WenKai Mono,monospace;font-size:12px;padding:4px 6px;outline:none;transition:border-color .15s ease}.plan-annotation-textarea:focus{border-color:var(--accent-blue)}.plan-annotation-textarea::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}.plan-deletion-card{display:flex;align-items:center;gap:6px;padding:2px 8px;margin:2px 0;background:#f7768e0f;border-left:3px solid var(--accent-red);border-radius:0 4px 4px 0;font-size:11px}.plan-selection-float{position:absolute;z-index:1000;display:flex;flex-direction:row;gap:2px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;padding:2px;box-shadow:0 2px 8px #0000004d}.plan-selection-float button{width:24px;height:24px;border-radius:4px;border:none;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;background:transparent;transition:background .15s,transform .1s}.plan-selection-float button:hover{transform:scale(1.1)}.plan-selection-float__delete{color:var(--accent-red)}.plan-selection-float__delete:hover{background:#f7768e33}.plan-selection-float__replace{color:var(--accent-blue)}.plan-selection-float__replace:hover{background:#7aa2f733}.plan-selection-float__comment{color:var(--accent-green)}.plan-selection-float__comment:hover{background:#9ece6a33}.plan-replace-card{display:flex;align-items:flex-start;gap:6px;padding:2px 8px;margin:2px 0;border-left:3px solid rgba(122,162,247,.6);background:#7aa2f70a;border-radius:0 4px 4px 0;font-size:11px}.plan-comment-card{display:flex;align-items:flex-start;gap:6px;padding:2px 8px;margin:2px 0;border-left:3px solid rgba(158,206,106,.6);background:#9ece6a0a;border-radius:0 4px 4px 0;font-size:11px}.plan-block--deleted{border-left:3px solid rgba(247,118,142,.5);padding-left:8px;border-radius:2px;position:relative}.plan-block--replaced{border-left:3px solid rgba(122,162,247,.5);padding-left:8px;border-radius:2px;position:relative}.plan-block--commented{border-left:3px solid rgba(158,206,106,.5);padding-left:8px;border-radius:2px;position:relative}.mermaid-diagram{margin:8px 0;padding:12px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;overflow-x:auto}.mermaid-diagram svg{display:block;margin:0 auto;max-width:100%;height:auto}.mermaid-error{border-left:3px solid var(--accent-red);padding-left:8px}.mermaid-error__msg{color:var(--accent-red);font-size:11px;margin-top:4px}.pane-btn--sm{font-size:11px;flex-shrink:0}.plan-file-browser{display:flex;flex-direction:column;height:100%;width:100%;background:var(--bg-secondary);overflow:hidden}.plan-file-browser__header{display:flex;align-items:center;justify-content:space-between;padding:4px 8px;height:28px;flex-shrink:0;border-bottom:1px solid var(--border)}.plan-file-browser__title{font-size:11px;color:var(--accent-blue);font-weight:600;letter-spacing:.3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;direction:rtl;text-align:left}.plan-file-browser__list{flex:1;overflow-y:auto;overflow-x:hidden;padding:2px 0}.plan-file-browser__status{padding:8px 10px;font-size:11px;color:var(--text-secondary);font-style:italic}.plan-file-browser__item{display:flex;align-items:center;padding:3px 8px;font-size:12px;cursor:pointer;gap:5px;transition:background .1s ease;border-left:2px solid transparent}.plan-file-browser__item:hover{background:var(--bg-tertiary)}.plan-file-browser__item--active{background:#7aa2f71a;border-left-color:var(--accent-blue)}.plan-file-browser__item--active .plan-file-browser__name{color:var(--text-bright)}.plan-file-browser__icon{flex-shrink:0;width:14px;font-size:10px;color:var(--text-secondary);text-align:center}.plan-file-browser__name{flex:1;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.plan-file-browser__size{flex-shrink:1;font-size:9px;color:var(--scrollbar-thumb-hover);white-space:nowrap;overflow:hidden;min-width:0}.plan-file-browser__create{display:flex;align-items:center;gap:4px;padding:4px 6px;border-top:1px solid var(--border);flex-shrink:0}.plan-file-browser__input{flex:1;min-width:0;background:var(--bg-primary);border:1px solid var(--border);color:var(--text-primary);padding:2px 6px;border-radius:3px;font-family:inherit;font-size:11px;outline:none;transition:border-color .15s ease}.plan-file-browser__input:focus{border-color:var(--accent-blue)}.plan-file-browser__input::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}.plan-overlay-body{display:flex;flex:1;min-height:0;overflow:hidden}.plan-overlay-center{flex:1;min-width:0;overflow:hidden}.plan-anno-counts{display:inline-flex;align-items:center;gap:4px;font-size:10px;margin-left:4px}.plan-anno-counts__unsent{color:var(--accent-yellow)}.plan-anno-counts__sent{color:var(--accent-green)}.plan-anno-dropdown-trigger{display:flex;align-items:center;gap:4px;padding:2px 6px;border:1px solid var(--border);border-radius:3px;cursor:pointer;background:var(--bg-primary);transition:border-color .15s ease,background .15s ease;min-width:0}.plan-anno-dropdown-trigger:hover,.plan-anno-dropdown-trigger--active{border-color:var(--accent-blue);background:var(--bg-hover)}.plan-anno-dropdown-trigger__text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:var(--text-secondary)}.plan-anno-dropdown-trigger__arrow{flex-shrink:0;font-size:9px;color:var(--text-secondary);transition:transform .15s ease}.plan-anno-dropdown-trigger--active .plan-anno-dropdown-trigger__arrow{transform:rotate(180deg)}.plan-anno-dropdown{position:absolute;top:100%;right:0;z-index:100;width:320px;max-height:300px;display:flex;flex-direction:column;background:var(--bg-secondary);border:1px solid var(--border);border-radius:4px;box-shadow:0 4px 12px #0000004d;overflow:hidden}.plan-anno-dropdown__header{display:flex;align-items:center;justify-content:center;padding:4px 6px;border-bottom:1px solid var(--border);flex-shrink:0}.plan-anno-dropdown__list{flex:1;overflow-y:auto;padding:2px 0}.plan-anno-dropdown__item{display:flex;align-items:center;gap:4px;padding:3px 6px;font-size:11px;border-bottom:1px solid var(--border-subtle, rgba(128,128,128,.1))}.plan-anno-dropdown__item:last-child{border-bottom:none}.plan-anno-dropdown__item--add{border-left:2px solid var(--accent-yellow)}.plan-anno-dropdown__item--del{border-left:2px solid var(--accent-red)}.plan-anno-dropdown__item--rep{border-left:2px solid var(--accent-blue)}.plan-anno-dropdown__item--com{border-left:2px solid var(--accent-green)}.plan-anno-dropdown__type{flex-shrink:0;width:14px;font-weight:700;text-align:center}.plan-anno-dropdown__text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-primary)}.plan-anno-dropdown__badge{flex-shrink:0;font-size:9px;padding:0 4px;border-radius:3px;background:var(--accent-green);color:var(--bg-primary)}.plan-anno-dropdown__empty{padding:8px;text-align:center;font-size:11px;color:var(--text-secondary);font-style:italic}.plan-edit-textarea{width:100%;flex:1;resize:none;border:none;outline:none;padding:8px 12px;font-family:JetBrains Mono,LXGW WenKai Mono,Menlo,Monaco,Courier New,monospace;line-height:1.6;background:var(--bg-primary);color:var(--text-primary);-moz-tab-size:2;tab-size:2}.plan-edit-textarea::placeholder{color:var(--scrollbar-thumb-hover);font-style:italic}
@@ -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 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,{})})}));
@@ -10,11 +10,11 @@
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-9ElcUlG3.js"></script>
13
+ <script type="module" crossorigin src="/assets/index-D4ZKzY3K.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">
17
- <link rel="stylesheet" crossorigin href="/assets/index-DXFXOQ2Y.css">
17
+ <link rel="stylesheet" crossorigin href="/assets/index-BI7oV4SU.css">
18
18
  </head>
19
19
  <body>
20
20
  <div id="root"></div>
package/web/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-cli-online-web",
3
- "version": "3.0.2",
3
+ "version": "3.0.3",
4
4
  "description": "CLI-Online Web Frontend",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -1,32 +0,0 @@
1
- var Tn=Object.defineProperty;var Cn=(e,t,n)=>t in e?Tn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wt=(e,t,n)=>Cn(e,typeof t!="symbol"?t+"":t,n);import{r as a,a as En,g as In,R as bt}from"./react-vendor-BCIvbQoU.js";import{D as Qt,o as en,L as jn,x as tn}from"./terminal-DnNpv9tw.js";import{p as ut,g as nn}from"./markdown-CU76q5qk.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const i of c.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(o){if(o.ep)return;o.ep=!0;const c=n(o);fetch(o.href,c)}})();var rn={exports:{}},et={};/**
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 Rn=a,Nn=Symbol.for("react.element"),Ln=Symbol.for("react.fragment"),Dn=Object.prototype.hasOwnProperty,Mn=Rn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,An={key:!0,ref:!0,__self:!0,__source:!0};function on(e,t,n){var r,o={},c=null,i=null;n!==void 0&&(c=""+n),t.key!==void 0&&(c=""+t.key),t.ref!==void 0&&(i=t.ref);for(r in t)Dn.call(t,r)&&!An.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:Nn,type:e,key:c,ref:i,props:o,_owner:Mn.current}}et.Fragment=Ln;et.jsx=on;et.jsxs=on;rn.exports=et;var s=rn.exports,ft={},St=En;ft.createRoot=St.createRoot,ft.hydrateRoot=St.hydrateRoot;const zn={},kt=e=>{let t;const n=new Set,r=(u,f)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const g=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(x=>x(t,g))}},o=()=>t,p={setState:r,getState:o,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{n.clear()}},l=t=e(r,o,p);return p},_n=e=>e?kt(e):kt;var sn={exports:{}},an={},cn={exports:{}},ln={};/**
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 je=a;function $n(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var On=typeof Object.is=="function"?Object.is:$n,Pn=je.useState,Fn=je.useEffect,Bn=je.useLayoutEffect,Un=je.useDebugValue;function Wn(e,t){var n=t(),r=Pn({inst:{value:n,getSnapshot:t}}),o=r[0].inst,c=r[1];return Bn(function(){o.value=n,o.getSnapshot=t,ct(o)&&c({inst:o})},[e,n,t]),Fn(function(){return ct(o)&&c({inst:o}),e(function(){ct(o)&&c({inst:o})})},[e]),Un(n),n}function ct(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!On(e,n)}catch{return!0}}function Hn(e,t){return t()}var Kn=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hn:Wn;ln.useSyncExternalStore=je.useSyncExternalStore!==void 0?je.useSyncExternalStore:Kn;cn.exports=ln;var Jn=cn.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 tt=a,Gn=Jn;function Vn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var qn=typeof Object.is=="function"?Object.is:Vn,Yn=Gn.useSyncExternalStore,Xn=tt.useRef,Zn=tt.useEffect,Qn=tt.useMemo,er=tt.useDebugValue;an.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var c=Xn(null);if(c.current===null){var i={hasValue:!1,value:null};c.current=i}else i=c.current;c=Qn(function(){function p(g){if(!l){if(l=!0,u=g,g=r(g),o!==void 0&&i.hasValue){var x=i.value;if(o(x,g))return f=x}return f=g}if(x=f,qn(u,g))return x;var R=r(g);return o!==void 0&&o(x,R)?(u=g,x):(u=g,f=R)}var l=!1,u,f,h=n===void 0?null:n;return[function(){return p(t())},h===null?void 0:function(){return p(h())}]},[t,n,r,o]);var d=Yn(e,c[0],c[1]);return Zn(function(){i.hasValue=!0,i.value=d},[d]),er(d),d};sn.exports=an;var tr=sn.exports;const nr=In(tr),dn={},{useDebugValue:rr}=bt,{useSyncExternalStoreWithSelector:or}=nr;let Tt=!1;const sr=e=>e;function ar(e,t=sr,n){(dn?"production":void 0)!=="production"&&n&&!Tt&&(Tt=!0);const r=or(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return rr(r),r}const Ct=e=>{const t=typeof e=="function"?_n(e):e,n=(r,o)=>ar(t,r,o);return Object.assign(n,t),n},cr=e=>e?Ct(e):Ct,xe="";function oe(e){return{Authorization:`Bearer ${e}`}}class Ae extends Error{constructor(t,n){super(n),this.status=t,this.name="ApiError"}}function Ce(e,t){return`${xe}/api/sessions/${encodeURIComponent(e)}/${t}`}function Et(e){return`${xe}/api/settings/${e}`}async function Ve(e){if(!e.ok){const t=await e.text().catch(()=>e.statusText);throw new Ae(e.status,t)}return e.json()}const ne={async get(e,t,n,r){const o=new URL(Ce(t,n),window.location.origin);if(r)for(const[i,d]of Object.entries(r))o.searchParams.set(i,d);const c=await fetch(o.toString(),{headers:oe(e)});return Ve(c)},async getOptional(e,t,n,r){const o=new URL(Ce(t,n),window.location.origin);if(r)for(const[i,d]of Object.entries(r))o.searchParams.set(i,d);const c=await fetch(o.toString(),{headers:oe(e)});return c.status===304?null:Ve(c)},async post(e,t,n,r){const o=await fetch(Ce(t,n),{method:"POST",headers:{...oe(e),"Content-Type":"application/json"},body:JSON.stringify(r)});return Ve(o)},async put(e,t,n,r){const o=await fetch(Ce(t,n),{method:"PUT",headers:{...oe(e),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const c=await o.text().catch(()=>o.statusText);throw new Ae(o.status,c)}},async del(e,t,n,r){const o=await fetch(Ce(t,n),{method:"DELETE",headers:{...oe(e),"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0});if(!o.ok){const c=await o.text().catch(()=>o.statusText);throw new Ae(o.status,c)}},async getBlob(e,t,n,r){const o=new URL(Ce(t,n),window.location.origin);if(r)for(const[i,d]of Object.entries(r))o.searchParams.set(i,d);const c=await fetch(o.toString(),{headers:oe(e)});if(!c.ok)throw new Ae(c.status,"Download failed");return c}},nt={async get(e,t){const n=await fetch(Et(t),{headers:oe(e)});return Ve(n)},async put(e,t,n){const r=await fetch(Et(t),{method:"PUT",headers:{...oe(e),"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.text().catch(()=>r.statusText);throw new Ae(r.status,o)}}};async function ir(e){try{return(await nt.get(e,"font-size")).fontSize}catch{return 14}}async function lr(e,t){try{await nt.put(e,"font-size",{fontSize:t})}catch{}}let We=null;const dr=(e,t)=>({fontSize:14,setFontSize:n=>{const r=Math.max(10,Math.min(24,n));e({fontSize:r}),We&&clearTimeout(We),We=setTimeout(()=>{We=null;const o=t().token;o&&lr(o,r)},500)},latency:null,setLatency:n=>e({latency:n}),theme:(()=>{try{const n=localStorage.getItem("ai-cli-online-theme");if(n==="light"||n==="dark")return n}catch{}return"dark"})(),setTheme:n=>{e({theme:n});try{localStorage.setItem("ai-cli-online-theme",n)}catch{}document.documentElement.setAttribute("data-theme",n)},toggleTheme:()=>{const n=t().theme==="dark"?"light":"dark";t().setTheme(n)},sidebarOpen:!1,toggleSidebar:()=>e(n=>({sidebarOpen:!n.sidebarOpen})),serverSessions:[],fetchSessions:async()=>{const n=t().token;if(n)try{const r=await fetch(`${xe}/api/sessions`,{headers:oe(n)});if(!r.ok)return;const o=await r.json();e({serverSessions:o})}catch{}}});function qe(e,t){if(e.type==="leaf")return e.terminalId===t?null:e;const n=[],r=[];for(let i=0;i<e.children.length;i++){const d=qe(e.children[i],t);d!==null&&(n.push(d),r.push(e.sizes[i]))}if(n.length===0)return null;if(n.length===1)return n[0];const o=r.reduce((i,d)=>i+d,0),c=r.map(i=>i/o*100);return{...e,children:n,sizes:c}}function un(e,t,n,r,o){return e.type==="leaf"?e.terminalId===t?{id:o,type:"split",direction:n,children:[e,r],sizes:[50,50]}:e:{...e,children:e.children.map(c=>un(c,t,n,r,o))}}function fn(e,t,n){return e.type==="leaf"?e:e.id===t?{...e,sizes:n}:{...e,children:e.children.map(r=>fn(r,t,n))}}function it(e){return e.tabs.find(t=>t.id===e.activeTabId)}function pe(e,t,n){return e.map(r=>r.id===t?n(r):r)}function It(e,t){const n=e.tabs.find(l=>l.terminalIds.includes(t));if(!n){const{[t]:l,...u}=e.terminalsMap;return{terminalsMap:u}}const r=n.terminalIds.filter(l=>l!==t),o=n.layout?qe(n.layout,t):null,c=pe(e.tabs,n.id,l=>({...l,terminalIds:r,layout:o})),{[t]:i,...d}=e.terminalsMap,p={terminalsMap:d,tabs:c};return n.id===e.activeTabId&&(p.terminalIds=r,p.layout=o),p}async function ur(e){try{return(await nt.get(e,"tabs-layout")).layout}catch{return null}}async function fr(e,t){try{await nt.put(e,"tabs-layout",{layout:t})}catch{}}function jt(e,t){try{const n=`${xe}/api/settings/tabs-layout`,r=JSON.stringify({layout:t,token:e});navigator.sendBeacon(n,new Blob([r],{type:"application/json"}))}catch{}}const pt="ai-cli-online-tabs",Rt="ai-cli-online-layout",Nt="ai-cli-online-session-names";let ie=null;function pr(e){ie=e,yr()}let He=null,we=null,ze=null;function mr(e){ze=e,we&&clearTimeout(we),we=setTimeout(()=>{we=null,ze=null;const t=ie==null?void 0:ie.getState().token;t&&fr(t,e)},2e3)}function te(e){const t={version:2,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId,tabs:e.tabs};try{localStorage.setItem(pt,JSON.stringify(t))}catch{}mr(t)}function hr(e){He&&clearTimeout(He),He=setTimeout(()=>{He=null,te(e)},500)}function ee(e){return{tabs:e.tabs,activeTabId:e.activeTabId,nextId:e.nextId,nextSplitId:e.nextSplitId,nextTabId:e.nextTabId}}function gr(){try{const e=localStorage.getItem(pt);if(e){const t=JSON.parse(e);if(t.version===2)return t}}catch{}try{const e=localStorage.getItem(Rt);if(e){const t=JSON.parse(e);let n="Default";try{const c=localStorage.getItem(Nt);if(c){const i=JSON.parse(c),d=Object.values(i)[0];d&&(n=d)}}catch{}const r={id:"tab1",name:n,status:"open",terminalIds:t.terminalIds,layout:t.layout,createdAt:Date.now()},o={version:2,activeTabId:"tab1",nextId:t.nextId,nextSplitId:t.nextSplitId,nextTabId:2,tabs:[r]};try{localStorage.setItem(pt,JSON.stringify(o))}catch{}return localStorage.removeItem(Rt),localStorage.removeItem(Nt),o}}catch{}return null}function br(e,t){const n=new Set(t.map(i=>i.sessionId)),r=[];for(const i of e.tabs){if(i.status!=="open"){const l=i.terminalIds.filter(u=>n.has(u));if(l.length>0){let u=i.layout;for(const f of i.terminalIds)!n.has(f)&&u&&(u=qe(u,f));r.push({...i,terminalIds:l,layout:u})}continue}const d=i.terminalIds.filter(l=>n.has(l));if(d.length===0)continue;let p=i.layout;for(const l of i.terminalIds)!n.has(l)&&p&&(p=qe(p,l));r.push({...i,terminalIds:d,layout:p})}if(r.filter(i=>i.status==="open").length===0)return null;let o=e.activeTabId;if(!r.find(i=>i.id===o&&i.status==="open")){const i=r.find(d=>d.status==="open");o=(i==null?void 0:i.id)||""}return{...e,activeTabId:o,tabs:r}}async function xr(e,t){var o,c;if(!ie)return;const{setState:n,getState:r}=ie;try{const[i,d]=await Promise.all([ur(e),fetch(`${xe}/api/sessions`,{headers:oe(e)}).then(x=>x.ok?x.json():[]).catch(()=>[])]);if(r().token!==e)return;const p=i&&((o=i.tabs)==null?void 0:o.length)>0?i:t;if(!p||p.tabs.length===0){n({tabsLoading:!1});return}const l=br(p,d);if(!l){n({tabsLoading:!1,terminalsMap:{},tabs:[],activeTabId:"",nextId:p.nextId,nextSplitId:p.nextSplitId,nextTabId:p.nextTabId,terminalIds:[],layout:null});return}const u=r().terminalsMap,f={};for(const x of l.tabs)if(x.status==="open")for(const R of x.terminalIds)f[R]=u[R]||{id:R,connected:!1,sessionResumed:!1,error:null,panels:((c=x.panelStates)==null?void 0:c[R])||{chatOpen:!1,planOpen:!1}};const h=l.tabs.find(x=>x.id===l.activeTabId&&x.status==="open")||l.tabs.find(x=>x.status==="open"),g=(h==null?void 0:h.id)||"";n({tabsLoading:!1,terminalsMap:f,tabs:l.tabs,activeTabId:g,nextId:l.nextId,nextSplitId:l.nextSplitId,nextTabId:l.nextTabId,terminalIds:(h==null?void 0:h.terminalIds)||[],layout:(h==null?void 0:h.layout)||null}),te(ee(r()))}catch{r().token===e&&n({tabsLoading:!1})}}function yr(){typeof window>"u"||!ie||window.addEventListener("beforeunload",()=>{const e=ie==null?void 0:ie.getState().token;if(e)if(ze)we&&(clearTimeout(we),we=null),jt(e,ze),ze=null;else{const t=ie.getState();t.tabs.length>0&&jt(e,ee(t))}})}const _=cr((...e)=>{const[t,n]=e;return{...dr(...e),token:null,tabsLoading:!1,setToken:r=>{var o;if(r){try{localStorage.setItem("ai-cli-online-token",r)}catch{}ir(r).then(i=>{n().token===r&&t({fontSize:i})});const c=gr();if(c&&c.tabs.length>0){const i={};for(const l of c.tabs)if(l.status==="open")for(const u of l.terminalIds)i[u]={id:u,connected:!1,sessionResumed:!1,error:null,panels:((o=l.panelStates)==null?void 0:o[u])||{chatOpen:!1,planOpen:!1}};const d=c.tabs.find(l=>l.id===c.activeTabId&&l.status==="open")||c.tabs.find(l=>l.status==="open"),p=(d==null?void 0:d.id)||"";t({token:r,tabsLoading:!0,terminalsMap:i,tabs:c.tabs,activeTabId:p,nextId:c.nextId,nextSplitId:c.nextSplitId,nextTabId:c.nextTabId,terminalIds:(d==null?void 0:d.terminalIds)||[],layout:(d==null?void 0:d.layout)||null})}else t({token:r,tabsLoading:!0,terminalsMap:{},tabs:[],activeTabId:"",nextId:1,nextSplitId:1,nextTabId:1,terminalIds:[],layout:null});xr(r,c);return}localStorage.removeItem("ai-cli-online-token"),localStorage.removeItem("ai-cli-online-tabs"),t({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 o=n(),c=`tab${o.nextTabId}`,i=`t${o.nextId}`,d={id:i,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},p={type:"leaf",terminalId:i},l={id:c,name:r||`Tab ${o.nextTabId}`,status:"open",terminalIds:[i],layout:p,createdAt:Date.now()};return t({tabs:[...o.tabs,l],activeTabId:c,nextTabId:o.nextTabId+1,nextId:o.nextId+1,terminalsMap:{...o.terminalsMap,[i]:d},terminalIds:l.terminalIds,layout:l.layout}),te(ee(n())),c},switchTab:r=>{const c=n().tabs.find(i=>i.id===r);!c||c.status!=="open"||(t({activeTabId:r,terminalIds:c.terminalIds,layout:c.layout}),te(ee(n())))},closeTab:r=>{const o=n(),c=o.tabs.find(h=>h.id===r);if(!c||c.status!=="open"||o.tabs.filter(h=>h.status==="open").length<=1)return;const d={...o.terminalsMap};for(const h of c.terminalIds)delete d[h];const p=pe(o.tabs,r,h=>({...h,status:"closed"}));let l=o.activeTabId,u=o.terminalIds,f=o.layout;if(o.activeTabId===r){const h=o.tabs.findIndex(R=>R.id===r),g=p.filter(R=>R.status==="open"),x=g.find(R=>p.findIndex(j=>j.id===R.id)>h)||g[g.length-1];x&&(l=x.id,u=x.terminalIds,f=x.layout)}t({tabs:p,activeTabId:l,terminalsMap:d,terminalIds:u,layout:f}),te(ee(n()))},reopenTab:r=>{var p;const o=n(),c=o.tabs.find(l=>l.id===r);if(!c||c.status!=="closed")return;const i={...o.terminalsMap};for(const l of c.terminalIds)i[l]={id:l,connected:!1,sessionResumed:!1,error:null,panels:((p=c.panelStates)==null?void 0:p[l])||{chatOpen:!1,planOpen:!1}};const d=pe(o.tabs,r,l=>({...l,status:"open"}));t({tabs:d,activeTabId:r,terminalsMap:i,terminalIds:c.terminalIds,layout:c.layout}),te(ee(n()))},deleteTab:async r=>{const o=n(),c=o.tabs.find(x=>x.id===r);if(!c)return;const i=o.token;i&&await Promise.all(c.terminalIds.map(x=>fetch(`${xe}/api/sessions/${encodeURIComponent(x)}`,{method:"DELETE",headers:oe(i)}).catch(()=>{})));const d=n(),p=d.tabs.find(x=>x.id===r);if(!p)return;const l={...d.terminalsMap};for(const x of p.terminalIds)delete l[x];const u=d.tabs.filter(x=>x.id!==r);let f=d.activeTabId,h=d.terminalIds,g=d.layout;if(d.activeTabId===r){const x=u.find(R=>R.status==="open");x?(f=x.id,h=x.terminalIds,g=x.layout):(f="",h=[],g=null)}t({tabs:u,activeTabId:f,terminalsMap:l,terminalIds:h,layout:g}),te(ee(n())),setTimeout(()=>n().fetchSessions(),500)},renameTab:(r,o)=>{const c=pe(n().tabs,r,i=>({...i,name:o}));t({tabs:c}),te(ee(n()))},addTerminal:(r,o)=>{const c=n();if(o&&c.terminalsMap[o])return o;const i=it(c);if(!i){const P=`tab${c.nextTabId}`,B=o||`t${c.nextId}`;let $=c.nextId;const F=B.match(/^t(\d+)$/);F&&($=Math.max($,parseInt(F[1],10)+1));const O=o?$:$+1,D={id:B,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},T={type:"leaf",terminalId:B},y={id:P,name:`Tab ${c.nextTabId}`,status:"open",terminalIds:[B],layout:T,createdAt:Date.now()};return t({tabs:[...c.tabs,y],activeTabId:P,nextTabId:c.nextTabId+1,nextId:O,terminalsMap:{...c.terminalsMap,[B]:D},terminalIds:[B],layout:T}),te(ee(n())),B}const{nextId:d,nextSplitId:p,terminalsMap:l}=c,{terminalIds:u,layout:f}=i,h=o||`t${d}`;let g=d;const x=h.match(/^t(\d+)$/);x&&(g=Math.max(g,parseInt(x[1],10)+1));const R={id:h,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1}},C={type:"leaf",terminalId:h};let j,S=p;if(!f)j=C;else if(f.type==="leaf"){const P=r||"horizontal";j={id:`s${S}`,type:"split",direction:P,children:[f,C],sizes:[50,50]},S++}else if(f.direction===(r||"horizontal")){const B=100/(f.children.length+1),$=(100-B)/100,F=[...f.sizes.map(O=>O*$),B];j={...f,children:[...f.children,C],sizes:F}}else{const P=r||"horizontal";j={id:`s${S}`,type:"split",direction:P,children:[f,C],sizes:[50,50]},S++}const w=[...u,h],k=o?g:g+1,A=pe(c.tabs,i.id,P=>({...P,terminalIds:w,layout:j}));return t({terminalsMap:{...l,[h]:R},terminalIds:w,layout:j,tabs:A,nextId:k,nextSplitId:S}),te(ee(n())),h},splitTerminal:(r,o,c)=>{const i=n(),d=it(i);if(!d||!d.layout)return"";const{nextId:p,nextSplitId:l,terminalsMap:u}=i,f=`t${p}`,h={id:f,connected:!1,sessionResumed:!1,error:null,panels:{chatOpen:!1,planOpen:!1},...c?{startCwd:c}:{}},g={type:"leaf",terminalId:f},x=`s${l}`,R=un(d.layout,r,o,g,x),C=[...d.terminalIds,f],j=p+1,S=l+1,w=pe(i.tabs,d.id,k=>({...k,terminalIds:C,layout:R}));return t({terminalsMap:{...u,[f]:h},terminalIds:C,layout:R,tabs:w,nextId:j,nextSplitId:S}),te(ee(n())),f},removeTerminal:r=>{const o=It(n(),r);o&&(t(o),te(ee(n())))},disconnectTerminal:r=>{const o=n();if(!o.terminalsMap[r])return;const{[r]:i,...d}=o.terminalsMap;t({terminalsMap:d})},reconnectTerminal:r=>{var p;const o=n();if(o.terminalsMap[r])return;const c=o.tabs.find(l=>l.terminalIds.includes(r)),i=((p=c==null?void 0:c.panelStates)==null?void 0:p[r])||{chatOpen:!1,planOpen:!1},d={id:r,connected:!1,sessionResumed:!1,error:null,panels:i};t({terminalsMap:{...o.terminalsMap,[r]:d}})},setTerminalConnected:(r,o)=>{t(c=>{const i=c.terminalsMap[r];return!i||i.connected===o?c:{terminalsMap:{...c.terminalsMap,[r]:{...i,connected:o}}}})},setTerminalResumed:(r,o)=>{t(c=>{const i=c.terminalsMap[r];return!i||i.sessionResumed===o?c:{terminalsMap:{...c.terminalsMap,[r]:{...i,sessionResumed:o}}}})},setTerminalError:(r,o)=>{t(c=>{const i=c.terminalsMap[r];return!i||i.error===o?c:{terminalsMap:{...c.terminalsMap,[r]:{...i,error:o}}}})},toggleChat:r=>{const o=n(),c=o.terminalsMap[r];if(!c)return;const i={...c.panels,chatOpen:!c.panels.chatOpen},d={...o.terminalsMap,[r]:{...c,panels:i}},p=o.tabs.find(u=>u.terminalIds.includes(r));let l=o.tabs;if(p){const u={...p.panelStates,[r]:i};l=pe(o.tabs,p.id,f=>({...f,panelStates:u}))}t({terminalsMap:d,tabs:l}),te(ee(n()))},togglePlan:r=>{const o=n(),c=o.terminalsMap[r];if(!c)return;const i={...c.panels,planOpen:!c.panels.planOpen},d={...o.terminalsMap,[r]:{...c,panels:i}},p=o.tabs.find(u=>u.terminalIds.includes(r));let l=o.tabs;if(p){const u={...p.panelStates,[r]:i};l=pe(o.tabs,p.id,f=>({...f,panelStates:u}))}t({terminalsMap:d,tabs:l}),te(ee(n()))},setSplitSizes:(r,o)=>{const c=n(),i=it(c);if(!i||!i.layout)return;const d=fn(i.layout,r,o),p=pe(c.tabs,i.id,l=>({...l,layout:d}));t({layout:d,tabs:p}),hr(ee(n()))},killServerSession:async r=>{const o=n().token;if(!o)return;try{await fetch(`${xe}/api/sessions/${encodeURIComponent(r)}`,{method:"DELETE",headers:oe(o)})}catch{}const c=It(n(),r);c&&(t(c),te(ee(n()))),setTimeout(()=>n().fetchSessions(),500)}}});pr(_);typeof document<"u"&&document.documentElement.setAttribute("data-theme",_.getState().theme);function vr(){const[e,t]=a.useState(""),n=_(o=>o.setToken),r=o=>{o.preventDefault(),e.trim()&&n(e.trim())};return s.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:s.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:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"36px"},children:[s.jsx("div",{style:{width:"56px",height:"56px",margin:"0 auto 16px",borderRadius:"14px",background:"linear-gradient(135deg, 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:">_"}),s.jsx("h1",{style:{fontSize:"22px",fontWeight:"bold",color:"var(--text-bright)",marginBottom:"6px",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Terminal in your browser"})]}),s.jsxs("form",{onSubmit:r,children:[s.jsxs("div",{style:{marginBottom:"20px"},children:[s.jsx("label",{htmlFor:"token",style:{display:"block",fontSize:"12px",color:"var(--accent-blue)",marginBottom:"8px",fontWeight:500,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Auth Token"}),s.jsx("input",{type:"password",id:"token",className:"login-input",value:e,onChange:o=>t(o.target.value),placeholder:"Enter your AUTH_TOKEN",autoFocus:!0,autoComplete:"current-password",style:{width:"100%",padding:"11px 14px",backgroundColor:"var(--bg-primary)",color:"var(--text-bright)",border:"1px solid var(--border)",borderRadius:"8px",fontSize:"14px",outline:"none"}})]}),s.jsx("button",{type:"submit",className:"login-submit",disabled:!e.trim(),style:{width:"100%",padding:"11px",background:e.trim()?"linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-cyan) 100%)":"var(--bg-hover)",color:e.trim()?"var(--bg-primary)":"var(--text-secondary)",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:e.trim()?"pointer":"not-allowed",letterSpacing:"0.3px"},children:"Connect"})]}),s.jsx("div",{style:{marginTop:"28px",textAlign:"center",color:"var(--scrollbar-thumb-hover)",fontSize:"11px"},children:s.jsxs("p",{children:["Token is configured in"," ",s.jsx("code",{style:{backgroundColor:"var(--bg-primary)",padding:"2px 6px",borderRadius:"4px",border:"1px solid var(--border)",fontSize:"11px"},children:"server/.env"})]})})]})})}const rt=new Map;function wr(e,t,n){rt.set(e,{onChunk:t,onControl:n})}function Sr(e){rt.delete(e)}function kr(e,t){var n;(n=rt.get(e))==null||n.onChunk(t)}function Tr(e,t){var n;(n=rt.get(e))==null||n.onControl(t)}const Cr=1,Lt=2,Er=3,Ir=4,jr=5,Rr=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`,Ke=500,Nr=8e3,Lr=1e4,Dt=4e3,Dr=5e3,Mr=10,Ar=64*1024,zr=new TextDecoder,_r=new TextEncoder;function Mt(e,t){const n=_r.encode(t),r=new Uint8Array(1+n.length);return r[0]=e,r.set(n,1),r.buffer}function $r(e,t,n){const r=a.useRef(null),o=a.useRef(Ke),c=a.useRef(null),i=a.useRef(null),d=a.useRef(null),p=a.useRef(null),l=a.useRef(!1),u=a.useRef(n),f=a.useRef(!1),h=a.useRef(0),g=a.useRef(!0),x=a.useRef(!navigator.onLine),R=a.useRef(""),C=a.useRef(null),j=a.useRef("");u.current=n;const S=a.useCallback(()=>{i.current&&(clearInterval(i.current),i.current=null),d.current&&(clearTimeout(d.current),d.current=null),c.current&&(clearTimeout(c.current),c.current=null),p.current&&(clearTimeout(p.current),p.current=null),C.current&&(clearTimeout(C.current),C.current=null)},[]),w=a.useCallback(()=>{var W;const{token:F,setTerminalError:O}=_.getState();if(!F||l.current)return;if(r.current){const U=r.current.readyState;if(U===WebSocket.OPEN||U===WebSocket.CONNECTING)return}f.current=!1;const D=(W=_.getState().terminalsMap[t])==null?void 0:W.startCwd;let T=`${Rr}?sessionId=${encodeURIComponent(t)}`;D&&(T+=`&cwd=${encodeURIComponent(D)}`);const y=new WebSocket(T);y.binaryType="arraybuffer",p.current=window.setTimeout(()=>{y.readyState===WebSocket.CONNECTING&&y.close()},Dr);const G=()=>{y.readyState===WebSocket.OPEN&&(h.current=performance.now(),y.send(JSON.stringify({type:"ping"})),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,y.close())},Dt))};y.onopen=()=>{p.current&&(clearTimeout(p.current),p.current=null),y.send(JSON.stringify({type:"auth",token:F})),O(t,null),o.current=Ke,g.current=!0},y.onclose=U=>{const{setTerminalConnected:V,setTerminalError:z,setToken:L}=_.getState();if(V(t,!1),S(),f.current)return;if(U.code===4001){l.current=!0,z(t,"Authentication failed"),L(null),localStorage.removeItem("ai-cli-online-token");return}if(U.code===4002)return;if(U.code===4005){z(t,"Connection limit reached");return}if(!navigator.onLine){x.current=!0;return}if(g.current){g.current=!1,c.current=window.setTimeout(()=>w(),50);return}const M=o.current;o.current=Math.min(M*2,Nr);const H=Math.round(M*(.5+Math.random()));c.current=window.setTimeout(()=>{w()},H)},y.onerror=()=>{},y.onmessage=U=>{var V;try{const z=e.current;if(U.data instanceof ArrayBuffer){const M=new Uint8Array(U.data);if(M.length<1)return;const H=M[0],X=M.subarray(1);switch(H){case Cr:z==null||z.write(X);break;case Er:z==null||z.write(X);break;case Ir:{(V=u.current)==null||V.call(u,zr.decode(X));break}case jr:{kr(t,X);break}}return}const L=JSON.parse(U.data);switch(L.type){case"connected":{const M=_.getState();M.setTerminalConnected(t,!0),M.setTerminalResumed(t,L.resumed);const H=e.current;H&&y.readyState===WebSocket.OPEN&&y.send(JSON.stringify({type:"resize",cols:H.cols,rows:H.rows})),j.current&&(y.send(Mt(Lt,j.current)),j.current=""),G(),i.current=window.setInterval(G,Lr);break}case"error":_.getState().setTerminalError(t,L.error);break;case"pong":{if(d.current&&(clearTimeout(d.current),d.current=null),h.current>0){const M=Math.round(performance.now()-h.current),H=_.getState();(H.terminalIds.length===0||H.terminalIds[0]===t)&&H.setLatency(M),h.current=0}break}case"file-stream-start":case"file-stream-end":case"file-stream-error":Tr(t,L);break}}catch{}},r.current=y},[t,e,S]),k=a.useCallback(F=>{const O=r.current;if(!O||O.readyState!==WebSocket.OPEN){j.current.length<Ar&&(j.current+=F);return}R.current+=F,C.current||(C.current=window.setTimeout(()=>{const D=R.current;R.current="",C.current=null,D&&O.readyState===WebSocket.OPEN&&O.send(Mt(Lt,D))},Mr))},[]),A=a.useCallback((F,O)=>{var D;((D=r.current)==null?void 0:D.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"resize",cols:F,rows:O}))},[]),P=a.useCallback(()=>{var F;((F=r.current)==null?void 0:F.readyState)===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"capture-scrollback"}))},[]),B=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}))},[]),$=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(()=>{_.getState().token&&(l.current=!1,w());const O=()=>{x.current=!1,o.current=Ke,g.current=!0;const y=r.current;(!y||y.readyState===WebSocket.CLOSED||y.readyState===WebSocket.CLOSING)&&w()},D=()=>{x.current=!0},T=()=>{if(document.visibilityState!=="visible")return;const y=r.current;if(!y||y.readyState!==WebSocket.OPEN){!x.current&&!f.current&&(o.current=Ke,g.current=!0,w());return}h.current=performance.now(),y.send(JSON.stringify({type:"ping"})),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{h.current>0&&(h.current=0,y.close())},Dt)};return window.addEventListener("online",O),window.addEventListener("offline",D),document.addEventListener("visibilitychange",T),()=>{f.current=!0,S(),window.removeEventListener("online",O),window.removeEventListener("offline",D),document.removeEventListener("visibilitychange",T),r.current&&(r.current.close(),r.current=null)}},[w,S,t]),{sendInput:k,sendResize:A,requestScrollback:P,requestFileStream:B,cancelFileStream:$}}function Or(e){const t=a.useRef(null),n=a.useRef(null),r=a.useRef(e);r.current=e;const o=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null),t.current&&(t.current.remove(),t.current=null)},[]),c=a.useCallback((i,d)=>{o();const p=document.createElement("div");p.style.cssText=`position:fixed;left:${i}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 l=document.createElement("textarea");l.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;",l.placeholder="Ctrl+V",l.addEventListener("paste",u=>{var h;u.preventDefault();const f=(h=u.clipboardData)==null?void 0:h.getData("text/plain");f&&r.current(f),o()}),l.addEventListener("keydown",u=>{u.key==="Escape"&&o()}),p.appendChild(l),document.body.appendChild(p),t.current=p,requestAnimationFrame(()=>{const u=p.getBoundingClientRect();u.right>window.innerWidth&&(p.style.left=`${window.innerWidth-u.width-8}px`),u.bottom>window.innerHeight&&(p.style.top=`${window.innerHeight-u.height-8}px`),l.focus()}),n.current=setTimeout(o,8e3)},[o]);return a.useEffect(()=>{const i=()=>{t.current&&o()};return document.addEventListener("click",i),()=>{document.removeEventListener("click",i),o()}},[o]),{showPasteFloat:c,removePasteFloat:o}}const Ye={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"},Xe={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"},pn="'JetBrains Mono', 'LXGW WenKai Mono', Menlo, Monaco, 'Courier New', monospace",Pr=a.forwardRef(function({sessionId:t},n){const r=a.useRef(null),o=a.useRef(null),c=a.useRef(null),[i,d]=a.useState(!1),[p,l]=a.useState(""),u=_(A=>A.fontSize),f=_(A=>A.theme),h=a.useCallback(A=>{l(A),d(!0)},[]),{sendInput:g,sendResize:x,requestScrollback:R,requestFileStream:C,cancelFileStream:j}=$r(o,t,h);a.useImperativeHandle(n,()=>({sendInput:g,requestFileStream:C,cancelFileStream:j}),[g,C,j]);const S=a.useRef(g),w=a.useRef(x);S.current=g,w.current=x;const{removePasteFloat:k}=Or(A=>S.current(A));return a.useEffect(()=>{if(!r.current)return;let A=!1,P=null,B=null,$=null,F=null;if(A||!r.current)return;const O=new Qt({cursorBlink:!0,scrollback:1e4,fontSize:_.getState().fontSize,fontFamily:pn,theme:_.getState().theme==="dark"?Ye:Xe,allowProposedApi:!0}),D=new en;O.loadAddon(D),O.loadAddon(new jn((L,M)=>{window.open(M,"_blank","noopener,noreferrer")})),O.open(r.current);try{const L=new tn;L.onContextLoss(()=>{L.dispose()}),O.loadAddon(L)}catch{}o.current=O,c.current=D,O.onSelectionChange(()=>{const L=O.getSelection();L&&navigator.clipboard.writeText(L).catch(()=>{})});const T=O.element,y=L=>{var M;L.preventDefault(),k(),(M=navigator.clipboard)!=null&&M.readText&&navigator.clipboard.readText().then(H=>{H&&S.current(H)}).catch(()=>{})};T&&T.addEventListener("contextmenu",y);const G=()=>{try{const L=r.current;if(L&&L.clientWidth>0&&L.clientHeight>0)return D.fit(),w.current(O.cols,O.rows),!0}catch{}return!1};requestAnimationFrame(()=>G());let W=0;P=setInterval(()=>{W++,(G()||W>=10)&&(clearInterval(P),P=null)},100),document.fonts.ready.then(()=>{if(!A)try{D.fit(),w.current(O.cols,O.rows)}catch{}});let U=null;const V=()=>{A||(U&&clearTimeout(U),U=setTimeout(()=>{if(!A)try{D.fit(),w.current(O.cols,O.rows)}catch{}},100))};document.fonts.addEventListener("loadingdone",V),O.onData(L=>{S.current(L)});let z=!1;return F=new ResizeObserver(()=>{if(document.body.classList.contains("resizing-panes")||document.body.classList.contains("resizing-panes-v")){if(!z){z=!0;const M=()=>{document.removeEventListener("mouseup",M),z=!1,requestAnimationFrame(()=>{try{D.fit(),w.current(O.cols,O.rows)}catch{}})};document.addEventListener("mouseup",M)}return}B||(B=requestAnimationFrame(()=>{B=null;try{D.fit(),$&&clearTimeout($),$=setTimeout(()=>{$=null,w.current(O.cols,O.rows)},50)}catch{}}))}),F.observe(r.current),()=>{A=!0,P&&clearInterval(P),B&&cancelAnimationFrame(B),$&&clearTimeout($),U&&clearTimeout(U),document.fonts.removeEventListener("loadingdone",V),F&&F.disconnect(),k(),T&&T.removeEventListener("contextmenu",y),o.current&&(o.current.dispose(),o.current=null),c.current=null}},[t]),a.useEffect(()=>{const A=o.current,P=c.current;if(!(!A||!P)&&A.options.fontSize!==u){A.options.fontSize=u;try{P.fit()}catch{}w.current(A.cols,A.rows)}},[u]),a.useEffect(()=>{o.current&&(o.current.options.theme=f==="dark"?Ye:Xe)},[f]),s.jsxs("div",{style:{width:"100%",height:"100%",position:"relative"},children:[s.jsx("div",{ref:r,style:{width:"100%",height:"100%",backgroundColor:"var(--bg-primary)",contain:"strict",willChange:"transform",isolation:"isolate"}}),s.jsx("button",{tabIndex:-1,onClick:A=>{A.currentTarget.blur(),i?(d(!1),l("")):R()},title:"Toggle scrollback history",style:{position:"absolute",top:4,right:4,zIndex:10,background:i?"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:A=>{A.currentTarget.style.opacity="1"},onMouseLeave:A=>{A.currentTarget.style.opacity="0.8"},children:i?"✕":s.jsx("span",{style:{fontSize:14},children:"👁"})}),i&&s.jsx(Fr,{data:p,onClose:()=>{d(!1),l("")}})]})});function Fr({data:e,onClose:t}){const n=a.useRef(null),r=a.useRef(t);r.current=t;const o=_(l=>l.fontSize),c=_(l=>l.theme),i=a.useRef(null),d=a.useRef(null);a.useEffect(()=>{if(!n.current)return;const l=new Qt({cursorBlink:!1,disableStdin:!0,scrollback:5e4,fontSize:o,fontFamily:pn,theme:c==="dark"?Ye:Xe});i.current=l;const u=new en;d.current=u,l.loadAddon(u),l.open(n.current);let f=null;try{f=new tn,f.onContextLoss(()=>{f==null||f.dispose(),f=null}),l.loadAddon(f)}catch{f=null}l.onSelectionChange(()=>{const j=l.getSelection();j&&navigator.clipboard.writeText(j).catch(()=>{})}),l.attachCustomKeyEventHandler(j=>(j.key==="Escape"&&r.current(),!1)),l.write(e);let h=null;const g=()=>{const j=n.current;if(!j||j.clientWidth<=0||j.clientHeight<=0)return!1;try{return u.fit(),l.scrollToBottom(),!0}catch{return!1}};requestAnimationFrame(()=>{if(!g()){let j=0;h=setInterval(()=>{j++,(g()||j>=30)&&(clearInterval(h),h=null)},50)}});let x=null;const R=new ResizeObserver(()=>{x||(x=requestAnimationFrame(()=>{x=null,g()}))});R.observe(n.current);const C=j=>{j.key==="Escape"&&r.current()};return document.addEventListener("keydown",C),()=>{if(h&&clearInterval(h),x&&cancelAnimationFrame(x),document.removeEventListener("keydown",C),R.disconnect(),f){try{f.dispose()}catch{}f=null}l.dispose(),i.current=null,d.current=null}},[e]),a.useEffect(()=>{var l;if(i.current){i.current.options.fontSize=o;try{(l=d.current)==null||l.fit()}catch{}}},[o]),a.useEffect(()=>{i.current&&(i.current.options.theme=c==="dark"?Ye:Xe)},[c]);const p=28;return s.jsxs("div",{style:{position:"absolute",inset:0,zIndex:5,backgroundColor:"var(--bg-primary)"},children:[s.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:s.jsx("span",{children:"Scrollback History (mouse wheel to scroll, ESC to close)"})}),s.jsx("div",{ref:n,style:{position:"absolute",top:p,left:0,right:0,bottom:0,overflow:"hidden"}})]})}const Br=50;function mt(){const e=a.useRef([]),t=a.useCallback(o=>{e.current.push(o),e.current.length>Br&&e.current.shift()},[]),n=a.useCallback(()=>e.current.pop(),[]),r=a.useCallback(()=>{e.current=[]},[]);return a.useMemo(()=>({pushUndo:t,popUndo:n,clearUndo:r}),[t,n,r])}function ht(e,t,n){e.preventDefault();const r=e.currentTarget,o=r.selectionStart,c=r.selectionEnd,i=r.value;n==null||n(i);const d=i.slice(0,o)+" "+i.slice(c);t(d),requestAnimationFrame(()=>{r.selectionStart=r.selectionEnd=o+2})}function Ze(e,t=20){var n;return Math.min(t,Math.max(1,(((n=e.match(/\n/g))==null?void 0:n.length)??0)+1))}let Ee=null,mn="dark";const Ur=["https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs","https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs"],Wr={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"},Hr={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"},Kr={titleTopMargin:15,barHeight:24,barGap:6,topPadding:40,numberSectionStyles:4,useWidth:800};function At(e,t){return mn=t,e.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:t==="dark"?Wr:Hr,gantt:Kr}),e}function Jr(e="dark"){return Ee?mn!==e?Ee.then(t=>At(t,e)):Ee:(Ee=(async()=>{for(const t of Ur)try{const n=await import(t);return At(n.default,e)}catch{}throw Ee=null,new Error("All mermaid CDN sources failed")})(),Ee)}let zt=0;function Gr(e,t,n="dark"){const r=a.useRef(n);a.useEffect(()=>{const o=e.current;if(!o)return;const c=r.current!==n;r.current=n;const i=o.querySelectorAll("code.language-mermaid, code.language-gantt"),d=c?o.querySelectorAll(".mermaid-diagram[data-mermaid-source]"):[];if(i.length===0&&d.length===0)return;let p=!1;return(async()=>{let l;try{l=await Jr(n)}catch{if(p)return;for(const f of i){const h=f.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 u of d){if(p)break;const f=u.getAttribute("data-mermaid-source");if(!f)continue;const h=`mermaid-${++zt}`;try{const{svg:g}=await l.render(h,f);if(p)break;u.innerHTML=ut.sanitize(g,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]})}catch{}}for(const u of i){if(p)break;const f=u.parentElement;if(!f||f.tagName!=="PRE")continue;const h=u.textContent||"";if(!h.trim())continue;const g=`mermaid-${++zt}`;try{const{svg:x}=await l.render(g,h);if(p)break;const R=document.createElement("div");R.className="mermaid-diagram",R.setAttribute("data-mermaid-source",h),R.innerHTML=ut.sanitize(x,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["foreignObject"]}),f.replaceWith(R)}catch{if(p)break;f.classList.add("mermaid-error");const x=document.createElement("div");x.className="mermaid-error__msg",x.textContent="Mermaid syntax error",f.appendChild(x)}}}})(),()=>{p=!0}},[t,n])}async function Vr(e,t,n){const r=await ne.get(e,t,"annotations",{path:n});return r.content?{content:r.content,updatedAt:r.updatedAt}:null}async function hn(e,t,n,r,o){await ne.put(e,t,"annotations",{path:n,content:r,updatedAt:o})}async function _t(e,t,n,r){return ne.post(e,t,"task-annotations",{modulePath:n,content:r})}const gt={additions:[],deletions:[],replacements:[],comments:[]};let qr=0;function ce(){return`ann_${++qr}_${Date.now()}`}function _e(e,t){return`plan-annotations-${e}-${t}`}function $t(e,t){return`plan-scroll-${e}-${t}`}function Yr(e){const t=String(nn.parser([e],{async:!1}));return ut.sanitize(t,{ADD_TAGS:["img"],ADD_ATTR:["src","alt","title","width","height"]})}function Je(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++){const o=e[r].raw??"";for(const c of o)c===`
26
- `&&n++}return n}function Ge(e,t,n,r){const o=e.join(`
27
- `);let c=0;for(let g=0;g<t-1&&g<e.length;g++)c+=e[g].length+1;let i=0;for(let g=0;g<n&&g<e.length;g++)i+=e[g].length+1;let d=c,p=Math.min(o.length,i);if(r){const g=Math.max(0,c-10),x=Math.min(o.length,i+10),C=o.slice(g,x).indexOf(r);C>=0&&(d=g+C,p=d+r.length)}const l=Math.max(0,d-20),u=o.slice(l,d).replace(/\n/g,"↵"),f=Math.min(o.length,p+20),h=o.slice(p,f).replace(/\n/g,"↵");return{before:u,after:h}}function Ot(e,t){const n=[],r=[],o=[],c=[];for(const i of e.additions){const{before:d,after:p}=Ge(t,i.sourceLine,i.sourceLine);n.push([`Line${i.sourceLine}:...${d}`,i.content,`${p}...`])}for(const i of e.deletions){const{before:d,after:p}=Ge(t,i.startLine,i.endLine,i.selectedText);r.push([`Line${i.startLine}:...${d}`,i.selectedText,`${p}...`])}for(const i of e.replacements){const{before:d,after:p}=Ge(t,i.startLine,i.endLine,i.selectedText);o.push([`Line${i.startLine}:...${d}`,i.selectedText,i.content,`${p}...`])}for(const i of e.comments){const{before:d,after:p}=Ge(t,i.startLine,i.endLine,i.selectedText);c.push([`Line${i.startLine}:...${d}`,i.selectedText,i.content,`${p}...`])}return{"Insert Annotations":n,"Delete Annotations":r,"Replace Annotations":o,"Comment Annotations":c}}function Pt(e){return e.additions.length>0||e.deletions.length>0||e.replacements.length>0||e.comments.length>0}function Ft(e){return/^[a-zA-Z0-9_./:@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function Bt(e,t){return`/ai-cli-task plan ${Ft(e)} ${Ft(t)} --silent`}function Ut(e){const t=e.split("/"),n=t.indexOf("AiTasks");return n>=0&&n+1<t.length?t.slice(0,n+2).join("/"):e.substring(0,e.lastIndexOf("/"))}function Qe(e){const t=new Set;return e.additions.forEach(n=>t.add(n.id)),e.deletions.forEach(n=>t.add(n.id)),e.replacements.forEach(n=>t.add(n.id)),e.comments.forEach(n=>t.add(n.id)),t}function Wt(e){return e.replacements||(e.replacements=[]),e.comments||(e.comments=[]),e}function Xr({sessionId:e,filePath:t,token:n,annotations:r,annLoadedRef:o,setAnnotations:c,baselineIdsRef:i}){const d=_(f=>f.latency),p=a.useRef(void 0),l=a.useRef(void 0),u=a.useRef(!1);a.useEffect(()=>{if(!o.current)return;const f=_e(e,t),h=JSON.stringify(r);p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{try{localStorage.setItem(f,h)}catch{}},50),l.current&&clearTimeout(l.current);const g=Math.max(200,(d??30)*3);return l.current=setTimeout(()=>{u.current||(u.current=!0,hn(n,e,t,h,Date.now()).catch(()=>{}).finally(()=>{u.current=!1}))},g),()=>{p.current&&clearTimeout(p.current),l.current&&clearTimeout(l.current)}},[r,e,t,n,d,o]),a.useEffect(()=>{o.current=!1;let f=gt,h=0;try{const x=localStorage.getItem(_e(e,t));x&&(f=Wt(JSON.parse(x)),h=Date.now())}catch{}c(f),i.current=Qe(f);let g=!1;return Vr(n,e,t).then(x=>{if(!g&&x&&x.updatedAt>h)try{const R=Wt(JSON.parse(x.content));c(R);try{localStorage.setItem(_e(e,t),x.content)}catch{}i.current=Qe(R)}catch{}}).catch(()=>{}).finally(()=>{o.current=!0}),o.current=!0,()=>{g=!0}},[e,t,n,o,c,i])}function gn(e,t){let n=e.replace(/<[^>]*>/g,"").trim().toLowerCase().replace(/\s+/g,"-").replace(/[&<>"'`]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");n||(n="heading");const r=t.get(n)||0;return r>0&&(n=`${n}-${r}`),t.set(n,r+1),n}function bn(e){return e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.*?\)/g,"$1").trim()}function Zr(e){if(!e)return[];const t=[],n=new Map,r=e.split(`
28
- `);let o=!1;for(const c of r){if(/^```/.test(c.trim())){o=!o;continue}if(o)continue;const i=c.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if(i){const d=i[1].length,p=bn(i[2]),l=gn(p,n);t.push({id:l,text:p,level:d})}}return t}const Qr=160,eo=22;function to({headings:e,scrollRef:t}){const[n,r]=a.useState(null),[o,c]=a.useState(()=>localStorage.getItem("md-toc-collapsed")==="true"),i=a.useRef(null),d=a.useRef(!1),p=a.useMemo(()=>Math.min(...e.map(f=>f.level)),[e]),l=a.useCallback(()=>{c(f=>{const h=!f;try{localStorage.setItem("md-toc-collapsed",String(h))}catch{}return h})},[]);a.useEffect(()=>{const f=t.current;if(!f||e.length===0)return;const h=()=>{d.current=!1;const x=f.scrollTop,R=50;let C=null;for(const j of e){const S=f.querySelector(`[id="${CSS.escape(j.id)}"]`);S&&S.offsetTop<=x+R&&(C=j.id)}r(C)},g=()=>{d.current||(d.current=!0,requestAnimationFrame(h))};return h(),f.addEventListener("scroll",g,{passive:!0}),()=>f.removeEventListener("scroll",g)},[e,t]);const u=a.useCallback(f=>{const h=t.current;if(!h)return;const g=h.querySelector(`[id="${CSS.escape(f)}"]`);g&&(g.scrollIntoView({behavior:"smooth",block:"start"}),r(f))},[t]);return a.useEffect(()=>{if(!n||o)return;const f=i.current;if(!f)return;const h=f.querySelector(`[data-toc-id="${CSS.escape(n)}"]`);if(h){const g=h.offsetTop-f.offsetTop,x=g+h.offsetHeight;(g<f.scrollTop||x>f.scrollTop+f.clientHeight)&&h.scrollIntoView({block:"nearest"})}},[n,o]),e.length<2?null:o?s.jsx("div",{style:{width:eo,flexShrink:0,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:4,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{onClick:l,title:"Show table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:13,cursor:"pointer",padding:"2px",lineHeight:1},onMouseEnter:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"☰"})}):s.jsxs("div",{ref:i,style:{width:Qr,flexShrink:0,borderLeft:"1px solid var(--border)",backgroundColor:"var(--bg-secondary)",overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{fontSize:10,color:"var(--border)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Contents"}),s.jsx("button",{onClick:l,title:"Hide table of contents",style:{background:"none",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:"0 2px",lineHeight:1},onMouseEnter:f=>{f.currentTarget.style.color="var(--accent-blue)"},onMouseLeave:f=>{f.currentTarget.style.color="var(--text-secondary)"},children:"»"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0"},children:e.map((f,h)=>s.jsx("div",{"data-toc-id":f.id,onClick:()=>u(f.id),style:{padding:`2px 6px 2px ${(f.level-p)*10+6}px`,fontSize:11,lineHeight:1.5,color:n===f.id?"var(--accent-blue)":"var(--text-secondary)",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderLeft:n===f.id?"2px solid var(--accent-blue)":"2px solid transparent",fontWeight:f.level<=2?500:400,transition:"color 0.1s"},title:f.text,onMouseEnter:g=>{n!==f.id&&(g.currentTarget.style.color="var(--text-primary)"),g.currentTarget.style.backgroundColor="var(--bg-tertiary)"},onMouseLeave:g=>{n!==f.id&&(g.currentTarget.style.color="var(--text-secondary)"),g.currentTarget.style.backgroundColor="transparent"},children:f.text},`${f.id}-${h}`))})]})}const no={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 ro({annotations:e,annCounts:t,isSent:n,onSendAll:r,onSendSingle:o,onDelete:c}){const[i,d]=a.useState(!1),p=a.useRef(null);a.useEffect(()=>{if(!i)return;const f=h=>{p.current&&!p.current.contains(h.target)&&d(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i]);const l=a.useCallback((f,h,g)=>{const x=no[h],R=n(f);return s.jsxs("div",{className:`plan-anno-dropdown__item plan-anno-dropdown__item--${h}`,children:[s.jsx("span",{className:"plan-anno-dropdown__type",style:{color:x.color},children:x.symbol}),s.jsxs("span",{className:"plan-anno-dropdown__text",children:[g.slice(0,60),g.length>60?"...":""]}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!R&&o(f,h),disabled:R,title:R?"Already sent":"Send to terminal",style:R?{opacity:.3}:{color:"var(--accent-blue)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>c(f,h),title:"Delete",children:"×"})]},f)},[n,o,c]),u=(()=>{const f=e.additions[0],h=e.deletions[0],g=e.replacements[0],x=e.comments[0],R=f?f.content:h?h.selectedText:g?g.content:x?x.content:"";return R?R.slice(0,40)+(R.length>40?"...":""):""})();return s.jsxs("div",{ref:p,style:{position:"relative",flex:1,minWidth:0},children:[s.jsxs("div",{className:`plan-anno-dropdown-trigger${i?" plan-anno-dropdown-trigger--active":""}`,onClick:()=>d(f=>!f),title:t.total>0?`${t.total} annotations (${t.unsent} unsent)`:"No annotations",children:[s.jsx("span",{className:"plan-anno-dropdown-trigger__text",children:u}),s.jsx("span",{className:"plan-anno-dropdown-trigger__arrow",children:"▼"})]}),i&&s.jsxs("div",{className:"plan-anno-dropdown",children:[t.unsent>0&&s.jsx("div",{className:"plan-anno-dropdown__header",children:s.jsxs("button",{className:"pane-btn",onClick:r,style:{color:"var(--accent-blue)",fontSize:11},children:["Send All Unsent (",t.unsent,")"]})}),s.jsxs("div",{className:"plan-anno-dropdown__list",children:[e.additions.map(f=>l(f.id,"add",f.content)),e.deletions.map(f=>l(f.id,"del",f.selectedText)),e.replacements.map(f=>l(f.id,"rep",f.content)),e.comments.map(f=>l(f.id,"com",f.content)),t.total===0&&s.jsx("div",{className:"plan-anno-dropdown__empty",children:"No annotations"})]})]})]})}const oo={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 lt({type:e,annotation:t,fontSize:n,onEdit:r,onRemove:o,onSend:c,isSent:i}){const d=oo[e],[p,l]=a.useState(!1),[u,f]=a.useState(""),h=a.useRef(null),g=e==="del"?t.selectedText:t.content,x=a.useCallback(()=>{l(!0),f(g)},[g]),R=a.useCallback(()=>{const C=u.trim();C?r(t.id,C):o(t.id),l(!1)},[u,t.id,r,o]);return a.useEffect(()=>{p&&requestAnimationFrame(()=>{const C=h.current;C&&(C.focus(),C.selectionStart=C.selectionEnd=C.value.length)})},[p]),p?s.jsx("div",{className:d.className,children:s.jsx("textarea",{ref:h,className:"plan-annotation-textarea",value:u,onChange:C=>f(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.ctrlKey||C.metaKey)&&(C.preventDefault(),R()),C.key==="Escape"&&(C.preventDefault(),l(!1))},onBlur:R,rows:Ze(u),style:{fontSize:`${n}px`,flex:1}})}):s.jsxs("div",{className:d.className,children:[d.icon&&s.jsx("span",{style:{color:d.color,flexShrink:0},children:d.icon}),e==="del"?s.jsx("span",{style:{flex:1,fontSize:`${n}px`,color:d.color,textDecoration:"line-through",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:t.selectedText}):e==="rep"?s.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsx("span",{style:{color:"var(--accent-red)",textDecoration:"line-through"},children:t.selectedText}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:" → "}),s.jsx("span",{style:{color:"var(--accent-blue)"},children:t.content})]}):s.jsxs("span",{style:{flex:1,fontSize:`${n}px`,whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:x,title:"Double-click to edit",children:[s.jsxs("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:['"',t.selectedText,'"']}),s.jsx("span",{style:{color:"var(--text-secondary)"},children:": "}),s.jsx("span",{style:{color:"var(--accent-green)"},children:t.content})]}),c&&s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!i&&c(t.id),disabled:i,title:i?"Already sent":"Send to terminal",style:i?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:x,style:{color:"var(--accent-blue)"},title:`Edit ${e==="del"?"deletion":e==="rep"?"replacement":"comment"}`,children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>o(t.id),title:`Remove ${e==="del"?"deletion":e==="rep"?"replacement":"comment"}`,children:"×"})]})}function so({x:e,y:t,onDelete:n,onReplace:r,onComment:o}){return s.jsxs("div",{className:"plan-selection-float",style:{top:t,left:e},children:[s.jsx("button",{className:"plan-selection-float__delete",onMouseDown:c=>{c.preventDefault(),n()},title:"Delete selection",children:"−"}),s.jsx("button",{className:"plan-selection-float__replace",onMouseDown:c=>{c.preventDefault(),r()},title:"Replace selection",children:"⇄"}),s.jsx("button",{className:"plan-selection-float__comment",onMouseDown:c=>{c.preventDefault(),o()},title:"Comment on selection",children:"?"})]})}const ao=a.forwardRef(function({markdown:t,filePath:n,sessionId:r,token:o,onExecute:c,onSend:i,onRefresh:d,onClose:p,expanded:l,readOnly:u},f){const h=_(m=>m.fontSize),g=a.useMemo(()=>t?nn.lexer(t):[],[t]),x=a.useMemo(()=>t.split(`
29
- `),[t]),R=a.useMemo(()=>Zr(t),[t]),C=a.useMemo(()=>{const m=new Map,b=new Map;return g.forEach((N,E)=>{if(N.type==="heading"){const J=bn(N.text||""),K=gn(J,b);m.set(E,K)}}),m},[g]),j=a.useRef(new Set),S=a.useRef(!1),[w,k]=a.useState(()=>{try{const m=localStorage.getItem(_e(r,n)),b=m?JSON.parse(m):gt;return j.current=Qe(b),b.replacements||(b.replacements=[]),b.comments||(b.comments=[]),b}catch{return gt}});Xr({sessionId:r,filePath:n,token:o,annotations:w,annLoadedRef:S,setAnnotations:k,baselineIdsRef:j});const[A,P]=a.useState(0),B=a.useMemo(()=>{const m=j.current,b=w.additions.length+w.deletions.length+w.replacements.length+w.comments.length;let N=0;return w.additions.forEach(E=>{m.has(E.id)&&N++}),w.deletions.forEach(E=>{m.has(E.id)&&N++}),w.replacements.forEach(E=>{m.has(E.id)&&N++}),w.comments.forEach(E=>{m.has(E.id)&&N++}),{total:b,sent:N,unsent:b-N}},[w,A]),[$,F]=a.useState(null),[O,D]=a.useState(""),T=a.useRef(null),[y,G]=a.useState(null),[W,U]=a.useState(""),V=a.useRef(null),[z,L]=a.useState(null),M=a.useRef(null),H=a.useRef(0),X=a.useRef(null);a.useEffect(()=>{const m=M.current;if(!m)return;let b;const N=()=>{clearTimeout(b),b=setTimeout(()=>{const E=$t(r,n);if(m.scrollTop>0)try{localStorage.setItem(E,String(m.scrollTop))}catch{}else localStorage.removeItem(E)},50)};return m.addEventListener("scroll",N,{passive:!0}),()=>{clearTimeout(b),m.removeEventListener("scroll",N)}},[r,n]),a.useEffect(()=>{if(!g.length)return;const m=localStorage.getItem($t(r,n));if(!m)return;const b=Number(m),N=M.current;if(!N||(N.scrollTop=b,N.scrollTop>=b-10))return;let E;const J=()=>{N.scrollTop=b,K.disconnect()},K=new MutationObserver(()=>{clearTimeout(E),E=setTimeout(J,80)});K.observe(N,{childList:!0,subtree:!0});const q=setTimeout(J,500);return()=>{clearTimeout(E),clearTimeout(q),K.disconnect()}},[r,n,g.length]),a.useEffect(()=>{$!=null&&requestAnimationFrame(()=>{var m;return(m=T.current)==null?void 0:m.focus()})},[$]),a.useEffect(()=>{y&&requestAnimationFrame(()=>{var m;return(m=V.current)==null?void 0:m.focus()})},[y]);const Y=a.useRef({annotations:w,activeInsert:$,insertText:O,pendingAction:y,pendingText:W,tokens:g,filePath:n,sessionId:r,token:o});Y.current={annotations:w,activeInsert:$,insertText:O,pendingAction:y,pendingText:W,tokens:g,filePath:n,sessionId:r,token:o},a.useEffect(()=>()=>{const m=Y.current;let b=m.annotations,N=!1;if(m.activeInsert!=null&&m.insertText.trim()){const E=Je(m.tokens,m.activeInsert+1);b={...b,additions:[...b.additions,{id:ce(),afterTokenIndex:m.activeInsert,sourceLine:E,content:m.insertText.trim()}]},N=!0}if(m.pendingAction&&m.pendingText.trim()){const E=m.pendingAction,J=m.pendingText.trim();E.type==="replace"?b={...b,replacements:[...b.replacements,{id:ce(),tokenIndices:E.tokenIndices,startLine:E.startLine,endLine:E.endLine,selectedText:E.text,content:J}]}:b={...b,comments:[...b.comments,{id:ce(),tokenIndices:E.tokenIndices,startLine:E.startLine,endLine:E.endLine,selectedText:E.text,content:J}]},N=!0}if(N){const E=JSON.stringify(b);try{localStorage.setItem(_e(m.sessionId,m.filePath),E)}catch{}hn(m.token,m.sessionId,m.filePath,E,Date.now()).catch(()=>{})}},[]);const Z=a.useCallback(m=>{if(!O.trim()){F(null),D("");return}const b=Je(g,m+1);k(N=>({...N,additions:[...N.additions,{id:ce(),afterTokenIndex:m,sourceLine:b,content:O.trim()}]})),F(null),D("")},[O,g]),ue=a.useCallback(m=>{k(b=>({...b,additions:b.additions.filter(N=>N.id!==m)}))},[]),ye=a.useCallback((m,b)=>{k(N=>({...N,additions:N.additions.map(E=>E.id===m?{...E,id:ce(),content:b}:E)}))},[]),$e=a.useCallback(()=>{var m;z&&(k(b=>({...b,deletions:[...b.deletions,{id:ce(),tokenIndices:z.tokenIndices,startLine:z.startLine,endLine:z.endLine,selectedText:z.text.slice(0,80)}]})),L(null),(m=window.getSelection())==null||m.removeAllRanges())},[z]),Se=a.useCallback(m=>{var b;z&&(G({type:m,tokenIndices:z.tokenIndices,startLine:z.startLine,endLine:z.endLine,text:z.text.slice(0,80)}),U(""),L(null),(b=window.getSelection())==null||b.removeAllRanges())},[z]),se=a.useCallback(()=>{if(!y)return;const m=W.trim();if(!m){G(null),U("");return}y.type==="replace"?k(b=>({...b,replacements:[...b.replacements,{id:ce(),tokenIndices:y.tokenIndices,startLine:y.startLine,endLine:y.endLine,selectedText:y.text,content:m}]})):k(b=>({...b,comments:[...b.comments,{id:ce(),tokenIndices:y.tokenIndices,startLine:y.startLine,endLine:y.endLine,selectedText:y.text,content:m}]})),G(null),U("")},[y,W]),ve=a.useCallback(m=>{k(b=>({...b,replacements:b.replacements.filter(N=>N.id!==m)}))},[]),le=a.useCallback((m,b)=>{k(N=>({...N,replacements:N.replacements.map(E=>E.id===m?{...E,id:ce(),content:b}:E)}))},[]),re=a.useCallback(m=>{k(b=>({...b,comments:b.comments.filter(N=>N.id!==m)}))},[]),Oe=a.useCallback((m,b)=>{k(N=>({...N,comments:N.comments.map(E=>E.id===m?{...E,id:ce(),content:b}:E)}))},[]),ae=a.useCallback(m=>{k(b=>({...b,deletions:b.deletions.filter(N=>N.id!==m)}))},[]),Re=a.useCallback((m,b)=>{k(N=>({...N,deletions:N.deletions.map(E=>E.id===m?{...E,id:ce(),selectedText:b}:E)}))},[]),fe=a.useCallback(m=>{let b=m instanceof Element?m:m.parentElement;for(;b&&b!==M.current;){if(b.hasAttribute("data-token-index"))return b;b=b.parentElement}return null},[]),me=a.useCallback(()=>{const m=window.getSelection();if(!m||m.isCollapsed||!M.current){L(null);return}const b=m.toString().trim();if(!b){L(null);return}const N=m.getRangeAt(0);if(!M.current.contains(N.commonAncestorContainer)){L(null);return}const E=fe(N.startContainer),J=fe(N.endContainer);if(!E||!J){L(null);return}const K=parseInt(E.getAttribute("data-token-index")||"0",10),q=parseInt(J.getAttribute("data-token-index")||"0",10),Q=[];for(let at=Math.min(K,q);at<=Math.max(K,q);at++)Q.push(at);const ge=Je(g,Math.min(K,q)),Me=Je(g,Math.max(K,q)+1),Be=N.getBoundingClientRect(),st=M.current,yt=st.getBoundingClientRect();navigator.clipboard.writeText(b).catch(()=>{});const Ue=X.current,vt=Ue&&Date.now()-Ue.time<500;H.current=Date.now(),L({x:(vt?Ue.x:Be.right)-yt.left+st.scrollLeft+6,y:(vt?Ue.y:Be.top)-yt.top+st.scrollTop-44,tokenIndices:Q,startLine:ge,endLine:Me,text:b})},[g,fe]),he=a.useRef(void 0);a.useEffect(()=>{const m=()=>{he.current&&clearTimeout(he.current),he.current=setTimeout(()=>{const b=window.getSelection();if(!b||b.isCollapsed||!M.current){if(Date.now()-H.current<300)return;L(null);return}const N=b.anchorNode;N&&M.current.contains(N)&&me()},120)};return document.addEventListener("selectionchange",m),()=>{document.removeEventListener("selectionchange",m),he.current&&clearTimeout(he.current)}},[me]);const Pe=_(m=>m.theme);Gr(M,g,Pe);const ke=a.useCallback(()=>{const m=j.current;return{additions:w.additions.filter(b=>!m.has(b.id)),deletions:w.deletions.filter(b=>!m.has(b.id)),replacements:w.replacements.filter(b=>!m.has(b.id)),comments:w.comments.filter(b=>!m.has(b.id))}},[w]),Te=a.useCallback(async()=>{const m=ke();if(!Pt(m))return;const b=Ot(m,x),N=Ut(n);try{const{path:E}=await _t(o,r,N,b),J=Bt(n,E);c(J),j.current=Qe(w),P(K=>K+1)}catch{}},[ke,w,x,c,n,o,r]),de=a.useCallback(async(m,b)=>{if(!i)return;const N={additions:[],deletions:[],replacements:[],comments:[]};if(b==="add"){const K=w.additions.find(q=>q.id===m);if(!K)return;N.additions.push(K)}else if(b==="del"){const K=w.deletions.find(q=>q.id===m);if(!K)return;N.deletions.push(K)}else if(b==="rep"){const K=w.replacements.find(q=>q.id===m);if(!K)return;N.replacements.push(K)}else{const K=w.comments.find(q=>q.id===m);if(!K)return;N.comments.push(K)}const E=Ot(N,x),J=Ut(n);try{const{path:K}=await _t(o,r,J,E);i(Bt(n,K)),j.current.add(m),P(q=>q+1)}catch{}},[i,n,w,x,o,r]),Ne=a.useCallback((m,b)=>{b==="add"?ue(m):b==="del"?ae(m):b==="rep"?ve(m):re(m)},[ue,ae,ve,re]);a.useImperativeHandle(f,()=>({getSummary:()=>{const m=ke();return Pt(m)?"[pending annotations]":""},handleEscape:()=>y?(se(),!0):$!=null?(Z($),!0):!1,getScrollTop:()=>{var m;return((m=M.current)==null?void 0:m.scrollTop)??0},setScrollTop:m=>{requestAnimationFrame(()=>{M.current&&(M.current.scrollTop=m)})}}),[ke,$,Z,y,se]);const Le=a.useMemo(()=>{const m=new Set;return w.deletions.forEach(b=>b.tokenIndices.forEach(N=>m.add(N))),m},[w.deletions]),De=a.useMemo(()=>{const m=new Set;return w.replacements.forEach(b=>b.tokenIndices.forEach(N=>m.add(N))),m},[w.replacements]),ot=a.useMemo(()=>{const m=new Set;return w.comments.forEach(b=>b.tokenIndices.forEach(N=>m.add(N))),m},[w.comments]),Fe=a.useMemo(()=>{const m=new Map;return w.additions.forEach(b=>{const N=m.get(b.afterTokenIndex)||[];N.push(b),m.set(b.afterTokenIndex,N)}),m},[w.additions]),v=B.unsent>0,I=a.useCallback(m=>j.current.has(m),[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[s.jsxs("div",{className:"plan-anno-toolbar",children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:n,children:n.split("/").pop()||n}),d&&s.jsx("button",{className:"pane-btn",onClick:d,title:"Refresh current file",children:"↻"}),s.jsx("button",{className:"pane-btn",onClick:Te,disabled:!v,title:"Send all annotations",style:v?{color:"var(--accent-green)"}:{opacity:.4},children:"Send"}),s.jsx(ro,{annotations:w,annCounts:B,isSent:I,onSendAll:Te,onSendSingle:de,onDelete:Ne}),p&&s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:async()=>{await Te(),p()},title:"Send annotations & close file",children:"×"})]}),s.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[s.jsxs("div",{ref:M,className:`plan-anno-content md-preview${$!=null?" plan-anno-content--editing":""}`,style:{flex:1,overflow:"auto",padding:"8px 12px",position:"relative",fontSize:`${h}px`,minWidth:0},onMouseUp:m=>{X.current={x:m.clientX,y:m.clientY,time:Date.now()},me()},children:[!u&&s.jsx(Ht,{index:-1,active:$===-1,additions:Fe.get(-1),onOpen:()=>{F(-1),D("")},onSubmit:()=>Z(-1),onRemoveAddition:ue,onEditAddition:ye,onSendSingle:i?m=>de(m,"add"):void 0,isSent:I,insertText:O,setInsertText:D,textareaRef:$===-1?T:void 0,expanded:l,alwaysShow:g.length===0,fontSize:h}),g.map((m,b)=>{const N=Yr(m);return s.jsxs("div",{children:[s.jsx("div",{"data-token-index":b,id:C.get(b),className:Le.has(b)?"plan-block--deleted":De.has(b)?"plan-block--replaced":ot.has(b)?"plan-block--commented":void 0,dangerouslySetInnerHTML:{__html:N}}),w.deletions.filter(E=>E.tokenIndices[0]===b).map(E=>s.jsx(lt,{type:"del",annotation:E,fontSize:h,onEdit:Re,onRemove:ae,onSend:i?J=>de(J,"del"):void 0,isSent:j.current.has(E.id)},E.id)),w.replacements.filter(E=>E.tokenIndices[0]===b).map(E=>s.jsx(lt,{type:"rep",annotation:E,fontSize:h,onEdit:le,onRemove:ve,onSend:i?J=>de(J,"rep"):void 0,isSent:j.current.has(E.id)},E.id)),w.comments.filter(E=>E.tokenIndices[0]===b).map(E=>s.jsx(lt,{type:"com",annotation:E,fontSize:h,onEdit:Oe,onRemove:re,onSend:i?J=>de(J,"com"):void 0,isSent:j.current.has(E.id)},E.id)),y&&y.tokenIndices[0]===b&&s.jsxs("div",{className:y.type==="replace"?"plan-replace-card":"plan-comment-card",style:{padding:"4px 8px"},children:[s.jsx("span",{style:{color:y.type==="replace"?"var(--accent-blue)":"var(--accent-green)",flexShrink:0},children:y.type==="replace"?"⇄":"?"}),s.jsx("textarea",{ref:V,className:"plan-annotation-textarea",value:W,onChange:E=>U(E.target.value),onKeyDown:E=>{if(E.key==="Enter"&&(E.ctrlKey||E.metaKey)){E.preventDefault(),se();return}if(E.key==="Escape"){E.preventDefault(),se();return}},onBlur:se,placeholder:y.type==="replace"?"Replace with... (Ctrl+Enter to save)":"Comment... (Ctrl+Enter to save)",rows:Ze(W),style:{fontSize:`${h}px`,flex:1}})]}),!u&&s.jsx(Ht,{index:b,active:$===b,additions:Fe.get(b),onOpen:()=>{F(b),D("")},onSubmit:()=>Z(b),onRemoveAddition:ue,onEditAddition:ye,onSendSingle:i?E=>de(E,"add"):void 0,isSent:I,insertText:O,setInsertText:D,textareaRef:$===b?T:void 0,expanded:l,fontSize:h})]},b)}),!u&&z&&s.jsx(so,{x:z.x,y:z.y,onDelete:$e,onReplace:()=>Se("replace"),onComment:()=>Se("comment")})]}),s.jsx(to,{headings:R,scrollRef:M})]})]})});function Ht({index:e,active:t,additions:n,onOpen:r,onSubmit:o,onRemoveAddition:c,onEditAddition:i,onSendSingle:d,isSent:p,insertText:l,setInsertText:u,textareaRef:f,expanded:h,alwaysShow:g,fontSize:x=14}){const[R,C]=a.useState(null),[j,S]=a.useState(""),w=a.useRef(null),k=mt(),A=mt();a.useEffect(()=>{R&&(k.clearUndo(),requestAnimationFrame(()=>{const D=w.current;D&&(D.focus(),D.selectionStart=D.selectionEnd=D.value.length)}))},[R]),a.useEffect(()=>{t&&A.clearUndo()},[t]);const P=a.useCallback(D=>{S(T=>(k.pushUndo(T),D))},[k]),B=a.useCallback(D=>{A.pushUndo(l),u(D)},[l,u,A]),$=a.useCallback(D=>{C(D.id),S(D.content)},[]),F=a.useCallback(()=>{if(!R)return;const D=j.trim();D?i(R,D):c(R),C(null),S("")},[R,j,i,c]),O=a.useCallback(()=>{C(null),S("")},[]);return s.jsxs("div",{className:`plan-insert-zone${g?" plan-insert-zone--empty":""}`,"data-zone-index":e,children:[n==null?void 0:n.map(D=>s.jsx("div",{className:"plan-annotation-card",children:R===D.id?s.jsx("textarea",{ref:w,className:"plan-annotation-textarea",value:j,onChange:T=>P(T.target.value),onKeyDown:T=>{if(T.key==="Enter"&&(T.ctrlKey||T.metaKey)){T.preventDefault(),F();return}if(T.key==="Escape"){T.preventDefault(),O();return}if(T.key==="Tab"){ht(T,P);return}},onBlur:F,rows:Ze(j),style:{fontSize:`${x}px`,flex:1,...h?{minWidth:300}:void 0}}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:`${x}px`,color:"var(--accent-yellow)",whiteSpace:"pre-wrap",cursor:"text"},onDoubleClick:()=>$(D),title:"Double-click to edit",children:D.content}),d&&(()=>{const T=(p==null?void 0:p(D.id))??!1;return s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>!T&&d(D.id),disabled:T,title:T?"Already sent":"Send to terminal",style:T?{opacity:.3}:{color:"var(--accent-green)"},children:"Send"})})(),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:()=>$(D),style:{color:"var(--accent-blue)"},title:"Edit annotation",children:"✎"}),s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm",onClick:()=>c(D.id),children:"×"})]})},D.id)),t?s.jsx("div",{className:"plan-annotation-card plan-annotation-card--editing",children:s.jsx("textarea",{ref:f,className:"plan-annotation-textarea",value:l,onChange:D=>B(D.target.value),onKeyDown:D=>{if(D.key==="Enter"&&(D.ctrlKey||D.metaKey)){D.preventDefault(),o();return}if(D.key==="Escape"){D.preventDefault(),o();return}if(D.key==="Tab"){ht(D,B);return}},onBlur:o,placeholder:"Add annotation... (Ctrl+Enter or Esc to save)",rows:Ze(l),style:{fontSize:`${x}px`,...h?{minWidth:300}:void 0}})}):g&&!(n!=null&&n.length)?s.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."}):s.jsx("button",{className:"plan-insert-btn",onClick:r,title:"Add annotation here",children:"+"})]})}async function be(e,t,n){const r=n?{path:n}:void 0;return ne.get(e,t,"files",r)}function co(e,t,n,r){return new Promise((o,c)=>{const i=new FormData;for(const p of n)i.append("files",p);const d=new XMLHttpRequest;d.open("POST",`${xe}/api/sessions/${encodeURIComponent(t)}/upload`),d.setRequestHeader("Authorization",`Bearer ${e}`),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?o():c(new Error(`Upload failed: ${d.status}`))}),d.addEventListener("error",()=>c(new Error("Upload network error"))),d.addEventListener("abort",()=>c(new Error("Upload aborted"))),d.send(i)})}async function Kt(e,t){return(await ne.get(e,t,"cwd")).cwd}async function io(e,t,n){return ne.post(e,t,"touch",{name:n})}async function lo(e,t,n){return ne.post(e,t,"mkdir",{path:n})}async function uo(e,t,n){return ne.del(e,t,"rm",{path:n})}async function fo(e,t){const n=await ne.getBlob(e,t,"download-cwd"),r=await n.blob(),o=URL.createObjectURL(r),c=document.createElement("a");c.href=o;const i=n.headers.get("Content-Disposition"),d=i==null?void 0:i.match(/filename="(.+)"/);c.download=d?decodeURIComponent(d[1]):"cwd.tar.gz",document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(o)}async function po(e,t,n){const o=await(await ne.getBlob(e,t,"download",{path:n})).blob(),c=URL.createObjectURL(o),i=document.createElement("a");i.href=c,i.download=n.split("/").pop()||"download",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(c)}function xn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function mo(e,t){if(t==="directory")return"📁";const n=e.slice(e.lastIndexOf(".")).toLowerCase();return n===".pdf"?"📕":n===".html"||n===".htm"?"🌐":n===".md"?"📝":"📄"}function yn(e){const t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function ho({sessionId:e,token:t,planDir:n,selectedFile:r,onSelectFile:o,onCreateFile:c,onDeleteFile:i}){const[d,p]=a.useState([]),[l,u]=a.useState(!0),[f,h]=a.useState(""),[g,x]=a.useState(!1),R=a.useRef(null),[C,j]=a.useState(n),S=a.useCallback(async()=>{if(!(!t||!C)){u(!0);try{const G=(await be(t,e,C)).files.filter(W=>W.type==="file"&&W.name.toLowerCase().endsWith(".md")||W.type==="directory").sort((W,U)=>{const V=W.type==="file"&&W.name===".index.md",z=U.type==="file"&&U.name===".index.md";return V&&!z?-1:!V&&z?1:W.type==="directory"&&U.type!=="directory"?-1:W.type!=="directory"&&U.type==="directory"?1:W.name.localeCompare(U.name)});p(G)}catch{p([])}finally{u(!1)}}},[t,e,C]);a.useEffect(()=>{S()},[S]),a.useEffect(()=>{const y=setInterval(S,5e3);return()=>clearInterval(y)},[S]);const w=a.useCallback(()=>{const y=n.substring(0,n.lastIndexOf("/")+1);return C.startsWith(y)?C.substring(y.length):C},[n,C]),k=a.useCallback(async()=>{const y=f.trim();if(!y)return;const G=y.endsWith(".md")?y:`${y}.md`;x(!0);try{const W=await io(t,e,`${w()}/${G}`);W.ok&&(h(""),await S(),c(W.path))}catch{}finally{x(!1)}},[f,t,e,w,S,c]),A=a.useCallback(async()=>{const y=f.trim().replace(/\/+$/,"");if(y){x(!0);try{await lo(t,e,`${w()}/${y}`),h(""),await S()}catch{}finally{x(!1)}}},[f,t,e,w,S]),P=a.useCallback(async y=>{const G=`${C}/${y.name}`,W=y.type==="directory"?`folder "${y.name}" and all its contents`:`"${y.name}"`;if(window.confirm(`Delete ${W}?`))try{await uo(t,e,G),i==null||i(G),await S()}catch{}},[t,e,C,S,i]),B=a.useCallback(y=>{j(G=>`${G}/${y}`)},[]),$=a.useCallback(()=>{C!==n&&j(y=>y.substring(0,y.lastIndexOf("/")))},[C,n]),F=n.split("/").pop()||"AiTasks",O=(()=>{const y=n.split("/");return y.length>=2?y[y.length-2]+"/":""})(),D=C===n?O+F+"/":O+F+"/"+C.substring(n.length+1)+"/",T=r?r.split("/").pop():null;return s.jsxs("div",{className:"plan-file-browser",children:[s.jsxs("div",{className:"plan-file-browser__header",children:[s.jsx("span",{className:"plan-file-browser__title",title:D,children:D}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:S,title:"Refresh file list",style:{fontSize:12},children:"↻"})]}),s.jsxs("div",{className:"plan-file-browser__create",children:[s.jsx("input",{ref:R,className:"plan-file-browser__input",value:f,onChange:y=>h(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),k())},placeholder:"name",disabled:g}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:k,disabled:g||!f.trim(),title:"Create new .md file",style:f.trim()?{color:"var(--accent-green)",fontWeight:700,fontSize:14}:{opacity:.4,fontWeight:700,fontSize:14},children:"+"}),s.jsx("button",{className:"pane-btn pane-btn--sm",onClick:A,disabled:g||!f.trim(),title:"Create new folder",style:f.trim()?{color:"var(--accent-blue)"}:{opacity:.4},children:"📁"})]}),s.jsxs("div",{className:"plan-file-browser__list",children:[l&&d.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"Loading..."}),!l&&d.length===0&&s.jsx("div",{className:"plan-file-browser__status",children:"No .md files"}),C!==n&&s.jsxs("div",{className:"plan-file-browser__item",onClick:$,title:"Go up to parent directory",style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",style:{color:"var(--accent-blue)"},children:"←"}),s.jsx("span",{className:"plan-file-browser__name",style:{color:"var(--accent-blue)"},children:".."})]}),d.map(y=>{const G=`${C}/${y.name}`,W=y.type==="file"&&y.name===T,U=y.type==="directory";return s.jsxs("div",{className:`plan-file-browser__item${W?" plan-file-browser__item--active":""}`,onClick:()=>U?B(y.name):o(G),title:U?`Open folder ${y.name}`:y.name,style:{cursor:"pointer"},children:[s.jsx("span",{className:"plan-file-browser__icon",children:U?"📁":y.name===".index.md"?"🔒":"□"}),s.jsxs("span",{className:"plan-file-browser__name",children:[y.name,U?"/":""]}),!U&&s.jsx("span",{className:"plan-file-browser__size",children:xn(y.size)}),y.name!==".index.md"&&s.jsx("button",{className:"pane-btn pane-btn--danger pane-btn--sm plan-file-browser__delete",onClick:V=>{V.stopPropagation(),P(y)},title:`Delete ${y.name}`,children:"×"})]},y.name)})]})]})}const dt={status:"idle",mode:"lines",lines:[],content:"",buffer:null,totalSize:0,receivedBytes:0,mtime:0,error:null},go=200;function bo(){const[e,t]=a.useState(dt),n=a.useRef("lines"),r=a.useRef([]),o=a.useRef(""),c=a.useRef(""),i=a.useRef([]),d=a.useRef(0),p=a.useRef(0),l=a.useRef(null),u=a.useRef(null),f=a.useCallback(()=>{const j=n.current;t(S=>({...S,receivedBytes:d.current,...j==="lines"?{lines:[...r.current]}:{},...j==="content"?{content:c.current}:{}}))},[]),h=a.useCallback(()=>{l.current===null&&(l.current=window.setTimeout(()=>{l.current=null,f()},go))},[f]),g=a.useCallback(j=>{n.current=j,r.current=[],o.current="",c.current="",i.current=[],d.current=0,p.current=0,u.current=new TextDecoder,l.current!==null&&(clearTimeout(l.current),l.current=null),t({...dt,mode:j,status:"streaming"})},[]),x=a.useCallback(j=>{d.current+=j.length;const S=n.current;if(S==="lines"){const k=u.current.decode(j,{stream:!0}).split(`
30
- `);k[0]=o.current+k[0],o.current=k.pop(),k.length>0&&r.current.push(...k)}else if(S==="content"){const w=u.current.decode(j,{stream:!0});c.current+=w}else i.current.push(new Uint8Array(j));h()},[h]),R=a.useCallback(j=>{switch(j.type){case"file-stream-start":p.current=j.size,t(S=>({...S,totalSize:j.size,mtime:j.mtime}));break;case"file-stream-end":{l.current!==null&&(clearTimeout(l.current),l.current=null);const S=n.current;let w=r.current,k=c.current,A=null;if(S==="lines"){const P=u.current.decode(),B=o.current+P;B&&(w=[...w,B],r.current=w),o.current=""}else if(S==="content"){const P=u.current.decode();k=c.current+P,c.current=k}else{const P=i.current.reduce(($,F)=>$+F.length,0);A=new Uint8Array(P);let B=0;for(const $ of i.current)A.set($,B),B+=$.length;i.current=[]}t({status:"complete",mode:S,lines:S==="lines"?[...w]:[],content:S==="content"?k:"",buffer:S==="binary"?A:null,totalSize:p.current,receivedBytes:d.current,mtime:0,error:null});break}case"file-stream-error":l.current!==null&&(clearTimeout(l.current),l.current=null),t(S=>({...S,status:"error",error:j.error}));break}},[]),C=a.useCallback(()=>{l.current!==null&&(clearTimeout(l.current),l.current=null),r.current=[],o.current="",c.current="",i.current=[],d.current=0,p.current=0,u.current=null,t(dt)},[]);return{state:e,startStream:g,handleChunk:x,handleControl:R,reset:C}}async function Jt(e,t,n,r){const o={path:n};return r&&(o.since=String(r)),ne.getOptional(e,t,"file-content",o)}function Gt({label:e,percent:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:e}),t!=null&&s.jsxs("div",{style:{width:120,display:"flex",alignItems:"center",gap:6},children:[s.jsx("div",{style:{flex:1,height:4,backgroundColor:"var(--border)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${t}%`,backgroundColor:"var(--accent-blue)",transition:"width 0.2s"}})}),s.jsxs("span",{style:{fontSize:10,color:"var(--text-secondary)",whiteSpace:"nowrap"},children:[t,"%"]})]})]})}function xo({sessionId:e,token:t,connected:n,onRequestFileStream:r,onSendToTerminal:o}){const c=bo(),[i,d]=a.useState(!1),[p,l]=a.useState(null),[u,f]=a.useState(null),[h,g]=a.useState(""),[x,R]=a.useState(!1),[C,j]=a.useState(!1),S=a.useRef(null),w=`plan-selected-file-${e}`,k=a.useRef(void 0);a.useEffect(()=>{if(u)return clearTimeout(k.current),k.current=setTimeout(()=>{try{localStorage.setItem(w,u)}catch{}},50),()=>clearTimeout(k.current)},[u,w]);const A=a.useRef(null);a.useEffect(()=>{A.current=null;let L=!1;return R(!0),j(!1),(async()=>{let M="";try{const H=await be(t,e);if(L)return;if(M=H.home||"",H.files.find(Y=>Y.name==="AiTasks"&&Y.type==="directory")){const Y=H.cwd+"/AiTasks";l(Y);const Z=localStorage.getItem(w);Z&&Z.startsWith(Y+"/")&&f(Z)}else l(null),f(null),j(!0)}catch{l(null)}finally{L||R(!1)}try{if(L)return;if(M){const H=`${M}/.claude/plugins/installed_plugins.json`,X=await Jt(t,e,H,0);if(!L&&X)try{const Y=JSON.parse(X.content);"ai-cli-task@moonview"in(Y.plugins||Y)||d(!0)}catch{d(!0)}}}catch{}})(),()=>{L=!0}},[e,t]),a.useEffect(()=>(wr(e,c.handleChunk,c.handleControl),()=>Sr(e)),[e,c.handleChunk,c.handleControl]),a.useEffect(()=>{!u||!n||A.current===u&&h||(A.current=u,c.reset(),c.startStream("content"),r==null||r(u))},[u,n]);const P=a.useRef(0);a.useEffect(()=>{c.state.status==="complete"&&u&&(g(c.state.content),P.current=Date.now())},[c.state.status,c.state.content,u]),a.useEffect(()=>{if(!u||!n||!h)return;const L=setInterval(async()=>{if(P.current)try{const M=await Jt(t,e,u,P.current);M&&(g(M.content),P.current=M.mtime)}catch{}},3e3);return()=>clearInterval(L)},[u,n,h,t,e]);const B=a.useRef(new Map),$=a.useCallback(()=>{var M,H;if(!u)return;const L=((H=(M=S.current)==null?void 0:M.getScrollTop)==null?void 0:H.call(M))??0;L>0&&B.current.set(u,L)},[u]);a.useEffect(()=>{if(!u||!h)return;const L=B.current.get(u);L!=null&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var M,H;(H=(M=S.current)==null?void 0:M.setScrollTop)==null||H.call(M,L)})})},[u,h]);const F=a.useCallback(L=>{L!==u&&($(),f(L),g(""),A.current=null)},[u,$]),O=a.useCallback(L=>{u&&(u===L||u.startsWith(L+"/"))&&(f(null),g(""),A.current=null)},[u]),D=a.useCallback(L=>{f(L),g(""),A.current=null},[]),T=a.useCallback(L=>{L&&(o==null||o(L))},[o]),y=a.useCallback(()=>{$(),f(null),g(""),A.current=null},[$]),G=a.useCallback(()=>{!u||!n||(A.current=null,g(""),c.reset(),c.startStream("content"),r==null||r(u),A.current=u)},[u,n,c,r]),[W,U]=a.useState(()=>{const L=localStorage.getItem(`plan-fb-width-${e}`);if(L){const M=Number(L);if(Number.isFinite(M)&&M>=60&&M<=300)return M}return 130}),V=a.useRef(W);if(W!==V.current){V.current=W;try{localStorage.setItem(`plan-fb-width-${e}`,String(Math.round(W)))}catch{}}const z=a.useCallback(L=>{L.preventDefault();const M=L.clientX,H=W;document.body.classList.add("resizing-panes");const X=Z=>{const ue=Z.clientX-M;U(Math.min(300,Math.max(60,H+ue)))},Y=()=>{document.body.classList.remove("resizing-panes"),document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",Y)};document.addEventListener("mousemove",X),document.addEventListener("mouseup",Y)},[W]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[i&&s.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:[s.jsx("span",{style:{color:"var(--accent-yellow)",flex:1},children:"ai-cli-task plugin not installed"}),s.jsx("button",{className:"pane-btn",style:{color:"var(--accent-green)",fontSize:11},onClick:()=>{o&&o("/plugin marketplace add huacheng/moonview && /plugin install ai-cli-task@moonview"),d(!1)},children:"Install"}),s.jsx("button",{className:"pane-btn",style:{fontSize:11},onClick:()=>d(!1),children:"×"})]}),s.jsxs("div",{className:"plan-overlay-body",children:[p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:W,flexShrink:0,overflow:"hidden"},children:s.jsx(ho,{sessionId:e,token:t,planDir:p,selectedFile:u,onSelectFile:F,onCreateFile:D,onDeleteFile:O})}),s.jsx("div",{onMouseDown:z,style:{width:2,flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:L=>{L.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:L=>{L.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsx("div",{className:"plan-overlay-center",children:x?s.jsx(Gt,{label:"Loading AiTasks/..."}):C?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:12,padding:"0 20px"},children:[s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:14},children:"AiTasks/ directory not found"}),s.jsxs("span",{style:{color:"var(--text-secondary)",fontSize:12,textAlign:"center"},children:["Run ",s.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"]})]}):u&&!h&&(c.state.status==="streaming"||c.state.status==="idle")?s.jsx(Gt,{label:`Loading ${u.split("/").pop()}...`,percent:c.state.totalSize>0?Math.round(c.state.receivedBytes/c.state.totalSize*100):void 0}):u?s.jsx(ao,{ref:S,markdown:h,filePath:u,sessionId:e,token:t,onExecute:T,onSend:o,onRefresh:G,onClose:y,readOnly:u.endsWith("/.index.md")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",gap:8},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13,fontStyle:"italic"},children:"Select a file from the left panel"})})})]})]})}async function yo(e,t){try{return(await ne.get(e,t,"draft")).content??""}catch{return""}}async function Vt(e,t,n){try{await ne.put(e,t,"draft",{content:n})}catch{}}const xt="chat-history",qt=50;function vn(){try{const e=localStorage.getItem(xt);return e?JSON.parse(e):[]}catch{return[]}}function vo(e){const n=vn().filter(r=>r.text!==e);n.unshift({text:e,ts:Date.now()}),n.length>qt&&(n.length=qt),localStorage.setItem(xt,JSON.stringify(n))}const Yt=[{cmd:"/history",desc:"Browse sent message history"},{cmd:"/plan",desc:"Enter plan mode"},{cmd:"/help",desc:"Get help"},{cmd:"/compact",desc:"Compact conversation"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/model",desc:"Switch model"},{cmd:"/cost",desc:"Show token usage"},{cmd:"/status",desc:"Show status"},{cmd:"/init",desc:"Initialize project CLAUDE.md"},{cmd:"/memory",desc:"Edit memory files"},{cmd:"/review",desc:"Review code"},{cmd:"/bug",desc:"Report a bug"},{cmd:"/login",desc:"Login to Anthropic"},{cmd:"/doctor",desc:"Run diagnostics"},{cmd:"/permissions",desc:"Manage permissions"},{cmd:"/mcp",desc:"MCP server management"},{cmd:"/terminal-setup",desc:"Configure terminal"},{cmd:"/vim",desc:"Toggle vim mode"},{cmd:"/oh-my-claudecode:autopilot",desc:"Full autonomous execution"},{cmd:"/oh-my-claudecode:ralph",desc:"Persistence loop until done"},{cmd:"/oh-my-claudecode:ultrawork",desc:"Max parallel execution"},{cmd:"/oh-my-claudecode:ecomode",desc:"Token-efficient execution"},{cmd:"/oh-my-claudecode:plan",desc:"Strategic planning session"},{cmd:"/oh-my-claudecode:ralplan",desc:"Iterative planning consensus"},{cmd:"/oh-my-claudecode:ultrapilot",desc:"Parallel autopilot (3-5x faster)"},{cmd:"/oh-my-claudecode:analyze",desc:"Deep analysis/investigation"},{cmd:"/oh-my-claudecode:deepsearch",desc:"Thorough codebase search"},{cmd:"/oh-my-claudecode:deepinit",desc:"Generate AGENTS.md hierarchy"},{cmd:"/oh-my-claudecode:ultraqa",desc:"QA cycling: test/fix/repeat"},{cmd:"/oh-my-claudecode:tdd",desc:"Test-driven development"},{cmd:"/oh-my-claudecode:code-review",desc:"Comprehensive code review"},{cmd:"/oh-my-claudecode:security-review",desc:"Security vulnerability review"},{cmd:"/oh-my-claudecode:build-fix",desc:"Fix build/TypeScript errors"},{cmd:"/oh-my-claudecode:research",desc:"Parallel research orchestration"},{cmd:"/oh-my-claudecode:swarm",desc:"N coordinated agents"},{cmd:"/oh-my-claudecode:pipeline",desc:"Sequential agent chaining"},{cmd:"/oh-my-claudecode:learner",desc:"Extract skill from session"},{cmd:"/oh-my-claudecode:note",desc:"Save notes to notepad"},{cmd:"/oh-my-claudecode:cancel",desc:"Cancel active OMC mode"},{cmd:"/oh-my-claudecode:help",desc:"OMC usage guide"},{cmd:"/oh-my-claudecode:doctor",desc:"Diagnose OMC issues"},{cmd:"/oh-my-claudecode:omc-setup",desc:"One-time OMC setup"},{cmd:"/oh-my-claudecode:hud",desc:"Configure HUD statusline"},{cmd:"/oh-my-claudecode:release",desc:"Automated release workflow"},{cmd:"/oh-my-claudecode:ralph-init",desc:"Initialize PRD for ralph"},{cmd:"/oh-my-claudecode:review",desc:"Review plan with Critic"},{cmd:"/oh-my-claudecode:git-master",desc:"Git expert for commits"},{cmd:"/oh-my-claudecode:mcp-setup",desc:"Configure MCP servers"},{cmd:"/oh-my-claudecode:skill",desc:"Manage local skills"},{cmd:"/oh-my-claudecode:writer-memory",desc:"Writer memory system"},{cmd:"/oh-my-claudecode:psm",desc:"Project session manager"},{cmd:"/oh-my-claudecode:trace",desc:"Agent flow trace timeline"},{cmd:"/plan-analyzer",desc:"Task complexity grading & token routing"}],wo=a.forwardRef(function({onSend:t,onContentChange:n,sessionId:r,token:o},c){const i=_(v=>v.fontSize),[d,p]=a.useState(""),l=a.useRef(null),u=a.useRef(void 0),f=a.useRef(!1),h=a.useRef(!1),{pushUndo:g,popUndo:x}=mt(),R=a.useRef(d);R.current=d;const C=a.useCallback(()=>g(R.current),[g]),[j,S]=a.useState(!1),[w,k]=a.useState(""),[A,P]=a.useState(0),[B,$]=a.useState(!1),[F,O]=a.useState([]),[D,T]=a.useState(0),[y,G]=a.useState(""),W=a.useRef(null),U=a.useMemo(()=>{if(!y)return F;const v=y.toLowerCase();return F.filter(I=>I.text.toLowerCase().includes(v))},[F,y]),[V,z]=a.useState(!1),[L,M]=a.useState(""),[H,X]=a.useState(""),[Y,Z]=a.useState(0),[ue,ye]=a.useState([]),[$e,Se]=a.useState(!1),se=a.useRef(""),ve=a.useRef(null),le=a.useMemo(()=>{if(!w)return Yt;const v=w.toLowerCase();return Yt.filter(I=>I.cmd.toLowerCase().includes(v)||I.desc.toLowerCase().includes(v))},[w]),re=a.useMemo(()=>{let v=ue;if(L){const I=L.toLowerCase();v=v.filter(m=>m.name.toLowerCase().includes(I))}return[...v].sort((I,m)=>I.type==="directory"&&m.type!=="directory"?-1:I.type!=="directory"&&m.type==="directory"?1:I.name.localeCompare(m.name))},[ue,L]),Oe=_(v=>v.latency),ae=`chat-draft-${r}`,Re=a.useRef(!1),fe=a.useRef(void 0);a.useEffect(()=>{try{const I=localStorage.getItem(ae);I&&!h.current&&p(I)}catch{}let v=!1;return yo(o,r).then(I=>{if(v||h.current){f.current=!0;return}if(I){p(I);try{localStorage.setItem(ae,I)}catch{}}f.current=!0}).catch(()=>{f.current=!0}),()=>{v=!0}},[o,r,ae]),a.useEffect(()=>{if(!f.current)return;u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{try{localStorage.setItem(ae,d)}catch{}},50),fe.current&&clearTimeout(fe.current);const v=Math.max(200,(Oe??30)*3);return fe.current=setTimeout(()=>{Re.current||(Re.current=!0,Vt(o,r,d).catch(()=>{}).finally(()=>{Re.current=!1}))},v),()=>{u.current&&clearTimeout(u.current),fe.current&&clearTimeout(fe.current)}},[d,o,r,Oe,ae]),a.useEffect(()=>{var v;(v=l.current)==null||v.focus()},[]),a.useEffect(()=>{if(!V)return;let v=!1;return Se(!0),(async()=>{try{if(H){if(!se.current){const b=await be(o,r);if(v)return;se.current=b.cwd}const I=`${se.current}/${H.replace(/\/$/,"")}`,m=await be(o,r,I);if(v)return;ye(m.files)}else{const I=await be(o,r);if(v)return;se.current=I.cwd,ye(I.files)}Se(!1)}catch{if(v)return;ye([]),Se(!1)}})(),()=>{v=!0}},[V,H,o,r]),a.useEffect(()=>{if(!V||!ve.current)return;const v=ve.current.querySelector(".file-item--active");v==null||v.scrollIntoView({block:"nearest"})},[Y,V]);const me=a.useCallback(()=>{const v=R.current.trim();if(v){vo(v),t(v),p("");try{localStorage.removeItem(ae)}catch{}Vt(o,r,"").catch(()=>{})}},[t,o,r,ae]),he=a.useCallback(v=>{C(),p(v),h.current=!0},[C]),Pe=a.useCallback(v=>{const I=l.current;C();const m=R.current;if(I){const b=I.selectionStart,N=I.selectionEnd,E=m.slice(0,b)+v+m.slice(N);p(E);const J=b+v.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=J,I.focus()})}else p(m+v)},[C]);a.useImperativeHandle(c,()=>({send:me,fillContent:he,insertAtCursor:Pe}),[me,he,Pe]),a.useEffect(()=>{n==null||n(d.trim().length>0)},[d,n]);const ke=a.useCallback(()=>{const v=l.current;if(!v)return;const{selectionStart:I,selectionEnd:m}=v;if(I!==m){const b=v.value.substring(I,m);b&&navigator.clipboard.writeText(b).catch(()=>{})}},[]),Te=a.useCallback(()=>{const v=vn();S(!1),k("");const I=l.current;if(I){const m=I.selectionStart,b=d.slice(0,m),N=d.slice(m),E=b.match(/(?:^|\s)(\/history)\s*$/);if(E){const J=b.length-E[1].length;p(d.slice(0,J)+N)}}v.length!==0&&(O(v),T(0),G(""),$(!0))},[d]),de=a.useCallback(v=>{C(),p(v.text),$(!1),requestAnimationFrame(()=>{const I=l.current;I&&(I.selectionStart=I.selectionEnd=v.text.length,I.focus())})},[C]),Ne=a.useCallback(v=>{const I=U[v];if(!I)return;const m=F.filter(N=>N.ts!==I.ts||N.text!==I.text);O(m),localStorage.setItem(xt,JSON.stringify(m));const b=y?m.filter(N=>N.text.toLowerCase().includes(y.toLowerCase())):m;D>=b.length&&T(Math.max(0,b.length-1))},[U,F,D,y]);a.useEffect(()=>{if(!B||!W.current)return;const v=W.current.querySelector(".history-item--active");v==null||v.scrollIntoView({block:"nearest"})},[D,B]);const Le=a.useCallback(v=>{if(v==="/history"){Te();return}const I=l.current;if(!I)return;C();const m=I.selectionStart,b=d.slice(0,m),N=d.slice(m),J=b.lastIndexOf(`
31
- `)+1,q=b.slice(J).match(/\/[a-zA-Z:-]*$/);if(q){const Q=J+(q.index??0),ge=v+" ",Me=d.slice(0,Q)+ge+N;p(Me);const Be=Q+ge.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Be,I.focus()})}else{const Q=b+v+N;p(Q);const ge=m+v.length;requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=ge,I.focus()})}S(!1),k(""),P(0)},[d,C,Te]),De=a.useCallback(v=>{const I=l.current;if(!I)return;C();const m=I.selectionStart,b=d.slice(0,m),N=d.slice(m),E=b.match(/@([a-zA-Z0-9_.\-/]*)$/);if(!E)return;const J=b.length-E[0].length;if(v.type==="directory"){const K="@"+H+v.name+"/",q=d.slice(0,J)+K+N;p(q);const Q=J+K.length;X(H+v.name+"/"),M(""),Z(0),requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Q,I.focus()})}else{const K=v.name+" ",q=d.slice(0,J)+K+N;p(q);const Q=J+K.length;z(!1),M(""),X(""),Z(0),ye([]),se.current="",requestAnimationFrame(()=>{I.selectionStart=I.selectionEnd=Q,I.focus()})}},[d,H,C]),ot=a.useCallback(v=>{const I=v.target.value;if(p(I),B){const K=I.trim();K?(G(K),T(0)):G("");return}const m=v.target.selectionStart,b=I.slice(0,m),N=b.lastIndexOf(`
32
- `),J=b.slice(N+1).match(/(?:^|\s)\/([a-zA-Z:-]*)$/);if(J)S(!0),k(J[1]),P(0),z(!1);else{S(!1);const K=b.match(/@([a-zA-Z0-9_.\-/]*)$/);if(K){const q=K[1],Q=q.lastIndexOf("/"),ge=Q>=0?q.slice(0,Q+1):"",Me=Q>=0?q.slice(Q+1):q;M(Me),Z(0),X(ge),z(!0)}else z(!1)}},[B]),Fe=a.useCallback(v=>{if(j&&le.length>0){if(v.key==="ArrowDown"){v.preventDefault(),P(I=>(I+1)%le.length);return}if(v.key==="ArrowUp"){v.preventDefault(),P(I=>(I-1+le.length)%le.length);return}if(v.key==="Enter"||v.key==="Tab"){v.preventDefault(),Le(le[A].cmd);return}if(v.key==="Escape"){v.preventDefault(),S(!1);return}}if(V&&re.length>0){if(v.key==="ArrowDown"){v.preventDefault(),Z(I=>(I+1)%re.length);return}if(v.key==="ArrowUp"){v.preventDefault(),Z(I=>(I-1+re.length)%re.length);return}if(v.key==="Tab"||v.key==="Enter"){v.preventDefault(),De(re[Y]);return}if(v.key==="Escape"){v.preventDefault(),z(!1);return}}if(B&&U.length>0){if(v.key==="ArrowDown"){v.preventDefault(),T(I=>(I+1)%U.length);return}if(v.key==="ArrowUp"){v.preventDefault(),T(I=>(I-1+U.length)%U.length);return}if(v.key==="Enter"){v.preventDefault(),de(U[D]);return}if(v.key==="Delete"||v.key==="Backspace"&&(v.ctrlKey||v.metaKey)){v.preventDefault(),Ne(D);return}if(v.key==="Escape"){v.preventDefault(),$(!1);return}}if(v.key==="Tab"){ht(v,p,g);return}v.key==="Enter"&&(v.ctrlKey||v.metaKey)&&(v.preventDefault(),me())},[me,j,le,A,Le,V,re,Y,De,g,x,B,U,D,de,Ne]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--bg-primary)",overflow:"hidden"},children:[j&&le.length>0&&s.jsx("div",{className:"slash-dropdown",children:le.map((v,I)=>s.jsxs("div",{className:`slash-item${I===A?" slash-item--active":""}`,onMouseDown:m=>{m.preventDefault(),Le(v.cmd)},onMouseEnter:()=>P(I),children:[s.jsx("span",{className:"slash-cmd",children:v.cmd}),s.jsx("span",{className:"slash-desc",children:v.desc})]},v.cmd))}),V&&($e||re.length>0)&&s.jsx("div",{className:"file-dropdown",ref:ve,children:$e?s.jsx("div",{className:"file-item file-loading",children:"Loading..."}):re.map((v,I)=>s.jsxs("div",{className:`file-item${I===Y?" file-item--active":""}`,onMouseDown:m=>{m.preventDefault(),De(v)},onMouseEnter:()=>Z(I),children:[s.jsx("span",{className:"file-icon",children:v.type==="directory"?"📁":"📄"}),s.jsx("span",{className:"file-name",children:v.name})]},v.name))}),B&&s.jsx("div",{className:"history-dropdown",ref:W,children:U.length===0?s.jsx("div",{className:"history-item history-empty",children:"No history yet"}):U.map((v,I)=>s.jsxs("div",{className:`history-item${I===D?" history-item--active":""}`,onMouseDown:m=>{m.preventDefault(),de(v)},onMouseEnter:()=>T(I),children:[s.jsx("span",{className:"history-text",children:v.text.length>120?v.text.slice(0,120)+"...":v.text}),s.jsx("span",{className:"history-time",children:new Date(v.ts).toLocaleString()}),s.jsx("button",{className:"history-delete",onMouseDown:m=>{m.preventDefault(),m.stopPropagation(),Ne(I)},title:"Delete (Del key)",children:"×"})]},`${v.ts}-${I}`))}),s.jsx("textarea",{ref:l,className:"md-editor-textarea",value:d,onChange:ot,onKeyDown:Fe,onMouseUp:ke,placeholder:"Type / for commands, @ for files, Ctrl+Enter to send",spellCheck:!1,style:{flex:1,fontSize:`${i}px`}})]})});function So({token:e,sessionId:t,onClose:n}){const[r,o]=a.useState([]),[c,i]=a.useState(""),[d,p]=a.useState([]),[l,u]=a.useState(!0),[f,h]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{let S=!1;return(async()=>{try{const w=await be(e,t);S||(i(w.cwd),o(w.files))}catch{S||n()}finally{S||u(!1)}})(),()=>{S=!0}},[e,t,n]),a.useEffect(()=>{const S=A=>{A.key==="Escape"&&n()},w=A=>{g.current&&!g.current.contains(A.target)&&n()};document.addEventListener("keydown",S);const k=setTimeout(()=>document.addEventListener("mousedown",w),50);return()=>{document.removeEventListener("keydown",S),document.removeEventListener("mousedown",w),clearTimeout(k)}},[n]);const x=a.useCallback(async S=>{u(!0);try{const w=await be(e,t,S);p(k=>[...k,c]),i(S),o(w.files)}catch{}finally{u(!1)}},[e,t,c]),R=a.useCallback(async()=>{if(d.length===0)return;const S=d[d.length-1];u(!0);try{const w=await be(e,t,S);p(k=>k.slice(0,-1)),i(S),o(w.files)}catch{}finally{u(!1)}},[e,t,d]),C=a.useCallback(async S=>{try{await po(e,t,S)}catch(w){alert(`Download failed: ${w instanceof Error?w.message:"Unknown error"}`)}},[e,t]),j=a.useCallback(async()=>{h(!0),n();try{await fo(e,t)}catch(S){alert(`Download failed: ${S instanceof Error?S.message:"Unknown error"}`)}finally{h(!1)}},[e,t,n]);return s.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:[s.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&&s.jsx("button",{className:"pane-btn",onClick:R,disabled:l,style:{fontSize:11,flexShrink:0},title:"Go back",children:".."}),s.jsx("span",{style:{fontSize:11,color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",flex:1},children:c.split("/").slice(-2).join("/")||c}),s.jsx("button",{className:"pane-btn",onClick:n,style:{fontSize:11,flexShrink:0},title:"Close",children:"×"})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:"2px 0"},children:l?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12},children:"Loading..."}):r.length===0?s.jsx("div",{style:{padding:"12px",textAlign:"center",color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"Empty directory"}):r.map(S=>s.jsxs("div",{onClick:()=>{const w=c+"/"+S.name;S.type==="directory"?x(w):C(w)},style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:"var(--text-primary)",transition:"background-color 0.1s"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="var(--bg-secondary)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="transparent"},children:[s.jsx("span",{style:{flexShrink:0,fontSize:13},children:S.type==="directory"?"📁":mo(S.name,S.type)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name}),S.type==="directory"?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:"›"}):S.size!=null?s.jsx("span",{style:{fontSize:10,color:"var(--text-secondary)",flexShrink:0},children:xn(S.size)}):null]},S.name))}),s.jsx("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 8px",flexShrink:0,backgroundColor:"var(--bg-secondary)"},children:s.jsx("button",{className:"pane-btn",onClick:j,disabled:f,style:{fontSize:11,color:"var(--accent-blue)",width:"100%",textAlign:"center"},title:"Download entire CWD as tar.gz",children:f?"Downloading...":"Download All (tar.gz)"})})]})}function Xt(e,t,{containerRef:n,axis:r,offset:o=0,min:c,max:i,invert:d=!1,bodyClass:p}){const[l,u]=a.useState(()=>{const g=localStorage.getItem(e);if(g){const x=Number(g);if(Number.isFinite(x)&&x>=c&&x<=i)return x}return t}),f=a.useRef(l);if(l!==f.current){f.current=l;try{localStorage.setItem(e,String(Math.round(l)))}catch{}}const h=a.useCallback(g=>{g.preventDefault();const x=n.current;if(!x)return;const R=x.getBoundingClientRect(),C=r==="x"?R.width:R.height-o,j=r==="x"?R.left:R.top+o;document.body.classList.add(p);const S=k=>{let P=((r==="x"?k.clientX:k.clientY)-j)/C*100;d&&(P=100-P),u(Math.min(i,Math.max(c,P)))},w=()=>{document.body.classList.remove(p),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",w)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",w)},[n,r,o,c,i,d,p]);return[l,h]}const ko=600,Ie=typeof window<"u"?window.matchMedia(`(max-width: ${ko-1}px)`):null;function To(){const[e,t]=a.useState(()=>(Ie==null?void 0:Ie.matches)??!1);return a.useEffect(()=>{if(!Ie)return;const n=r=>t(r.matches);return Ie.addEventListener("change",n),()=>Ie.removeEventListener("change",n)},[]),e}const Co=a.memo(function({terminal:t}){const n=To(),r=_(z=>z.splitTerminal),o=_(z=>z.token),c=_(z=>z.toggleChat),i=_(z=>z.togglePlan),{chatOpen:d,planOpen:p}=t.panels,l=a.useRef(null),u=a.useRef(null),f=a.useRef(null),h=a.useRef(null),g=a.useRef(null),[x,R]=Xt(`plan-width-${t.id}`,50,{containerRef:u,axis:"x",min:20,max:80,bodyClass:"resizing-panes"}),[C,j]=Xt(`doc-height-${t.id}`,35,{containerRef:l,axis:"y",offset:24,min:15,max:60,invert:!0,bodyClass:"resizing-panes-v"}),[S,w]=a.useState("");a.useEffect(()=>{if(!o||!t.connected)return;let z=!1;const L=async()=>{try{const H=await Kt(o,t.id);z||w(H)}catch{}};L();const M=setInterval(L,5e3);return()=>{z=!0,clearInterval(M)}},[o,t.id,t.connected]);const k=a.useCallback(async z=>{let L;if(o)try{L=await Kt(o,t.id)}catch{}r(t.id,z,L)},[o,t.id,r]),[A,P]=a.useState(!1),[B,$]=a.useState(0),[F,O]=a.useState(!1),[D,T]=a.useState(!1),y=async z=>{const L=z.target.files;if(!(!L||L.length===0||!o)){P(!0),$(0);try{await co(o,t.id,L,M=>{$(M)})}catch(M){alert(`Upload failed: ${M instanceof Error?M.message:"Unknown error"}`)}finally{P(!1),$(0),f.current&&(f.current.value="")}}},G=a.useRef(void 0),W=a.useCallback(z=>{if(h.current){const L=z.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(L),G.current=window.setTimeout(()=>{var M;return(M=h.current)==null?void 0:M.sendInput("\r")},50)}},[]);a.useEffect(()=>()=>{G.current&&clearTimeout(G.current)},[]);const U=a.useCallback(z=>{if(h.current){const L=z.replace(/\r?\n/g," ").trimEnd();h.current.sendInput(L),setTimeout(()=>{var M;return(M=h.current)==null?void 0:M.sendInput("\r")},50)}},[]),V=a.useCallback(()=>T(!1),[]);return s.jsxs("div",{ref:l,style:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"3px 10px",backgroundColor:"var(--bg-secondary)",borderBottom:"1px solid var(--border)",flexShrink:0,height:"24px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",minWidth:0,flex:1,overflow:"hidden"},children:[s.jsx("span",{style:{display:"inline-block",width:"6px",height:"6px",borderRadius:"50%",backgroundColor:t.connected?"var(--accent-green)":"var(--accent-red)",flexShrink:0}}),s.jsxs("span",{style:{fontSize:"12px",color:"var(--text-secondary)",flexShrink:0},children:[t.id,t.connected?t.sessionResumed?" (resumed)":"":" (disconnected)"]}),S&&s.jsx("span",{style:{fontSize:"11px",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0},title:S,children:S})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsx("input",{ref:f,type:"file",multiple:!0,style:{display:"none"},onChange:y}),s.jsx("button",{className:"pane-btn",onClick:()=>{var z;return(z=f.current)==null?void 0:z.click()},disabled:A,style:A?{color:"var(--accent-yellow)"}:void 0,title:A?`Uploading ${B}%`:"Upload files","aria-label":"Upload files",children:A?`${B}%`:"↑"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("button",{className:"pane-btn",onClick:()=>T(!0),title:"Download files","aria-label":"Download files",children:"↓"}),D&&o&&s.jsx(So,{token:o,sessionId:t.id,onClose:V})]}),s.jsx("button",{className:`pane-btn${d?" pane-btn--active":""}`,onClick:()=>c(t.id),title:"Toggle Chat panel","aria-label":"Toggle Chat panel",children:"Chat"}),s.jsx("button",{className:`pane-btn${p?" pane-btn--active":""}`,onClick:()=>i(t.id),title:"Toggle Task annotation panel","aria-label":"Toggle Task annotation panel",children:"Task"}),s.jsx("button",{className:"pane-btn",onClick:()=>k(n?"vertical":"horizontal"),title:n?"Split vertical (screen too narrow for horizontal)":"Split horizontal (left/right)","aria-label":"Split horizontal",children:"|"}),s.jsx("button",{className:"pane-btn",onClick:()=>k("vertical"),title:"Split vertical (top/bottom)","aria-label":"Split vertical",children:"─"})]})]}),s.jsxs("div",{ref:u,style:{flex:1,display:"flex",flexDirection:"row",overflow:"hidden",minHeight:0},children:[p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:`${x}%`,minWidth:200,flexShrink:0,overflow:"hidden"},children:s.jsx(xo,{sessionId:t.id,token:o||"",connected:t.connected,onRequestFileStream:z=>{var L;return(L=h.current)==null?void 0:L.requestFileStream(z)},onSendToTerminal:U})}),s.jsx("div",{className:"md-editor-divider-h",onMouseDown:R,style:{width:"2px",flexShrink:0,cursor:"col-resize",backgroundColor:"var(--border)",transition:"background-color 0.15s"},onMouseEnter:z=>{z.currentTarget.style.backgroundColor="var(--accent-blue)"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="var(--border)"}})]}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[s.jsxs("div",{style:{flex:1,overflow:"hidden",position:"relative",minWidth:80},children:[s.jsx(Pr,{ref:h,sessionId:t.id}),!t.connected&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"var(--bg-secondary)",opacity:.85,zIndex:2,pointerEvents:"none"},children:s.jsx("span",{style:{color:"var(--text-secondary)",fontSize:"13px",fontStyle:"italic"},children:"Connecting..."})})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"md-editor-divider",onMouseDown:j}),s.jsxs("div",{style:{height:`${C}%`,minHeight:80,flexShrink:0,overflow:"hidden",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.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:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"11px",color:"var(--accent-blue)",fontWeight:500},children:"Chat"}),s.jsx("button",{className:"pane-btn",onClick:()=>{var z;return(z=g.current)==null?void 0:z.send()},disabled:!F,title:"Send to terminal (Ctrl+Enter)",style:F?{color:"var(--accent-green)"}:{opacity:.4,cursor:"default"},children:"Send"}),s.jsx("span",{style:{fontSize:"9px",color:"var(--text-secondary)"},children:"Ctrl+Enter"})]})}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(wo,{ref:g,onSend:W,onContentChange:O,sessionId:t.id,token:o||""})})]})]})]})]}),t.error&&s.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:t.error})]})});class wn extends a.Component{constructor(){super(...arguments);wt(this,"state",{hasError:!1,error:null})}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){}render(){var n,r;return this.state.hasError?this.props.inline?s.jsxs("div",{style:{height:"100%",backgroundColor:"var(--bg-primary)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",color:"var(--text-bright)",fontFamily:"monospace",padding:"16px"},children:[s.jsx("div",{style:{fontSize:"14px",color:"var(--accent-red)"},children:"Pane crashed"}),s.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"}),s.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"})]}):s.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:[s.jsx("div",{style:{fontSize:"18px",color:"var(--accent-red)"},children:"Something went wrong"}),s.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"}),s.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 Eo=4,Zt=10;function Io(){const e=_(o=>o.layout),t=_(o=>o.terminalIds.length),n=_(o=>o.addTerminal);if(!e)return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)"},children:s.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=t>1;return s.jsx("div",{style:{height:"100%",width:"100%",overflow:"hidden"},children:s.jsx(Sn,{node:e,canClose:r})})}const Sn=a.memo(function({node:t,canClose:n}){return t.type==="leaf"?s.jsx(jo,{terminalId:t.terminalId,canClose:n}):s.jsx(Ro,{node:t,canClose:n})}),jo=a.memo(function({terminalId:t,canClose:n}){const r=_(c=>c.terminalsMap[t]),o=_(c=>c.reconnectTerminal);return r?s.jsx(wn,{inline:!0,children:s.jsx(Co,{terminal:r,canClose:n})}):s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"var(--bg-primary)",border:"1px dashed var(--border)"},children:s.jsxs("button",{onClick:()=>o(t),style:{background:"none",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",padding:"8px 16px",borderRadius:"6px",cursor:"pointer",fontSize:"13px"},children:["↻ Reconnect ",t]})})}),Ro=a.memo(function({node:t,canClose:n}){const r=_(l=>l.setSplitSizes),o=a.useRef(null),c=t.direction==="horizontal",i=a.useRef(t.sizes);i.current=t.sizes;const d=a.useCallback((l,u)=>{u.preventDefault();const f=c?"resizing-panes":"resizing-panes-v";document.body.classList.add(f);const h=c?u.clientX:u.clientY,g=[...i.current],x=o.current,R=c?(x==null?void 0:x.clientWidth)||1:(x==null?void 0:x.clientHeight)||1;let C=null;const j=w=>{C||(C=requestAnimationFrame(()=>{C=null;const P=((c?w.clientX:w.clientY)-h)/R*100,B=g[l]+P,$=g[l+1]-P;if(B>=Zt&&$>=Zt){const F=[...g];F[l]=B,F[l+1]=$,r(t.id,F)}}))},S=()=>{C&&cancelAnimationFrame(C),document.body.classList.remove(f),document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",S)};document.addEventListener("mousemove",j),document.addEventListener("mouseup",S)},[c,t.id,r]),p=[];return t.children.forEach((l,u)=>{const f=l.type==="leaf"?l.terminalId:l.id;p.push(s.jsx("div",{style:{flex:`${t.sizes[u]} 0 0`,minWidth:0,minHeight:0,overflow:"hidden"},children:s.jsx(Sn,{node:l,canClose:n})},f)),u<t.children.length-1&&p.push(s.jsx("div",{onMouseDown:h=>d(u,h),style:{flex:`0 0 ${Eo}px`,cursor:c?"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-${t.id}-${u}`))}),s.jsx("div",{ref:o,style:{display:"flex",flexDirection:c?"row":"column",height:"100%",width:"100%",overflow:"hidden"},children:p})});function No({tabId:e}){const t=_(T=>T.tabs.find(y=>y.id===e)),n=_(T=>T.activeTabId),r=_(T=>T.switchTab),o=_(T=>T.closeTab),c=_(T=>T.reopenTab),i=_(T=>T.deleteTab),d=_(T=>T.renameTab),p=_(T=>t?t.terminalIds.map(y=>{const G=T.terminalsMap[y];return G?{id:y,connected:G.connected,active:!0}:{id:y,connected:!1,active:!1}}):[]),l=_(T=>T.disconnectTerminal),u=_(T=>T.reconnectTerminal),f=_(T=>T.killServerSession),[h,g]=a.useState(!1),[x,R]=a.useState(""),[C,j]=a.useState(!1),S=a.useRef(null);if(!t)return null;const w=n===e,k=t.status==="open",A=()=>{k&&r(e)},P=T=>{k&&(T.stopPropagation(),R(t.name),g(!0),setTimeout(()=>{var y;return(y=S.current)==null?void 0:y.focus()},0))},B=()=>{const T=x.trim();T&&d(e,T),g(!1)},$=T=>{T.stopPropagation(),c(e)},F=T=>{T.stopPropagation(),o(e)},O=async T=>{T.stopPropagation(),window.confirm(`Delete tab "${t.name}"? This will kill all tmux sessions in this tab.`)&&await i(e)},D=T=>{T.stopPropagation(),j(!C)};return s.jsxs("div",{children:[s.jsxs("div",{onClick:A,style:{padding:"8px 12px",cursor:k?"pointer":"default",borderLeft:w?"3px solid var(--accent-blue)":"3px solid transparent",backgroundColor:w?"rgba(122, 162, 247, 0.08)":"transparent",display:"flex",alignItems:"center",gap:"8px",borderBottom:"1px solid var(--border)",transition:"background-color 0.15s",opacity:k?1:.5},onMouseEnter:T=>{k&&!w&&(T.currentTarget.style.backgroundColor="rgba(122, 162, 247, 0.05)")},onMouseLeave:T=>{w||(T.currentTarget.style.backgroundColor="transparent")},children:[k&&t.terminalIds.length>0&&s.jsx("button",{onClick:D,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:C?"▼":"▶"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[h?s.jsx("input",{ref:S,value:x,onChange:T=>R(T.target.value),onBlur:B,onKeyDown:T=>{T.key==="Enter"&&B(),T.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"}}):s.jsx("div",{onDoubleClick:P,style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:k?"Double-click to rename":t.name,children:t.name}),s.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:[t.terminalIds.length," terminal",t.terminalIds.length!==1?"s":""," · ",yn(Math.floor(t.createdAt/1e3))]})]}),k?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:F,style:{flexShrink:0},title:"Close tab",children:"×"}):s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:$,title:"Reopen tab",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:O,title:"Delete tab",children:"×"})]})]}),k&&C&&p.length>0&&s.jsx("div",{style:{paddingLeft:"28px",backgroundColor:"rgba(0, 0, 0, 0.2)"},children:p.map(T=>s.jsxs("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center"},title:`Connected: ${T.connected}`,children:[s.jsx("span",{style:{fontFamily:"monospace"},children:T.id}),s.jsx("span",{style:{marginLeft:"8px",color:T.active?T.connected?"var(--accent-green)":"var(--accent-yellow)":"var(--text-secondary)"},children:T.active?T.connected?"●":"◐":"○"}),T.active?s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:y=>{y.stopPropagation(),l(T.id)},style:{marginLeft:"auto",flexShrink:0},title:"Disconnect terminal (keeps session alive)",children:"×"}):s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{className:"pane-btn",onClick:y=>{y.stopPropagation(),u(T.id)},title:"Reconnect terminal",style:{fontSize:"11px",padding:"2px 6px"},children:"↻"}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:y=>{y.stopPropagation(),window.confirm(`Kill terminal "${T.id}"? This will destroy the tmux session.`)&&f(T.id)},title:"Kill session",children:"×"})]})]},T.id))})]})}function Lo({sessionId:e,active:t,createdAt:n}){const r=_(d=>d.addTerminal),o=_(d=>d.killServerSession),c=()=>{r("horizontal",e)},i=d=>{d.stopPropagation(),window.confirm(`Delete orphaned session "${e}"? This will kill the tmux session.`)&&o(e)};return s.jsxs("div",{onClick:c,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:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:t?"var(--accent-green)":"var(--text-secondary)",flexShrink:0}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:"var(--text-bright)",fontSize:"14px",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"11px",marginTop:"2px"},children:yn(n)})]}),s.jsx("button",{className:"pane-btn pane-btn--danger",onClick:i,style:{flexShrink:0},title:"Delete session",children:"×"})]})}function Do(){const e=_(l=>l.sidebarOpen),t=_(l=>l.toggleSidebar),n=_(l=>l.fetchSessions),r=_(l=>e?l.serverSessions:[]),o=_(l=>e?l.tabs:[]),c=_(l=>l.terminalIds.length),i=_(l=>l.tabsLoading),d=new Set(o.flatMap(l=>l.terminalIds)),p=r.filter(l=>!d.has(l.sessionId));return a.useEffect(()=>{if(!e)return;n();let l=setInterval(n,5e3);const u=()=>{document.hidden?l&&(clearInterval(l),l=null):(n(),l||(l=setInterval(n,5e3)))};return document.addEventListener("visibilitychange",u),()=>{l&&clearInterval(l),document.removeEventListener("visibilitychange",u)}},[e,n]),a.useEffect(()=>{if(!e)return;const l=setTimeout(n,800);return()=>clearTimeout(l)},[c,e,n]),s.jsxs("div",{className:"session-sidebar",style:{width:e?280:0,height:"100%",backgroundColor:"var(--bg-secondary)",borderLeft:e?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,overflow:"hidden",transition:"width 0.2s ease"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[s.jsx("span",{style:{color:"var(--accent-blue)",fontSize:"14px",fontWeight:"bold"},children:"Tabs & Terminals"}),s.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"16px",padding:"0 4px",lineHeight:1},title:"Close sidebar",children:"×"})]}),s.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{padding:"8px 12px",color:"var(--accent-blue)",fontSize:"12px",fontWeight:"bold",backgroundColor:"rgba(122, 162, 247, 0.05)",borderBottom:"1px solid var(--border)"},children:"Tabs"}),o.length===0?s.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"14px",textAlign:"center",padding:"12px"},children:"No tabs"}):o.map(l=>s.jsx(No,{tabId:l.id},l.id))]}),!i&&p.length>0&&s.jsxs("div",{style:{marginTop:"16px"},children:[s.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(l=>s.jsx(Lo,{sessionId:l.sessionId,active:l.active,createdAt:l.createdAt},l.sessionId))]})]})]})}const kn=bt.memo(()=>{const e=_(k=>k.tabs),t=_(k=>k.activeTabId),n=_(k=>k.addTab),r=_(k=>k.switchTab),o=_(k=>k.closeTab),c=_(k=>k.renameTab),[i,d]=a.useState(null),[p,l]=a.useState(""),u=a.useRef(null),f=e.filter(k=>k.status==="open");a.useEffect(()=>{i&&u.current&&(u.current.focus(),u.current.select())},[i]);const h=k=>{d(k.id),l(k.name)},g=()=>{i&&p.trim()&&c(i,p.trim()),d(null),l("")},x=()=>{d(null),l("")},R=k=>{k.key==="Enter"?g():k.key==="Escape"&&x()},C=k=>{i||r(k)},j=(k,A)=>{k.stopPropagation(),o(A)},S=(k,A)=>{k.button===1&&(k.preventDefault(),o(A))},w=f.length>1;return s.jsxs("div",{className:"tab-bar",children:[f.map(k=>{const A=k.id===t,P=i===k.id,B=k.terminalIds.length;return s.jsx("div",{className:`tab-item ${A?"tab-item--active":""}`,onClick:()=>C(k.id),onDoubleClick:()=>h(k),onMouseDown:$=>S($,k.id),children:P?s.jsx("input",{ref:u,type:"text",value:p,onChange:$=>l($.target.value),onBlur:g,onKeyDown:R,className:"tab-item__rename-input"}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"tab-item__name",children:[k.name," ",B>0&&`(${B})`]}),w&&s.jsx("button",{className:"tab-item__close",onClick:$=>j($,k.id),title:"Close tab","aria-label":"Close tab",children:"×"})]})},k.id)}),s.jsx("button",{className:"tab-bar-add",onClick:()=>n(),title:"New tab","aria-label":"Add new tab",children:"+"})]})});kn.displayName="TabBar";function Mo(){return localStorage.getItem("ai-cli-online-token")}function Ao(){const e=_(u=>u.token),t=_(u=>u.setToken),n=_(u=>u.tabs),r=_(u=>u.addTab),o=_(u=>u.toggleSidebar),c=_(u=>u.fontSize),i=_(u=>u.setFontSize),d=_(u=>u.tabsLoading),p=_(u=>u.theme),l=_(u=>u.toggleTheme);return a.useEffect(()=>{const u=Mo();u&&!e&&t(u)},[]),a.useEffect(()=>{e&&!d&&n.filter(u=>u.status==="open").length===0&&r("Default")},[e,d]),e?s.jsxs("div",{style:{height:"100vh",display:"flex",flexDirection:"column",backgroundColor:"var(--bg-primary)"},children:[s.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:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsx("span",{style:{fontSize:"15px",fontWeight:"bold",color:"var(--accent-blue)",letterSpacing:"0.5px"},children:"AI-Cli Online"}),s.jsxs("span",{style:{fontSize:"11px",color:"var(--text-secondary)",fontWeight:400},children:["v","3.0.2"]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"2px",padding:"1px 4px",borderRadius:"6px",backgroundColor:"rgba(0,0,0,0.2)"},children:[s.jsx("button",{className:"header-btn",onClick:()=>i(c-1),disabled:c<=10,title:"Decrease font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A−"}),s.jsx("span",{style:{fontSize:"11px",color:"var(--text-primary)",minWidth:"20px",textAlign:"center"},children:c}),s.jsx("button",{className:"header-btn",onClick:()=>i(c+1),disabled:c>=24,title:"Increase font size",style:{fontSize:"11px",padding:"1px 5px",minWidth:0},children:"A+"})]}),s.jsx(_o,{}),s.jsx("button",{className:"header-btn",onClick:l,title:`Switch to ${p==="dark"?"light":"dark"} mode`,"aria-label":"Toggle theme",children:p==="dark"?"☀":"🌙"}),s.jsx("button",{className:"header-btn",onClick:o,title:"Toggle Tabs & Terminals Sidebar","aria-label":"Toggle sidebar",children:"☰"}),s.jsx("button",{className:"header-btn header-btn--muted",onClick:()=>{window.confirm("Logout will close all terminals. Continue?")&&t(null)},children:"Logout"})]})]}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[s.jsx("main",{style:{flex:1,overflow:"hidden"},children:s.jsx(Io,{})}),s.jsx(Do,{})]}),s.jsx(kn,{})]}):s.jsx(vr,{})}const zo=[1,2,3,4];function _o(){const e=_(r=>r.latency);if(e===null)return s.jsx("span",{style:{fontSize:"10px",color:"var(--scrollbar-thumb-hover)"},title:"Measuring latency...",children:"--ms"});let t,n;return e<50?(t="var(--accent-green)",n=4):e<150?(t="var(--accent-yellow)",n=3):e<300?(t="var(--accent-orange)",n=2):(t="var(--accent-red)",n=1),s.jsxs("span",{style:{display:"inline-flex",alignItems:"end",gap:"1.5px",padding:"2px 8px",borderRadius:"10px",backgroundColor:"rgba(0,0,0,0.2)"},title:`Latency: ${e}ms`,children:[zo.map(r=>s.jsx("span",{style:{display:"inline-block",width:"2.5px",height:`${3+r*2}px`,backgroundColor:r<=n?t:"var(--border)",borderRadius:"1px",transition:"background-color 0.3s ease"}},r)),s.jsxs("span",{style:{fontSize:"10px",color:t,marginLeft:"4px",fontWeight:500},children:[e,"ms"]})]})}ft.createRoot(document.getElementById("root")).render(s.jsx(bt.StrictMode,{children:s.jsx(wn,{children:s.jsx(Ao,{})})}));