@myrialabs/clopen 0.3.6 → 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.
@@ -19,7 +19,7 @@ import type { Browser, BrowserContext, Page } from 'puppeteer';
19
19
  import { debug } from '$shared/utils/logger';
20
20
  import puppeteer from 'puppeteer-extra';
21
21
  import StealthPlugin from 'puppeteer-extra-plugin-stealth';
22
- import { getChromiumExecutablePath } from '$backend/engine/install-recipes';
22
+ import { getChromeExecutablePath } from '$backend/engine/install-recipes';
23
23
 
24
24
  puppeteer.use(StealthPlugin());
25
25
 
@@ -45,9 +45,9 @@ const DEFAULT_CONFIG: PoolConfig = {
45
45
  };
46
46
 
47
47
  /**
48
- * Chromium launch arguments for stealth (matches test-cf.ts exactly)
48
+ * Chrome launch arguments for stealth (matches test-cf.ts exactly)
49
49
  */
50
- const CHROMIUM_ARGS = [
50
+ const CHROME_ARGS = [
51
51
  '--no-sandbox',
52
52
  '--disable-blink-features=AutomationControlled',
53
53
  '--window-size=1366,768',
@@ -99,18 +99,19 @@ class BrowserPool {
99
99
  private async launchBrowser(): Promise<Browser> {
100
100
  debug.log('preview', '🚀 Launching browser with puppeteer-extra + StealthPlugin...');
101
101
 
102
- // Use the clopen-managed Chromium under ~/.clopen/bin (macOS/Windows)
103
- // or the system Chromium installed via the distro package manager (Linux).
104
- const executablePath = getChromiumExecutablePath();
102
+ // Use the clopen-managed Chrome for Testing under ~/.clopen/bin
103
+ // (macOS/Windows) or the system Google Chrome / chromium installed
104
+ // via the distro package manager (Linux).
105
+ const executablePath = getChromeExecutablePath();
105
106
  if (!executablePath) {
106
- throw new Error('Chromium not installed. Go to Settings → System Tools and click Install.');
107
+ throw new Error('Chrome not installed. Go to Settings → System Tools and click Install.');
107
108
  }
108
- debug.log('preview', ` using Chromium at: ${executablePath}`);
109
+ debug.log('preview', ` using Chrome at: ${executablePath}`);
109
110
 
110
111
  const browser = await puppeteer.launch({
111
112
  headless: true,
112
113
  executablePath,
113
- args: CHROMIUM_ARGS
114
+ args: CHROME_ARGS
114
115
  }) as unknown as Browser;
115
116
 
116
117
  debug.log('preview', '✅ Browser launched successfully');
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * Cloudflared Binary Manager
3
3
  *
4
- * Handles downloading and managing the cloudflared binary.
5
- * Replaces the `cloudflared` npm package for binary management.
4
+ * Handles resolving and managing the cloudflared binary.
6
5
  *
7
- * Binary is stored in ~/.clopen/bin/cloudflared (or .clopen-dev for dev)
8
- * Downloads from GitHub releases: https://github.com/cloudflare/cloudflared/releases
6
+ * Primary install path is ~/.clopen/bin/cloudflared (.clopen-dev in dev), which
7
+ * the System Tools installer downloads from GitHub releases. A system-wide
8
+ * cloudflared (e.g. brew, apt) is also honored via PATH so users who already
9
+ * have it on their machine don't have to install through clopen.
10
+ *
11
+ * installBinary() is kept for programmatic use (CLI, one-off scripts) but
12
+ * the server never auto-downloads — tunnel flows fail with a pointer to
13
+ * Settings → System Tools when the binary is missing.
9
14
  */
10
15
 
11
16
  import { existsSync, mkdirSync, createWriteStream, chmodSync, unlinkSync, renameSync } from 'fs';
@@ -13,6 +18,7 @@ import { join, dirname } from 'path';
13
18
  import { platform, arch } from 'os';
14
19
  import { execSync } from 'child_process';
15
20
  import { getClopenDir } from '../../utils/paths';
21
+ import { resolveBinary } from '../../utils/cli';
16
22
  import { debug } from '$shared/utils/logger';
17
23
 
18
24
  const RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/';
@@ -47,6 +53,18 @@ export function isBinaryInstalled(): boolean {
47
53
  return existsSync(getBinaryPath());
48
54
  }
49
55
 
56
+ /**
57
+ * Resolve an executable cloudflared binary. Prefers the System Tools install
58
+ * under ~/.clopen/bin; falls back to any cloudflared on PATH so users who
59
+ * installed it via brew/apt/winget don't have to reinstall via clopen.
60
+ * Returns null when nothing is found.
61
+ */
62
+ export function resolveCloudflaredBinary(): string | null {
63
+ const managed = getBinaryPath();
64
+ if (existsSync(managed)) return managed;
65
+ return resolveBinary('cloudflared');
66
+ }
67
+
50
68
  /** Download a file via HTTPS, following redirects */
51
69
  function download(url: string, to: string, redirect = 0): Promise<string> {
52
70
  if (redirect > 10) {
@@ -5,9 +5,10 @@
5
5
  * Provides binary management and tunnel process control.
6
6
  */
7
7
 
8
- export { getBinaryPath, isBinaryInstalled, installBinary } from './binary';
8
+ export { getBinaryPath, isBinaryInstalled, installBinary, resolveCloudflaredBinary } from './binary';
9
9
  export {
10
10
  CloudflaredTunnel,
11
+ CloudflaredMissingError,
11
12
  type ConnectionInfo,
12
13
  type LoginHandle,
13
14
  type LoginCallbacks,
@@ -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
  }
@@ -66,7 +66,7 @@ export const wsRouter = createRouter()
66
66
  // AI Engine Management
67
67
  .merge(engineRouter)
68
68
 
69
- // System Tools (install Git, Claude Code, OpenCode, Chromium binaries)
69
+ // System Tools (install Git, Claude Code, OpenCode, Chrome binaries)
70
70
  .merge(systemToolsRouter);
71
71
 
72
72
  // Export API type for frontend type-safe access
@@ -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('chromium')
26
+ t.Literal('chrome'),
27
+ t.Literal('cloudflared')
27
28
  ]);
28
29
 
29
30
  const STATUS_UNION = t.Union([
@@ -2,7 +2,7 @@
2
2
  * System Tool Status Handlers
3
3
  *
4
4
  * Reports installation status for each managed tool (git, claude,
5
- * opencode, chromium). The corresponding recipe is bundled so the
5
+ * opencode, chrome). The corresponding recipe is bundled so the
6
6
  * frontend can render the install button state and manual fallback
7
7
  * without a second round-trip.
8
8
  */
@@ -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('chromium')
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' | 'chromium', 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', 'chromium'] 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-cQx6vfxB.js","assets/main-B3tMwjjU.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-cQx6vfxB.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-cQx6vfxB.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-cQx6vfxB.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-cQx6vfxB.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-cQx6vfxB.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};