@myrialabs/clopen 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,7 @@ import { join } from 'node:path';
19
19
  import { isElevated } from '$backend/utils/privilege';
20
20
  import { getClopenDir } from '$backend/utils/paths';
21
21
  import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
22
+ import { resolveStaticCurlAsset } from '$backend/utils/static-curl';
22
23
 
23
24
  export type ToolId = 'git' | 'claude' | 'opencode' | 'chrome';
24
25
 
@@ -38,12 +39,20 @@ export interface Recipe {
38
39
  /** Optional shell to wrap command (e.g. sh -c for pipe chains). */
39
40
  shell?: { program: string; args: string[] };
40
41
  /**
41
- * Fetch a remote script via Bun.fetch and pipe its body to the
42
- * interpreter's stdin. Used in place of `curl | bash` so clopen can
43
- * install tools like Claude/OpenCode without requiring curl to be
44
- * present on the system. Exclusive with `command`/`shell`.
42
+ * True when the install command (or script it downloads) shells out
43
+ * to `curl`. When set, the runner ensures curl is on PATH —
44
+ * downloading a SHA-pinned static curl from stunnel/static-curl if
45
+ * the system lacks one.
45
46
  */
46
- fetchAndPipe?: { url: string; interpreter: string[] };
47
+ requiresCurl?: boolean;
48
+ /**
49
+ * When requiresCurl is true and the system has no curl, this carries
50
+ * the pinned asset metadata so the frontend can surface URL + SHA256
51
+ * in the install confirmation dialog for explicit user consent.
52
+ * Undefined when system curl is already present or no asset covers
53
+ * the current platform/arch.
54
+ */
55
+ pendingCurlDownload?: { version: string; url: string; sha256: string; archKey: string };
47
56
  /** Human-readable command string for confirmation dialog preview. */
48
57
  displayCommand?: string;
49
58
  /** Extra env vars for the install subprocess. */
@@ -304,6 +313,29 @@ async function resolveGitRecipe(): Promise<Recipe> {
304
313
  return base;
305
314
  }
306
315
 
316
+ /**
317
+ * Populate `requiresCurl` and (when the system lacks curl) the pending
318
+ * static-curl download metadata. Returns false when this platform/arch
319
+ * has no pinned asset — caller should mark the recipe unavailable.
320
+ */
321
+ function attachCurlRequirement(base: Recipe, toolLabel: string): boolean {
322
+ base.requiresCurl = true;
323
+ if (resolveBinary('curl')) return true;
324
+
325
+ const asset = resolveStaticCurlAsset();
326
+ if (!asset) {
327
+ base.unavailableReason = `curl is required by the ${toolLabel} installer, and no static curl is available for ${process.platform}/${process.arch}.`;
328
+ return false;
329
+ }
330
+ base.pendingCurlDownload = {
331
+ version: asset.version,
332
+ url: asset.url,
333
+ sha256: asset.sha256,
334
+ archKey: asset.archKey
335
+ };
336
+ return true;
337
+ }
338
+
307
339
  async function resolveClaudeRecipe(): Promise<Recipe> {
308
340
  const base: Recipe = {
309
341
  tool: 'claude',
@@ -325,15 +357,17 @@ async function resolveClaudeRecipe(): Promise<Recipe> {
325
357
  return base;
326
358
  }
327
359
 
328
- // macOS / Linux — fetch the script via Bun.fetch and pipe it to bash
329
- // so curl does not need to be installed.
360
+ // macOS / Linux
330
361
  base.manualInstructions.push({
331
362
  label: 'curl + bash',
332
363
  command: 'curl -fsSL https://claude.ai/install.sh | bash',
333
364
  docs: 'https://docs.claude.com/en/docs/claude-code/overview'
334
365
  });
366
+ if (!attachCurlRequirement(base, 'Claude Code')) return base;
367
+
335
368
  base.autoInstallable = true;
336
- base.fetchAndPipe = { url: 'https://claude.ai/install.sh', interpreter: ['bash'] };
369
+ base.shell = { program: 'bash', args: ['-c'] };
370
+ base.command = ['curl -fsSL https://claude.ai/install.sh | bash'];
337
371
  base.displayCommand = 'curl -fsSL https://claude.ai/install.sh | bash';
338
372
  return base;
339
373
  }
@@ -355,8 +389,11 @@ async function resolveOpenCodeRecipe(): Promise<Recipe> {
355
389
  return base;
356
390
  }
357
391
 
392
+ if (!attachCurlRequirement(base, 'OpenCode')) return base;
393
+
358
394
  base.autoInstallable = true;
359
- base.fetchAndPipe = { url: 'https://opencode.ai/install', interpreter: ['bash'] };
395
+ base.shell = { program: 'bash', args: ['-c'] };
396
+ base.command = ['curl -fsSL https://opencode.ai/install | bash'];
360
397
  base.displayCommand = 'curl -fsSL https://opencode.ai/install | bash';
361
398
  return base;
362
399
  }
@@ -21,6 +21,7 @@ import { debug } from '$shared/utils/logger';
21
21
  import { ws } from '$backend/utils/ws';
22
22
  import { getCleanSpawnEnv } from '$backend/utils/env';
23
23
  import { refreshProcessPath } from '$backend/utils/path-enrich';
24
+ import { ensureCurlAvailable } from '$backend/utils/static-curl';
24
25
  import type { Recipe, ToolId } from './install-recipes';
25
26
  import { resolveRecipe } from './install-recipes';
26
27
 
@@ -194,78 +195,50 @@ async function runInstall(session: Session, env: Record<string, string>): Promis
194
195
  const { recipe } = session;
195
196
  let proc: ReturnType<typeof Bun.spawn>;
196
197
 
197
- if (recipe.fetchAndPipe) {
198
- const { url, interpreter } = recipe.fetchAndPipe;
199
- emitStream(session, 'stdout', `» fetching ${url}\n`);
200
-
201
- let body: string;
198
+ // Ensure curl is available when the recipe shells out to it. Prepends
199
+ // the static-curl directory to PATH when a managed binary is staged.
200
+ if (recipe.requiresCurl) {
202
201
  try {
203
- const response = await fetch(url, { redirect: 'follow' });
204
- if (!response.ok) {
205
- emitStream(session, 'stderr', `fetch failed: HTTP ${response.status} ${response.statusText}\n`);
206
- finalizeSession(session, 'failed', -1);
207
- return;
202
+ const curlDir = await ensureCurlAvailable((event) => {
203
+ emitStream(session, 'stdout', `» curl: ${event.message}\n`);
204
+ });
205
+ if (curlDir) {
206
+ env.PATH = `${curlDir}${process.platform === 'win32' ? ';' : ':'}${env.PATH ?? ''}`;
208
207
  }
209
- body = await response.text();
210
208
  } catch (err) {
211
- emitStream(session, 'stderr', `fetch error: ${err instanceof Error ? err.message : String(err)}\n`);
209
+ emitStream(session, 'stderr', `curl setup failed: ${err instanceof Error ? err.message : String(err)}\n`);
212
210
  finalizeSession(session, 'failed', -1);
213
211
  return;
214
212
  }
215
213
 
216
- // Cancel may have fired while the fetch was in flight.
214
+ // Cancel may have fired while curl was being staged.
217
215
  if (session.status !== 'running') {
218
216
  finalizeSession(session, session.status, -1);
219
217
  return;
220
218
  }
219
+ }
221
220
 
222
- emitStream(session, 'stdout', `» piping ${body.length} bytes to ${interpreter.join(' ')}\n`);
223
-
224
- try {
225
- proc = Bun.spawn(interpreter, {
226
- stdout: 'pipe',
227
- stderr: 'pipe',
228
- stdin: 'pipe',
229
- env
230
- });
231
- } catch (err) {
232
- emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);
233
- finalizeSession(session, 'failed', -1);
234
- return;
235
- }
236
-
237
- session.proc = proc;
238
-
239
- try {
240
- const stdin = proc.stdin as import('bun').FileSink;
241
- stdin.write(body);
242
- stdin.end();
243
- } catch (err) {
244
- debug.warn('path', `[install:${session.id}] stdin write error:`, err);
245
- }
246
- } else {
247
- const spawnArgs = recipe.shell
248
- ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command!]
249
- : recipe.command!;
250
-
251
- debug.log('path', `[install:${session.id}] Spawning: ${spawnArgs.join(' ')}`);
221
+ const spawnArgs = recipe.shell
222
+ ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command!]
223
+ : recipe.command!;
252
224
 
253
- try {
254
- proc = Bun.spawn(spawnArgs, {
255
- stdout: 'pipe',
256
- stderr: 'pipe',
257
- stdin: 'ignore',
258
- env
259
- });
260
- } catch (err) {
261
- emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);
262
- finalizeSession(session, 'failed', -1);
263
- return;
264
- }
225
+ debug.log('path', `[install:${session.id}] Spawning: ${spawnArgs.join(' ')}`);
265
226
 
266
- session.proc = proc;
227
+ try {
228
+ proc = Bun.spawn(spawnArgs, {
229
+ stdout: 'pipe',
230
+ stderr: 'pipe',
231
+ stdin: 'ignore',
232
+ env
233
+ });
234
+ } catch (err) {
235
+ emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);
236
+ finalizeSession(session, 'failed', -1);
237
+ return;
267
238
  }
268
239
 
240
+ session.proc = proc;
241
+
269
242
  const exitCode = await runStreamedProcess(session, proc);
270
243
  finalizeSession(session, exitCode === 0 ? 'success' : 'failed', exitCode);
271
244
  }
@@ -282,8 +255,7 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
282
255
  }
283
256
 
284
257
  const recipe = await resolveRecipe(tool);
285
- const hasExecutable = recipe.autoInstallable && (recipe.command || recipe.fetchAndPipe);
286
- if (!hasExecutable) {
258
+ if (!recipe.autoInstallable || !recipe.command) {
287
259
  throw new InstallNotAutoInstallableError(tool, recipe.unavailableReason ?? 'Not auto-installable on this platform');
288
260
  }
289
261
 
@@ -333,8 +305,8 @@ export function cancelInstall(sessionId: string): boolean {
333
305
  const session = sessions.get(sessionId);
334
306
  if (!session || session.status !== 'running') return false;
335
307
  session.status = 'cancelled';
336
- // `proc` may be null during the fetchAndPipe fetch phase; runInstall
337
- // re-checks status after fetch and finalizes accordingly.
308
+ // `proc` may be null during the static-curl download phase; runInstall
309
+ // re-checks status after each await and finalizes accordingly.
338
310
  if (session.proc) {
339
311
  try {
340
312
  session.proc.kill();
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Static curl binary management.
3
+ *
4
+ * Some install scripts clopen runs (notably OpenCode's) invoke `curl`
5
+ * internally. When the host system lacks curl and cannot install it
6
+ * non-interactively (e.g. Linux without root), clopen falls back to
7
+ * downloading a verified static curl binary from the stunnel/static-curl
8
+ * project into ~/.clopen/bin/curl and prepends that directory to PATH
9
+ * when spawning the install subprocess.
10
+ *
11
+ * Supply-chain hardening:
12
+ * - Version + SHA256 for each arch is pinned in source. If the remote
13
+ * asset ever changes the hash mismatch aborts the download and the
14
+ * cached/final file is never touched.
15
+ * - stunnel/static-curl is a reproducible-build project maintained by
16
+ * the stunnel team. Release: https://github.com/stunnel/static-curl
17
+ */
18
+
19
+ import { existsSync, readdirSync, mkdirSync, mkdtempSync, chmodSync, renameSync, rmSync } from 'node:fs';
20
+ import { join, dirname } from 'node:path';
21
+ import { tmpdir } from 'node:os';
22
+ import { debug } from '$shared/utils/logger';
23
+ import { getClopenDir } from '$backend/utils/paths';
24
+ import { resolveBinary } from '$backend/utils/cli';
25
+
26
+ export const STATIC_CURL_VERSION = '8.19.0';
27
+
28
+ export interface StaticCurlAsset {
29
+ /** Key like "linux-x86_64-glibc". */
30
+ archKey: string;
31
+ url: string;
32
+ sha256: string;
33
+ version: string;
34
+ }
35
+
36
+ function makeAsset(archKey: string, sha256: string): StaticCurlAsset {
37
+ return {
38
+ archKey,
39
+ url: `https://github.com/stunnel/static-curl/releases/download/${STATIC_CURL_VERSION}/curl-${archKey}-${STATIC_CURL_VERSION}.tar.xz`,
40
+ sha256,
41
+ version: STATIC_CURL_VERSION
42
+ };
43
+ }
44
+
45
+ // Hashes verified by downloading each archive and computing shasum -a 256
46
+ // against stunnel/static-curl 8.19.0 release on 2026-04-23.
47
+ const PINNED_ASSETS: Record<string, StaticCurlAsset> = {
48
+ 'linux-x86_64-glibc': makeAsset('linux-x86_64-glibc', '9c70e3ac08a6d8e211a891fe2fc871a9cd3314c291adb5bb1a38e7355ce98ff7'),
49
+ 'linux-x86_64-musl': makeAsset('linux-x86_64-musl', '477cf25c53e438b5293610faadf4b932009973c08e8be3a283afa25189aa85da'),
50
+ 'linux-aarch64-glibc': makeAsset('linux-aarch64-glibc', '46873008eae6b7eb586aa56ce8787bdb8c1eccb52faf7055b32b6470c1b84cd6'),
51
+ 'linux-aarch64-musl': makeAsset('linux-aarch64-musl', '592b12257e97de01f73f681800b6f7ba43347e5880100cca4d33c6fec3eb286b'),
52
+ 'linux-armv7-glibc': makeAsset('linux-armv7-glibc', 'fae4fd7f25c8a8744f53d5b5c8cefe3bed924d9e028165eac4fef8bd6b77e51b'),
53
+ 'linux-armv7-musl': makeAsset('linux-armv7-musl', 'eb0d2ab30f849bda6c56aa098cf7512720721476a4e4449515c91d117c1454e1')
54
+ };
55
+
56
+ function detectLibc(): 'glibc' | 'musl' {
57
+ // Alpine ships a sentinel file; other musl-based distros expose the
58
+ // musl dynamic loader at well-known locations.
59
+ if (existsSync('/etc/alpine-release')) return 'musl';
60
+ for (const dir of ['/lib', '/usr/lib', '/lib64', '/usr/lib64']) {
61
+ try {
62
+ if (readdirSync(dir).some((f) => f.startsWith('ld-musl-'))) return 'musl';
63
+ } catch {
64
+ // Directory missing — not fatal, try the next.
65
+ }
66
+ }
67
+ return 'glibc';
68
+ }
69
+
70
+ function detectArchKey(): string | null {
71
+ if (process.platform !== 'linux') return null;
72
+ const libc = detectLibc();
73
+ let arch: string;
74
+ switch (process.arch) {
75
+ case 'x64': arch = 'x86_64'; break;
76
+ case 'arm64': arch = 'aarch64'; break;
77
+ case 'arm': arch = 'armv7'; break;
78
+ default: return null;
79
+ }
80
+ return `linux-${arch}-${libc}`;
81
+ }
82
+
83
+ /**
84
+ * Resolve the pinned asset metadata for the current platform/arch, or
85
+ * null when this platform is not covered (macOS, Windows, exotic arches).
86
+ */
87
+ export function resolveStaticCurlAsset(): StaticCurlAsset | null {
88
+ const key = detectArchKey();
89
+ if (!key) return null;
90
+ return PINNED_ASSETS[key] ?? null;
91
+ }
92
+
93
+ export function getStaticCurlPath(): string {
94
+ return join(getClopenDir(), 'bin', 'curl');
95
+ }
96
+
97
+ export function hasCachedStaticCurl(): boolean {
98
+ return existsSync(getStaticCurlPath());
99
+ }
100
+
101
+ async function sha256OfFile(path: string): Promise<string> {
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);
109
+ }
110
+ } finally {
111
+ reader.releaseLock();
112
+ }
113
+ return hasher.digest('hex');
114
+ }
115
+
116
+ export type CurlProgressPhase = 'cached' | 'fetching' | 'verifying' | 'extracting' | 'done';
117
+
118
+ export interface CurlProgressEvent {
119
+ phase: CurlProgressPhase;
120
+ message: string;
121
+ }
122
+
123
+ /**
124
+ * Ensure curl is available for a subprocess. Returns the directory that
125
+ * should be prepended to PATH (null when the system already has curl and
126
+ * no action is required).
127
+ *
128
+ * Throws if the platform has no pinned static curl, if the download
129
+ * fails, or if SHA256 verification fails. Never leaves a partially
130
+ * extracted file at the final path.
131
+ */
132
+ export async function ensureCurlAvailable(
133
+ onProgress: (event: CurlProgressEvent) => void
134
+ ): Promise<string | null> {
135
+ if (resolveBinary('curl')) return null;
136
+
137
+ const asset = resolveStaticCurlAsset();
138
+ if (!asset) {
139
+ throw new Error(`No static curl binary available for ${process.platform}/${process.arch}`);
140
+ }
141
+
142
+ const finalPath = getStaticCurlPath();
143
+ const binDir = dirname(finalPath);
144
+
145
+ if (hasCachedStaticCurl()) {
146
+ onProgress({ phase: 'cached', message: `using cached curl at ${finalPath}` });
147
+ return binDir;
148
+ }
149
+
150
+ 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
+
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
+ }
167
+
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
+ }
178
+
179
+ const extractedBinary = join(workDir, 'curl');
180
+ if (!existsSync(extractedBinary)) {
181
+ throw new Error('tar succeeded but curl binary not found in archive');
182
+ }
183
+
184
+ // Atomic move — finalPath either exists and is valid, or doesn't exist.
185
+ renameSync(extractedBinary, finalPath);
186
+ chmodSync(finalPath, 0o755);
187
+
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
+ }
198
+ }
@@ -30,6 +30,12 @@ const RECIPE_SCHEMA = t.Object({
30
30
  label: t.String(),
31
31
  command: t.String(),
32
32
  docs: t.Optional(t.String())
33
+ })),
34
+ pendingCurlDownload: t.Optional(t.Object({
35
+ version: t.String(),
36
+ url: t.String(),
37
+ sha256: t.String(),
38
+ archKey: t.String()
33
39
  }))
34
40
  });
35
41
 
@@ -67,7 +73,8 @@ function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome', recipe: Awa
67
73
  unavailableReason: recipe.unavailableReason,
68
74
  displayCommand: recipe.displayCommand,
69
75
  missingPrereqs: recipe.missingPrereqs,
70
- manualInstructions: recipe.manualInstructions
76
+ manualInstructions: recipe.manualInstructions,
77
+ pendingCurlDownload: recipe.pendingCurlDownload
71
78
  };
72
79
  }
73
80
 
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-Be2TrEVr.js","assets/main-C184xHqk.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-Be2TrEVr.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-Be2TrEVr.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-Be2TrEVr.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-Be2TrEVr.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-Be2TrEVr.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-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};