@myrialabs/clopen 0.3.3 → 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.
@@ -0,0 +1,248 @@
1
+ /**
2
+ * PATH Enrichment
3
+ *
4
+ * Ensures process.env.PATH contains the directories where CLI tools we care
5
+ * about are typically installed, regardless of how clopen was launched
6
+ * (GUI app, systemd service, docker/Railway container, cron, login shell,
7
+ * …). Downstream consumers — Bun.which, Bun.spawn, getCleanSpawnEnv,
8
+ * bun-pty — then see a PATH that matches reality on every platform.
9
+ *
10
+ * Strategy (in order, dedup'd, prepended so new entries win):
11
+ * 1. Known install directories: deterministic list of locations used by
12
+ * common installers and package managers (our System Tools installer,
13
+ * `curl | bash` scripts, Homebrew, Scoop, winget links, cargo, bun,
14
+ * deno, volta, yarn, nvm/fnm node versions, …). Existing entries only.
15
+ * 2. Harvested shell PATH: on Unix desktops where the user has custom
16
+ * rc-file PATH additions that aren't in our known list. Cached once
17
+ * per process — shell config rarely changes mid-session, and spawning
18
+ * a shell on every status call is both slow and spammy in logs when
19
+ * the environment has no usable shell (containers, minimal images).
20
+ * Skipped silently on Windows, when no valid shell is found, or when
21
+ * CLOPEN_SKIP_PATH_HARVEST=1.
22
+ * 3. Existing process.env.PATH: preserved as fallback.
23
+ *
24
+ * Concurrency: refreshProcessPath() dedups via an in-flight promise so
25
+ * parallel callers share one pass. Known-dir enumeration happens every
26
+ * call so tools installed at runtime (via System Tools) become visible
27
+ * without a restart.
28
+ */
29
+
30
+ import { existsSync, statSync } from 'node:fs';
31
+ import { readdir } from 'node:fs/promises';
32
+ import { homedir, userInfo } from 'node:os';
33
+ import { join } from 'node:path';
34
+ import { debug } from '$shared/utils/logger';
35
+ import { getClopenDir } from './paths';
36
+
37
+ const SEP = process.platform === 'win32' ? ';' : ':';
38
+ const HARVEST_TIMEOUT_MS = 2000;
39
+
40
+ // Cached once per process — see file header for rationale.
41
+ let harvestAttempted = false;
42
+ let harvestedPath: string | null = null;
43
+
44
+ let inFlight: Promise<void> | null = null;
45
+
46
+ function posixKnownDirs(): string[] {
47
+ const home = homedir();
48
+ return [
49
+ // clopen-managed binaries (cloudflared, future CLI installs)
50
+ join(getClopenDir(), 'bin'),
51
+ // install-script targets
52
+ join(home, '.local', 'bin'),
53
+ join(home, '.opencode', 'bin'),
54
+ // user-scoped runtimes / package managers
55
+ join(home, '.bun', 'bin'),
56
+ join(home, '.deno', 'bin'),
57
+ join(home, '.cargo', 'bin'),
58
+ join(home, '.volta', 'bin'),
59
+ join(home, '.yarn', 'bin'),
60
+ join(home, 'go', 'bin'),
61
+ // system package managers
62
+ '/opt/homebrew/bin',
63
+ '/opt/homebrew/sbin',
64
+ '/usr/local/bin',
65
+ '/usr/local/sbin',
66
+ '/home/linuxbrew/.linuxbrew/bin',
67
+ '/home/linuxbrew/.linuxbrew/sbin',
68
+ '/usr/local/go/bin',
69
+ // standard system dirs (usually inherited, but belt-and-suspenders)
70
+ '/usr/bin',
71
+ '/usr/sbin',
72
+ '/bin',
73
+ '/sbin'
74
+ ];
75
+ }
76
+
77
+ function windowsKnownDirs(): string[] {
78
+ const home = homedir();
79
+ const localAppData = process.env['LOCALAPPDATA'] ?? join(home, 'AppData', 'Local');
80
+ const appData = process.env['APPDATA'] ?? join(home, 'AppData', 'Roaming');
81
+ const programFiles = process.env['PROGRAMFILES'] ?? 'C:\\Program Files';
82
+ return [
83
+ join(getClopenDir(), 'bin'),
84
+ join(home, '.bun', 'bin'),
85
+ join(home, '.deno', 'bin'),
86
+ join(home, '.cargo', 'bin'),
87
+ join(home, 'scoop', 'shims'),
88
+ join(localAppData, 'Microsoft', 'WinGet', 'Links'),
89
+ join(localAppData, 'Programs', 'Git', 'cmd'),
90
+ join(programFiles, 'Git', 'cmd'),
91
+ join(appData, 'npm')
92
+ ];
93
+ }
94
+
95
+ // Version managers keep per-version bin dirs; enumerate children.
96
+ async function versionManagerDirs(): Promise<string[]> {
97
+ if (process.platform === 'win32') return [];
98
+ const home = homedir();
99
+ const out: string[] = [];
100
+
101
+ const bases: Array<{ base: string; tail: string[] }> = [
102
+ { base: join(home, '.nvm', 'versions', 'node'), tail: ['bin'] },
103
+ { base: join(home, '.fnm', 'node-versions'), tail: ['installation', 'bin'] },
104
+ { base: join(home, '.asdf', 'installs'), tail: [] }
105
+ ];
106
+
107
+ for (const { base, tail } of bases) {
108
+ if (!existsSync(base)) continue;
109
+ try {
110
+ const entries = await readdir(base, { withFileTypes: true });
111
+ for (const e of entries) {
112
+ if (!e.isDirectory()) continue;
113
+ const candidate = join(base, e.name, ...tail);
114
+ if (tail.length > 0) {
115
+ if (existsSync(candidate)) out.push(candidate);
116
+ } else {
117
+ // asdf: ~/.asdf/installs/<tool>/<version>/bin — glob one more level
118
+ try {
119
+ const versions = await readdir(candidate, { withFileTypes: true });
120
+ for (const v of versions) {
121
+ if (!v.isDirectory()) continue;
122
+ const bin = join(candidate, v.name, 'bin');
123
+ if (existsSync(bin)) out.push(bin);
124
+ }
125
+ } catch { /* ignore */ }
126
+ }
127
+ }
128
+ } catch { /* ignore */ }
129
+ }
130
+
131
+ return out;
132
+ }
133
+
134
+ function isValidShellPath(shell: string | null | undefined): shell is string {
135
+ if (!shell) return false;
136
+ if (shell === 'unknown') return false;
137
+ if (!shell.startsWith('/')) return false;
138
+ try {
139
+ return statSync(shell).isFile();
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+
145
+ function resolveUserShell(): string | null {
146
+ const envShell = process.env.SHELL;
147
+ if (isValidShellPath(envShell)) return envShell;
148
+ try {
149
+ const info = userInfo();
150
+ if (isValidShellPath(info.shell)) return info.shell;
151
+ } catch { /* userInfo() can throw on some platforms */ }
152
+ return null;
153
+ }
154
+
155
+ async function harvestShellPath(): Promise<string | null> {
156
+ if (process.platform === 'win32') return null;
157
+ if (process.env.CLOPEN_SKIP_PATH_HARVEST === '1') return null;
158
+
159
+ const shell = resolveUserShell();
160
+ if (!shell) return null;
161
+
162
+ const controller = new AbortController();
163
+ const timer = setTimeout(() => controller.abort(), HARVEST_TIMEOUT_MS);
164
+
165
+ try {
166
+ // -i sources rc files (.bashrc/.zshrc); -l sources login files
167
+ // (.profile/.zprofile/.bash_profile). printf %s yields PATH cleanly;
168
+ // rc banners go to stderr (ignored) or appear before our printf.
169
+ const proc = Bun.spawn([shell, '-ilc', 'printf %s "$PATH"'], {
170
+ stdout: 'pipe',
171
+ stderr: 'ignore',
172
+ signal: controller.signal
173
+ });
174
+
175
+ const [stdout, exitCode] = await Promise.all([
176
+ new Response(proc.stdout).text(),
177
+ proc.exited
178
+ ]);
179
+
180
+ if (exitCode !== 0) return null;
181
+
182
+ const lines = stdout.split('\n').map(l => l.trim()).filter(Boolean);
183
+ const path = lines[lines.length - 1] ?? '';
184
+ if (!path.includes('/')) return null;
185
+ return path;
186
+ } catch {
187
+ return null;
188
+ } finally {
189
+ clearTimeout(timer);
190
+ }
191
+ }
192
+
193
+ function splitPath(path: string | undefined | null): string[] {
194
+ if (!path) return [];
195
+ return path.split(SEP).map(s => s.trim()).filter(Boolean);
196
+ }
197
+
198
+ function filterExisting(dirs: string[]): string[] {
199
+ const out: string[] = [];
200
+ for (const d of dirs) {
201
+ try {
202
+ if (existsSync(d)) out.push(d);
203
+ } catch { /* ignore */ }
204
+ }
205
+ return out;
206
+ }
207
+
208
+ function applyToProcess(prepend: string[]): void {
209
+ const existing = splitPath(process.env.PATH);
210
+ const seen = new Set<string>();
211
+ const merged: string[] = [];
212
+ for (const entry of [...prepend, ...existing]) {
213
+ if (seen.has(entry)) continue;
214
+ seen.add(entry);
215
+ merged.push(entry);
216
+ }
217
+ const next = merged.join(SEP);
218
+ if (next !== (process.env.PATH ?? '')) {
219
+ process.env.PATH = next;
220
+ debug.log('path', `PATH enriched (${merged.length} entries)`);
221
+ }
222
+ }
223
+
224
+ async function doEnrich(): Promise<void> {
225
+ const known = process.platform === 'win32' ? windowsKnownDirs() : posixKnownDirs();
226
+ const vmDirs = await versionManagerDirs();
227
+ const existingKnown = filterExisting([...known, ...vmDirs]);
228
+
229
+ if (!harvestAttempted) {
230
+ harvestAttempted = true;
231
+ harvestedPath = await harvestShellPath();
232
+ }
233
+ const harvested = splitPath(harvestedPath);
234
+
235
+ applyToProcess([...existingKnown, ...harvested]);
236
+ }
237
+
238
+ /**
239
+ * Enrich process.env.PATH so downstream Bun.which / Bun.spawn calls see
240
+ * the same binaries a terminal user would. Safe to call repeatedly —
241
+ * concurrent callers share one in-flight promise.
242
+ */
243
+ export async function refreshProcessPath(): Promise<void> {
244
+ if (!inFlight) {
245
+ inFlight = doEnrich().finally(() => { inFlight = null; });
246
+ }
247
+ return inFlight;
248
+ }
@@ -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
+ }
@@ -23,8 +23,7 @@ const TOOL_UNION = t.Union([
23
23
  t.Literal('git'),
24
24
  t.Literal('claude'),
25
25
  t.Literal('opencode'),
26
- t.Literal('chrome'),
27
- t.Literal('curl')
26
+ t.Literal('chrome')
28
27
  ]);
29
28
 
30
29
  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, chrome, curl). 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,8 +17,7 @@ const TOOL_UNION = t.Union([
17
17
  t.Literal('git'),
18
18
  t.Literal('claude'),
19
19
  t.Literal('opencode'),
20
- t.Literal('chrome'),
21
- t.Literal('curl')
20
+ t.Literal('chrome')
22
21
  ]);
23
22
 
24
23
  const RECIPE_SCHEMA = t.Object({
@@ -31,6 +30,12 @@ const RECIPE_SCHEMA = t.Object({
31
30
  label: t.String(),
32
31
  command: t.String(),
33
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()
34
39
  }))
35
40
  });
36
41
 
@@ -61,14 +66,15 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
61
66
  })
62
67
  ]);
63
68
 
64
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome' | 'curl', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
69
+ function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
65
70
  return {
66
71
  tool,
67
72
  autoInstallable: recipe.autoInstallable,
68
73
  unavailableReason: recipe.unavailableReason,
69
74
  displayCommand: recipe.displayCommand,
70
75
  missingPrereqs: recipe.missingPrereqs,
71
- manualInstructions: recipe.manualInstructions
76
+ manualInstructions: recipe.manualInstructions,
77
+ pendingCurlDownload: recipe.pendingCurlDownload
72
78
  };
73
79
  }
74
80
 
@@ -103,7 +109,7 @@ export const systemToolsStatusHandler = createRouter()
103
109
  })
104
110
  }, async () => {
105
111
  debug.log('path', 'system-tools:status-all');
106
- const ids = ['git', 'claude', 'opencode', 'chrome', 'curl'] as const;
112
+ const ids = ['git', 'claude', 'opencode', 'chrome'] as const;
107
113
  const tools = await Promise.all(ids.map(async (id) => {
108
114
  const [status, recipe] = await Promise.all([
109
115
  getToolStatus(id),
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-Cmzf1wb_.js","assets/main-w1JNDH4Y.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-Cmzf1wb_.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-Cmzf1wb_.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-Cmzf1wb_.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-Cmzf1wb_.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-Cmzf1wb_.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};