@myrialabs/clopen 0.3.5 → 0.3.7

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.
@@ -20,7 +20,20 @@ import { EventEmitter } from 'events';
20
20
  import { existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
21
21
  import { tmpdir, platform } from 'os';
22
22
  import { join } from 'path';
23
- import { getBinaryPath } from './binary';
23
+ import { resolveCloudflaredBinary } from './binary';
24
+
25
+ export class CloudflaredMissingError extends Error {
26
+ constructor() {
27
+ super('Cloudflared binary is not installed. Install it from Settings → System Tools, or install cloudflared system-wide and restart clopen.');
28
+ this.name = 'CloudflaredMissingError';
29
+ }
30
+ }
31
+
32
+ function requireBinary(): string {
33
+ const resolved = resolveCloudflaredBinary();
34
+ if (!resolved) throw new CloudflaredMissingError();
35
+ return resolved;
36
+ }
24
37
 
25
38
  // --- Output parsing regexes (from cloudflared npm package) ---
26
39
 
@@ -167,7 +180,7 @@ export class CloudflaredTunnel extends EventEmitter {
167
180
  env = { ...process.env, BROWSER: 'false', PATH: `${fakeOpenDir}:${process.env.PATH ?? ''}` };
168
181
  }
169
182
 
170
- const proc = spawn(getBinaryPath(), ['tunnel', 'login'], {
183
+ const proc = spawn(requireBinary(), ['tunnel', 'login'], {
171
184
  stdio: ['ignore', 'pipe', 'pipe'],
172
185
  env
173
186
  });
@@ -280,7 +293,7 @@ export class CloudflaredTunnel extends EventEmitter {
280
293
  /** Run a one-shot cloudflared command and collect all output. */
281
294
  private static run(args: string[]): Promise<{ output: string; exitCode: number }> {
282
295
  return new Promise((resolve, reject) => {
283
- const proc = spawn(getBinaryPath(), args, {
296
+ const proc = spawn(requireBinary(), args, {
284
297
  stdio: ['ignore', 'pipe', 'pipe']
285
298
  });
286
299
 
@@ -360,7 +373,7 @@ export class CloudflaredTunnel extends EventEmitter {
360
373
  }
361
374
 
362
375
  private createProcess(args: string[]): ChildProcess {
363
- const binPath = getBinaryPath();
376
+ const binPath = requireBinary();
364
377
  const child = spawn(binPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
365
378
 
366
379
  child.on('error', (error) => this.emit('error', error));
@@ -13,7 +13,7 @@ import { homedir } from 'os';
13
13
  import { join } from 'path';
14
14
  import { getTunnelDir } from './tunnel-config';
15
15
  import type { RemoteTunnelConfig, LocalTunnelConfig } from './tunnel-config';
16
- import { getBinaryPath, isBinaryInstalled, installBinary, CloudflaredTunnel, type LoginHandle } from './cloudflared';
16
+ import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError, type LoginHandle } from './cloudflared';
17
17
 
18
18
  // --- Types ---
19
19
 
@@ -63,7 +63,6 @@ class GlobalTunnelManager {
63
63
  private quickTunnels = new Map<number, QuickTunnelInstance>();
64
64
  private remoteTunnels = new Map<string, RemoteTunnelInstance>();
65
65
  private localTunnels = new Map<string, LocalTunnelInstance>();
66
- private binaryInstalled = false;
67
66
  private loginHandle: LoginHandle | null = null;
68
67
 
69
68
  // Callback for pushing ingress updates to connected clients
@@ -85,39 +84,21 @@ class GlobalTunnelManager {
85
84
 
86
85
  // --- Binary management ---
87
86
 
88
- private async ensureBinaryInstalled(
87
+ /**
88
+ * Verify cloudflared is available before a tunnel operation. Never
89
+ * downloads — installation is user-initiated through Settings → System
90
+ * Tools. Throws CloudflaredMissingError when nothing is resolvable.
91
+ */
92
+ private ensureBinaryAvailable(
89
93
  onProgress?: (stage: string, data?: any) => void
90
- ): Promise<{ needsDownload: boolean; downloadTime?: number }> {
91
- if (this.binaryInstalled) {
92
- onProgress?.('binary-ready', { cached: true });
93
- return { needsDownload: false };
94
+ ): void {
95
+ const resolved = resolveCloudflaredBinary();
96
+ if (!resolved) {
97
+ debug.warn('tunnel', 'Cloudflared binary not available; install via Settings → System Tools');
98
+ throw new CloudflaredMissingError();
94
99
  }
95
-
96
- if (!isBinaryInstalled()) {
97
- debug.log('tunnel', 'Cloudflared binary not found, downloading...');
98
- onProgress?.('downloading-binary', { size: '~66MB' });
99
-
100
- const startTime = Date.now();
101
- try {
102
- await installBinary();
103
- const downloadTime = Date.now() - startTime;
104
- debug.log('tunnel', `Cloudflared binary installed in ${downloadTime}ms at: ${getBinaryPath()}`);
105
-
106
- this.binaryInstalled = true;
107
- onProgress?.('binary-ready', { downloaded: true, time: downloadTime });
108
- return { needsDownload: true, downloadTime };
109
- } catch (error) {
110
- debug.error('tunnel', 'Failed to install cloudflared binary:', error);
111
- throw new Error(
112
- 'Failed to download cloudflared binary. Please check your internet connection and try again.'
113
- );
114
- }
115
- }
116
-
117
- debug.log('tunnel', 'Cloudflared binary already installed at:', getBinaryPath());
118
- this.binaryInstalled = true;
100
+ debug.log('tunnel', 'Cloudflared binary available at:', resolved);
119
101
  onProgress?.('binary-ready', { cached: true });
120
- return { needsDownload: false };
121
102
  }
122
103
 
123
104
  // --- Quick tunnel ---
@@ -126,15 +107,14 @@ class GlobalTunnelManager {
126
107
  port: number,
127
108
  autoStopMinutes: number = 60,
128
109
  onProgress?: (stage: string, data?: any) => void
129
- ): Promise<{ publicUrl: string; binaryDownloaded: boolean; timings: Record<string, number> }> {
110
+ ): Promise<{ publicUrl: string; timings: Record<string, number> }> {
130
111
  onProgress?.('checking-binary');
131
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
112
+ this.ensureBinaryAvailable(onProgress);
132
113
  const timings: Record<string, number> = {};
133
- if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
134
114
 
135
115
  if (this.quickTunnels.has(port)) {
136
116
  const existing = this.quickTunnels.get(port)!;
137
- return { publicUrl: existing.publicUrl, binaryDownloaded: binaryInfo.needsDownload, timings };
117
+ return { publicUrl: existing.publicUrl, timings };
138
118
  }
139
119
 
140
120
  onProgress?.('starting-tunnel', { port });
@@ -201,7 +181,7 @@ class GlobalTunnelManager {
201
181
  onProgress?.('connected', { publicUrl, timings });
202
182
  this.notifyStatusChanged();
203
183
 
204
- return { publicUrl, binaryDownloaded: binaryInfo.needsDownload, timings };
184
+ return { publicUrl, timings };
205
185
  } catch (error) {
206
186
  debug.error('tunnel', `Failed to start quick tunnel on port ${port}:`, error);
207
187
  throw error;
@@ -226,14 +206,13 @@ class GlobalTunnelManager {
226
206
  async startRemoteTunnel(
227
207
  config: RemoteTunnelConfig,
228
208
  onProgress?: (stage: string, data?: any) => void
229
- ): Promise<{ binaryDownloaded: boolean; timings: Record<string, number> }> {
209
+ ): Promise<{ timings: Record<string, number> }> {
230
210
  onProgress?.('checking-binary');
231
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
211
+ this.ensureBinaryAvailable(onProgress);
232
212
  const timings: Record<string, number> = {};
233
- if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
234
213
 
235
214
  if (this.remoteTunnels.has(config.id)) {
236
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
215
+ return { timings };
237
216
  }
238
217
 
239
218
  onProgress?.('starting-tunnel', { label: config.label });
@@ -305,7 +284,7 @@ class GlobalTunnelManager {
305
284
  onProgress?.('connected', { timings });
306
285
  this.notifyStatusChanged();
307
286
 
308
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
287
+ return { timings };
309
288
  } catch (error) {
310
289
  debug.error('tunnel', `Failed to start remote tunnel ${config.label}:`, error);
311
290
  throw error;
@@ -348,7 +327,7 @@ class GlobalTunnelManager {
348
327
  onComplete?: () => void,
349
328
  onError?: (error: string) => void
350
329
  ): Promise<void> {
351
- await this.ensureBinaryInstalled();
330
+ this.ensureBinaryAvailable();
352
331
 
353
332
  if (this.loginHandle) {
354
333
  onError?.('Login process already running');
@@ -410,7 +389,7 @@ class GlobalTunnelManager {
410
389
  }
411
390
 
412
391
  async createLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
413
- await this.ensureBinaryInstalled();
392
+ this.ensureBinaryAvailable();
414
393
 
415
394
  // Write credentials directly to our dir (not ~/.cloudflared/)
416
395
  const tunnelBaseDir = getTunnelDir();
@@ -433,7 +412,7 @@ class GlobalTunnelManager {
433
412
  }
434
413
 
435
414
  async deleteLocalTunnel(tunnelId: string, credentialsFile?: string): Promise<void> {
436
- await this.ensureBinaryInstalled();
415
+ this.ensureBinaryAvailable();
437
416
 
438
417
  await CloudflaredTunnel.deleteTunnel(tunnelId, { credentialsFile, origincert: CERT_PATH });
439
418
  debug.log('tunnel', `Local tunnel deleted: ${tunnelId}`);
@@ -448,7 +427,7 @@ class GlobalTunnelManager {
448
427
  }
449
428
 
450
429
  async routeDns(tunnelName: string, hostname: string): Promise<{ alreadyExists: boolean }> {
451
- await this.ensureBinaryInstalled();
430
+ this.ensureBinaryAvailable();
452
431
 
453
432
  const result = await CloudflaredTunnel.routeDns(tunnelName, hostname, { overwriteDns: true, origincert: CERT_PATH });
454
433
  debug.log('tunnel', `DNS route ${result.alreadyExists ? 'updated' : 'added'}: ${hostname} -> ${tunnelName}`);
@@ -483,14 +462,13 @@ class GlobalTunnelManager {
483
462
  async startLocalTunnel(
484
463
  config: LocalTunnelConfig,
485
464
  onProgress?: (stage: string, data?: any) => void
486
- ): Promise<{ binaryDownloaded: boolean; timings: Record<string, number> }> {
465
+ ): Promise<{ timings: Record<string, number> }> {
487
466
  onProgress?.('checking-binary');
488
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
467
+ this.ensureBinaryAvailable(onProgress);
489
468
  const timings: Record<string, number> = {};
490
- if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
491
469
 
492
470
  if (this.localTunnels.has(config.id)) {
493
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
471
+ return { timings };
494
472
  }
495
473
 
496
474
  if (config.ingress.length === 0) {
@@ -557,7 +535,7 @@ class GlobalTunnelManager {
557
535
  onProgress?.('connected', { timings });
558
536
  this.notifyStatusChanged();
559
537
 
560
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
538
+ return { timings };
561
539
  } catch (error) {
562
540
  debug.error('tunnel', `Failed to start local tunnel ${config.name}:`, error);
563
541
  throw error;
@@ -1,5 +1,5 @@
1
1
  import { debug } from '$shared/utils/logger';
2
- import { getBinaryPath, isBinaryInstalled, installBinary, CloudflaredTunnel } from './cloudflared';
2
+ import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError } from './cloudflared';
3
3
 
4
4
  interface TunnelInstance {
5
5
  tunnel: any;
@@ -18,7 +18,6 @@ interface TunnelConnection {
18
18
  class ProjectTunnelManager {
19
19
  // Key format: "projectId:port" to support multiple tunnels per project
20
20
  private activeTunnels = new Map<string, TunnelInstance>();
21
- private binaryInstalled = false;
22
21
 
23
22
  /**
24
23
  * Generate unique key for tunnel
@@ -28,51 +27,19 @@ class ProjectTunnelManager {
28
27
  }
29
28
 
30
29
  /**
31
- * Ensure cloudflared binary is installed
32
- * Downloads binary on first use (~66MB, takes 30-60 seconds)
30
+ * Verify cloudflared is available. Installation is user-initiated via
31
+ * Settings → System Tools; this manager never auto-downloads.
33
32
  */
34
- private async ensureBinaryInstalled(
33
+ private ensureBinaryAvailable(
35
34
  onProgress?: (stage: string, data?: any) => void
36
- ): Promise<{
37
- needsDownload: boolean;
38
- downloadTime?: number;
39
- }> {
40
- // Check if already verified in this session
41
- if (this.binaryInstalled) {
42
- onProgress?.('binary-ready', { cached: true });
43
- return { needsDownload: false };
44
- }
45
-
46
- // Check if binary file exists
47
- if (!isBinaryInstalled()) {
48
- debug.log('tunnel', '[PROGRESS:DOWNLOADING_BINARY] Cloudflared binary not found, downloading...');
49
- debug.log('tunnel', 'This may take 30-60 seconds on first use (downloading ~66MB)');
50
- onProgress?.('downloading-binary', { size: '~66MB' });
51
-
52
- const startTime = Date.now();
53
-
54
- try {
55
- await installBinary();
56
-
57
- const downloadTime = Date.now() - startTime;
58
- debug.log('tunnel', `[PROGRESS:BINARY_READY] Cloudflared binary installed successfully in ${downloadTime}ms at: ${getBinaryPath()}`);
59
-
60
- this.binaryInstalled = true;
61
- onProgress?.('binary-ready', { downloaded: true, time: downloadTime });
62
- return { needsDownload: true, downloadTime };
63
- } catch (error) {
64
- debug.error('tunnel', 'Failed to install cloudflared binary:', error);
65
- throw new Error(
66
- 'Failed to download cloudflared binary. Please check your internet connection and try again. ' +
67
- 'The tunnel feature requires downloading ~66MB on first use.'
68
- );
69
- }
70
- } else {
71
- debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary already installed at:', getBinaryPath());
72
- this.binaryInstalled = true;
73
- onProgress?.('binary-ready', { cached: true });
74
- return { needsDownload: false };
35
+ ): void {
36
+ const resolved = resolveCloudflaredBinary();
37
+ if (!resolved) {
38
+ debug.warn('tunnel', 'Cloudflared binary not available; install via Settings → System Tools');
39
+ throw new CloudflaredMissingError();
75
40
  }
41
+ debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary available at:', resolved);
42
+ onProgress?.('binary-ready', { cached: true });
76
43
  }
77
44
 
78
45
  /**
@@ -83,18 +50,13 @@ class ProjectTunnelManager {
83
50
  port: number,
84
51
  autoStopMinutes: number = 60,
85
52
  onProgress?: (stage: string, data?: any) => void
86
- ): Promise<{ publicUrl: string; status: 'active'; binaryDownloaded: boolean; timings: any }> {
87
- debug.log('tunnel', '[PROGRESS:CHECKING_BINARY] Checking if binary is installed...');
53
+ ): Promise<{ publicUrl: string; status: 'active'; timings: any }> {
54
+ debug.log('tunnel', '[PROGRESS:CHECKING_BINARY] Checking if binary is available...');
88
55
  onProgress?.('checking-binary');
89
56
 
90
- // Ensure binary is installed
91
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
57
+ this.ensureBinaryAvailable(onProgress);
92
58
  const timings: any = {};
93
59
 
94
- if (binaryInfo.needsDownload) {
95
- timings.binaryDownload = binaryInfo.downloadTime;
96
- }
97
-
98
60
  // Check if tunnel already exists for this port
99
61
  const tunnelKey = this.getTunnelKey(projectId, port);
100
62
  if (this.activeTunnels.has(tunnelKey)) {
@@ -209,7 +171,6 @@ class ProjectTunnelManager {
209
171
  return {
210
172
  publicUrl,
211
173
  status: 'active',
212
- binaryDownloaded: binaryInfo.needsDownload,
213
174
  timings
214
175
  };
215
176
  }
@@ -16,9 +16,9 @@
16
16
  * the stunnel team. Release: https://github.com/stunnel/static-curl
17
17
  */
18
18
 
19
- import { existsSync, readdirSync, mkdirSync, mkdtempSync, chmodSync, renameSync, rmSync } from 'node:fs';
19
+ import { existsSync, readdirSync, mkdirSync, chmodSync, renameSync } from 'node:fs';
20
20
  import { join, dirname } from 'node:path';
21
- import { tmpdir } from 'node:os';
21
+ import { XzReadableStream } from 'xz-decompress';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { getClopenDir } from '$backend/utils/paths';
24
24
  import { resolveBinary } from '$backend/utils/cli';
@@ -98,19 +98,65 @@ export function hasCachedStaticCurl(): boolean {
98
98
  return existsSync(getStaticCurlPath());
99
99
  }
100
100
 
101
- async function sha256OfFile(path: string): Promise<string> {
101
+ function sha256(bytes: Uint8Array): string {
102
102
  const hasher = new Bun.CryptoHasher('sha256');
103
- const reader = Bun.file(path).stream().getReader();
104
- try {
105
- while (true) {
106
- const { done, value } = await reader.read();
107
- if (done) break;
108
- hasher.update(value);
103
+ hasher.update(bytes);
104
+ return hasher.digest('hex');
105
+ }
106
+
107
+ function parseTarOctal(bytes: Uint8Array): number {
108
+ let end = bytes.length;
109
+ for (let i = 0; i < bytes.length; i++) {
110
+ if (bytes[i] === 0 || bytes[i] === 0x20) {
111
+ end = i;
112
+ break;
109
113
  }
110
- } finally {
111
- reader.releaseLock();
112
114
  }
113
- return hasher.digest('hex');
115
+ const str = new TextDecoder().decode(bytes.subarray(0, end)).trim();
116
+ return str === '' ? 0 : parseInt(str, 8);
117
+ }
118
+
119
+ /**
120
+ * Minimal POSIX tar reader: walks header blocks and returns the first
121
+ * regular file whose name matches. Sufficient for static-curl archives
122
+ * which contain `curl` at the root with a short name.
123
+ */
124
+ function findFileInTar(tarBytes: Uint8Array, filename: string): Uint8Array | null {
125
+ const decoder = new TextDecoder();
126
+ let offset = 0;
127
+ while (offset + 512 <= tarBytes.length) {
128
+ const header = tarBytes.subarray(offset, offset + 512);
129
+ let allZero = true;
130
+ for (let i = 0; i < 512; i++) {
131
+ if (header[i] !== 0) { allZero = false; break; }
132
+ }
133
+ if (allZero) return null;
134
+
135
+ const nameBytes = header.subarray(0, 100);
136
+ const nameEnd = nameBytes.indexOf(0);
137
+ const name = decoder.decode(nameEnd >= 0 ? nameBytes.subarray(0, nameEnd) : nameBytes);
138
+ const size = parseTarOctal(header.subarray(124, 136));
139
+ const typeflag = header[156];
140
+ const isRegularFile = typeflag === 0 || typeflag === 0x30; // '\0' or '0'
141
+
142
+ offset += 512;
143
+ if (isRegularFile && name === filename) {
144
+ return tarBytes.subarray(offset, offset + size);
145
+ }
146
+ offset += Math.ceil(size / 512) * 512;
147
+ }
148
+ return null;
149
+ }
150
+
151
+ async function decompressXz(xzBytes: Uint8Array): Promise<Uint8Array> {
152
+ const input = new ReadableStream<Uint8Array>({
153
+ start(controller) {
154
+ controller.enqueue(xzBytes);
155
+ controller.close();
156
+ }
157
+ });
158
+ const decompressed = new Response(new XzReadableStream(input));
159
+ return new Uint8Array(await decompressed.arrayBuffer());
114
160
  }
115
161
 
116
162
  export type CurlProgressPhase = 'cached' | 'fetching' | 'verifying' | 'extracting' | 'done';
@@ -148,51 +194,35 @@ export async function ensureCurlAvailable(
148
194
  }
149
195
 
150
196
  mkdirSync(binDir, { recursive: true });
151
- const workDir = mkdtempSync(join(tmpdir(), 'clopen-curl-'));
152
- const archivePath = join(workDir, 'curl.tar.xz');
153
-
154
- try {
155
- onProgress({ phase: 'fetching', message: `downloading ${asset.url}` });
156
- const response = await fetch(asset.url, { redirect: 'follow' });
157
- if (!response.ok) {
158
- throw new Error(`HTTP ${response.status} ${response.statusText}`);
159
- }
160
- await Bun.write(archivePath, response);
161
197
 
162
- onProgress({ phase: 'verifying', message: `verifying SHA256 ${asset.sha256}` });
163
- const actualSha = await sha256OfFile(archivePath);
164
- if (actualSha !== asset.sha256) {
165
- throw new Error(`SHA256 mismatch: expected ${asset.sha256}, got ${actualSha}`);
166
- }
198
+ onProgress({ phase: 'fetching', message: `downloading ${asset.url}` });
199
+ const response = await fetch(asset.url, { redirect: 'follow' });
200
+ if (!response.ok) {
201
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
202
+ }
203
+ const archiveBytes = new Uint8Array(await response.arrayBuffer());
167
204
 
168
- onProgress({ phase: 'extracting', message: `extracting curl to ${binDir}` });
169
- const proc = Bun.spawn(['tar', '-xJf', archivePath, '-C', workDir, 'curl'], {
170
- stdout: 'pipe',
171
- stderr: 'pipe'
172
- });
173
- const exit = await proc.exited;
174
- if (exit !== 0) {
175
- const stderr = (await new Response(proc.stderr).text()).trim();
176
- throw new Error(`tar extract failed (exit ${exit}): ${stderr || 'unknown error'}`);
177
- }
205
+ onProgress({ phase: 'verifying', message: `verifying SHA256 ${asset.sha256}` });
206
+ const actualSha = sha256(archiveBytes);
207
+ if (actualSha !== asset.sha256) {
208
+ throw new Error(`SHA256 mismatch: expected ${asset.sha256}, got ${actualSha}`);
209
+ }
178
210
 
179
- const extractedBinary = join(workDir, 'curl');
180
- if (!existsSync(extractedBinary)) {
181
- throw new Error('tar succeeded but curl binary not found in archive');
182
- }
211
+ onProgress({ phase: 'extracting', message: `extracting curl to ${binDir}` });
212
+ const tarBytes = await decompressXz(archiveBytes);
213
+ const curlBytes = findFileInTar(tarBytes, 'curl');
214
+ if (!curlBytes) {
215
+ throw new Error('curl binary not found in archive');
216
+ }
183
217
 
184
- // Atomic move — finalPath either exists and is valid, or doesn't exist.
185
- renameSync(extractedBinary, finalPath);
186
- chmodSync(finalPath, 0o755);
218
+ // Write via a sibling tmp path then rename, so finalPath is always
219
+ // either absent or a complete, valid binary.
220
+ const tmpPath = `${finalPath}.tmp-${process.pid}`;
221
+ await Bun.write(tmpPath, curlBytes);
222
+ chmodSync(tmpPath, 0o755);
223
+ renameSync(tmpPath, finalPath);
187
224
 
188
- onProgress({ phase: 'done', message: `curl installed at ${finalPath}` });
189
- debug.log('path', `static-curl: installed ${asset.archKey} v${asset.version} at ${finalPath}`);
190
- return binDir;
191
- } finally {
192
- try {
193
- rmSync(workDir, { recursive: true, force: true });
194
- } catch {
195
- // best-effort cleanup
196
- }
197
- }
225
+ onProgress({ phase: 'done', message: `curl installed at ${finalPath}` });
226
+ debug.log('path', `static-curl: installed ${asset.archKey} v${asset.version} at ${finalPath}`);
227
+ return binDir;
198
228
  }
@@ -23,7 +23,8 @@ const TOOL_UNION = t.Union([
23
23
  t.Literal('git'),
24
24
  t.Literal('claude'),
25
25
  t.Literal('opencode'),
26
- t.Literal('chrome')
26
+ t.Literal('chrome'),
27
+ t.Literal('cloudflared')
27
28
  ]);
28
29
 
29
30
  const STATUS_UNION = t.Union([
@@ -17,7 +17,8 @@ const TOOL_UNION = t.Union([
17
17
  t.Literal('git'),
18
18
  t.Literal('claude'),
19
19
  t.Literal('opencode'),
20
- t.Literal('chrome')
20
+ t.Literal('chrome'),
21
+ t.Literal('cloudflared')
21
22
  ]);
22
23
 
23
24
  const RECIPE_SCHEMA = t.Object({
@@ -66,7 +67,7 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
66
67
  })
67
68
  ]);
68
69
 
69
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
70
+ function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
70
71
  return {
71
72
  tool,
72
73
  autoInstallable: recipe.autoInstallable,
@@ -109,7 +110,7 @@ export const systemToolsStatusHandler = createRouter()
109
110
  })
110
111
  }, async () => {
111
112
  debug.log('path', 'system-tools:status-all');
112
- const ids = ['git', 'claude', 'opencode', 'chrome'] as const;
113
+ const ids = ['git', 'claude', 'opencode', 'chrome', 'cloudflared'] as const;
113
114
  const tools = await Promise.all(ids.map(async (id) => {
114
115
  const [status, recipe] = await Promise.all([
115
116
  getToolStatus(id),
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-D5uXex37.js","assets/main-CFh-PX_S.css"])))=>i.map(i=>d[i]);
2
- import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-D5uXex37.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-D5uXex37.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-D5uXex37.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-D5uXex37.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-D5uXex37.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-DhLx8wD1.js","assets/main-jTnmAoXS.css"])))=>i.map(i=>d[i]);
2
+ import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-DhLx8wD1.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-DhLx8wD1.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-DhLx8wD1.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-DhLx8wD1.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-DhLx8wD1.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};