@myrialabs/clopen 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/backend/auth/permissions.ts +7 -1
- package/backend/engine/adapters/opencode/message-converter.ts +26 -0
- package/backend/engine/adapters/opencode/server.ts +5 -2
- package/backend/engine/install-recipes.ts +393 -0
- package/backend/engine/install-runner.ts +362 -0
- package/backend/git/git-executor.ts +2 -1
- package/backend/index.ts +10 -0
- package/backend/preview/browser/browser-pool.ts +13 -5
- package/backend/utils/cli.ts +28 -5
- package/backend/utils/path-enrich.ts +248 -0
- package/backend/utils/privilege.ts +51 -0
- package/backend/ws/engine/claude/accounts.ts +2 -1
- package/backend/ws/index.ts +5 -1
- package/backend/ws/system-tools/index.ts +16 -0
- package/backend/ws/system-tools/install.ts +122 -0
- package/backend/ws/system-tools/status.ts +118 -0
- package/dist/assets/{index-7DYhZPkW.js → index-D4V47e9n.js} +2 -2
- package/dist/assets/{main-8urnNoR7.js → main-Be2TrEVr.js} +175 -167
- package/dist/assets/main-C184xHqk.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +2 -0
- package/shared/utils/logger.ts +2 -1
- package/dist/assets/main-TEa2MRnh.css +0 -1
|
@@ -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,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Privilege Detection
|
|
3
|
+
*
|
|
4
|
+
* Determines whether the clopen server process is running with elevated
|
|
5
|
+
* privileges (root on Unix, Administrator on Windows). Used by the
|
|
6
|
+
* install-runner to decide whether a package manager invocation that
|
|
7
|
+
* requires privilege (apt, choco) can realistically succeed in the
|
|
8
|
+
* current non-interactive spawn mode.
|
|
9
|
+
*
|
|
10
|
+
* Cached for the process lifetime — elevation status does not change
|
|
11
|
+
* while the process is running.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { debug } from '$shared/utils/logger';
|
|
15
|
+
|
|
16
|
+
let cached: boolean | null = null;
|
|
17
|
+
|
|
18
|
+
async function detectElevatedWindows(): Promise<boolean> {
|
|
19
|
+
try {
|
|
20
|
+
const proc = Bun.spawn(['net', 'session'], {
|
|
21
|
+
stdout: 'ignore',
|
|
22
|
+
stderr: 'ignore'
|
|
23
|
+
});
|
|
24
|
+
const exitCode = await proc.exited;
|
|
25
|
+
return exitCode === 0;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function detectElevatedUnix(): boolean {
|
|
32
|
+
try {
|
|
33
|
+
const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
|
|
34
|
+
return typeof getuid === 'function' && getuid.call(process) === 0;
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Returns true when the process is running elevated (root/Administrator).
|
|
42
|
+
* First call performs detection; subsequent calls return the cached value.
|
|
43
|
+
*/
|
|
44
|
+
export async function isElevated(): Promise<boolean> {
|
|
45
|
+
if (cached !== null) return cached;
|
|
46
|
+
cached = process.platform === 'win32'
|
|
47
|
+
? await detectElevatedWindows()
|
|
48
|
+
: detectElevatedUnix();
|
|
49
|
+
debug.log('path', `Privilege detection: ${cached ? 'elevated' : 'non-elevated'}`);
|
|
50
|
+
return cached;
|
|
51
|
+
}
|
|
@@ -19,6 +19,7 @@ import { createRouter } from '$shared/utils/ws-server';
|
|
|
19
19
|
import { ws } from '$backend/utils/ws';
|
|
20
20
|
import { engineQueries } from '../../../database/queries';
|
|
21
21
|
import { resetEnvironment, getClaudeUserConfigDir } from '../../../engine/adapters/claude/environment';
|
|
22
|
+
import { resolveBinaryWithRefresh } from '../../../utils/cli';
|
|
22
23
|
import { debug } from '$shared/utils/logger';
|
|
23
24
|
import { getCleanSpawnEnv } from '../../../utils/env';
|
|
24
25
|
|
|
@@ -190,7 +191,7 @@ export const accountsHandler = createRouter()
|
|
|
190
191
|
ptyEnv['CLAUDE_CONFIG_DIR'] = getClaudeUserConfigDir();
|
|
191
192
|
ptyEnv['BROWSER'] = 'false';
|
|
192
193
|
|
|
193
|
-
const claudeCmd =
|
|
194
|
+
const claudeCmd = await resolveBinaryWithRefresh('claude');
|
|
194
195
|
if (!claudeCmd) throw new Error('claude binary not found on PATH');
|
|
195
196
|
let pty: ReturnType<typeof spawn>;
|
|
196
197
|
try {
|
package/backend/ws/index.ts
CHANGED
|
@@ -28,6 +28,7 @@ import { systemRouter } from './system';
|
|
|
28
28
|
import { tunnelRouter } from './tunnel';
|
|
29
29
|
import { gitRouter } from './git';
|
|
30
30
|
import { engineRouter } from './engine';
|
|
31
|
+
import { systemToolsRouter } from './system-tools';
|
|
31
32
|
|
|
32
33
|
// ============================================
|
|
33
34
|
// Main App Router - Merge All Module Routers
|
|
@@ -63,7 +64,10 @@ export const wsRouter = createRouter()
|
|
|
63
64
|
.merge(gitRouter)
|
|
64
65
|
|
|
65
66
|
// AI Engine Management
|
|
66
|
-
.merge(engineRouter)
|
|
67
|
+
.merge(engineRouter)
|
|
68
|
+
|
|
69
|
+
// System Tools (install Git, Claude Code, OpenCode, Chrome binaries)
|
|
70
|
+
.merge(systemToolsRouter);
|
|
67
71
|
|
|
68
72
|
// Export API type for frontend type-safe access
|
|
69
73
|
export type WSAPI = typeof wsRouter['$api'];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Tools Router
|
|
3
|
+
*
|
|
4
|
+
* Entry point for install-related WebSocket handlers:
|
|
5
|
+
* - system-tools:status / status-all — detection + recipe
|
|
6
|
+
* - system-tools:install-start / install-cancel / install-session
|
|
7
|
+
* - Server → client stream events
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
11
|
+
import { systemToolsStatusHandler } from './status';
|
|
12
|
+
import { systemToolsInstallHandler } from './install';
|
|
13
|
+
|
|
14
|
+
export const systemToolsRouter = createRouter()
|
|
15
|
+
.merge(systemToolsStatusHandler)
|
|
16
|
+
.merge(systemToolsInstallHandler);
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Tool Install Handlers
|
|
3
|
+
*
|
|
4
|
+
* HTTP-style routes start/cancel installs and look up session state.
|
|
5
|
+
* Server → client events stream stdout/stderr lines and signal the
|
|
6
|
+
* final status. Install sessions are created on the backend and keyed
|
|
7
|
+
* by a server-generated session id; clients only pick the tool id.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
12
|
+
import { ws } from '$backend/utils/ws';
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
import {
|
|
15
|
+
startInstall,
|
|
16
|
+
cancelInstall,
|
|
17
|
+
getSession,
|
|
18
|
+
InstallAlreadyRunningError,
|
|
19
|
+
InstallNotAutoInstallableError
|
|
20
|
+
} from '$backend/engine/install-runner';
|
|
21
|
+
|
|
22
|
+
const TOOL_UNION = t.Union([
|
|
23
|
+
t.Literal('git'),
|
|
24
|
+
t.Literal('claude'),
|
|
25
|
+
t.Literal('opencode'),
|
|
26
|
+
t.Literal('chrome')
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
const STATUS_UNION = t.Union([
|
|
30
|
+
t.Literal('running'),
|
|
31
|
+
t.Literal('success'),
|
|
32
|
+
t.Literal('failed'),
|
|
33
|
+
t.Literal('cancelled')
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
export const systemToolsInstallHandler = createRouter()
|
|
37
|
+
|
|
38
|
+
.http('system-tools:install-start', {
|
|
39
|
+
data: t.Object({ tool: TOOL_UNION }),
|
|
40
|
+
response: t.Object({
|
|
41
|
+
sessionId: t.String(),
|
|
42
|
+
tool: TOOL_UNION,
|
|
43
|
+
displayCommand: t.String(),
|
|
44
|
+
startedAt: t.Number()
|
|
45
|
+
})
|
|
46
|
+
}, async ({ conn, data }) => {
|
|
47
|
+
const userId = ws.getUserId(conn);
|
|
48
|
+
if (!userId) throw new Error('Not authenticated');
|
|
49
|
+
|
|
50
|
+
debug.log('path', `install-start requested: tool=${data.tool} user=${userId}`);
|
|
51
|
+
try {
|
|
52
|
+
const session = await startInstall(data.tool, userId);
|
|
53
|
+
return {
|
|
54
|
+
sessionId: session.id,
|
|
55
|
+
tool: data.tool,
|
|
56
|
+
displayCommand: session.recipe.displayCommand ?? '',
|
|
57
|
+
startedAt: session.startedAt
|
|
58
|
+
};
|
|
59
|
+
} catch (err) {
|
|
60
|
+
if (err instanceof InstallAlreadyRunningError) {
|
|
61
|
+
throw new Error(`Install already running for ${err.tool}`);
|
|
62
|
+
}
|
|
63
|
+
if (err instanceof InstallNotAutoInstallableError) {
|
|
64
|
+
throw new Error(err.message);
|
|
65
|
+
}
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
.http('system-tools:install-cancel', {
|
|
71
|
+
data: t.Object({ sessionId: t.String() }),
|
|
72
|
+
response: t.Object({ cancelled: t.Boolean() })
|
|
73
|
+
}, async ({ data }) => {
|
|
74
|
+
const cancelled = cancelInstall(data.sessionId);
|
|
75
|
+
return { cancelled };
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
.http('system-tools:install-session', {
|
|
79
|
+
data: t.Object({ sessionId: t.String() }),
|
|
80
|
+
response: t.Object({
|
|
81
|
+
session: t.Union([
|
|
82
|
+
t.Null(),
|
|
83
|
+
t.Object({
|
|
84
|
+
sessionId: t.String(),
|
|
85
|
+
tool: TOOL_UNION,
|
|
86
|
+
status: STATUS_UNION,
|
|
87
|
+
exitCode: t.Union([t.Number(), t.Null()]),
|
|
88
|
+
startedAt: t.Number(),
|
|
89
|
+
endedAt: t.Union([t.Number(), t.Null()]),
|
|
90
|
+
totalLines: t.Number(),
|
|
91
|
+
recentLines: t.Array(t.String()),
|
|
92
|
+
displayCommand: t.String()
|
|
93
|
+
})
|
|
94
|
+
])
|
|
95
|
+
})
|
|
96
|
+
}, async ({ data }) => {
|
|
97
|
+
return { session: getSession(data.sessionId) };
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
// ═══ Server → client events ═══
|
|
101
|
+
|
|
102
|
+
.emit('system-tools:install-started', t.Object({
|
|
103
|
+
sessionId: t.String(),
|
|
104
|
+
tool: TOOL_UNION,
|
|
105
|
+
displayCommand: t.String(),
|
|
106
|
+
startedAt: t.Number()
|
|
107
|
+
}))
|
|
108
|
+
|
|
109
|
+
.emit('system-tools:install-stream', t.Object({
|
|
110
|
+
sessionId: t.String(),
|
|
111
|
+
tool: TOOL_UNION,
|
|
112
|
+
type: t.Union([t.Literal('stdout'), t.Literal('stderr')]),
|
|
113
|
+
line: t.String()
|
|
114
|
+
}))
|
|
115
|
+
|
|
116
|
+
.emit('system-tools:install-finished', t.Object({
|
|
117
|
+
sessionId: t.String(),
|
|
118
|
+
tool: TOOL_UNION,
|
|
119
|
+
status: STATUS_UNION,
|
|
120
|
+
exitCode: t.Number(),
|
|
121
|
+
endedAt: t.Number()
|
|
122
|
+
}));
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Tool Status Handlers
|
|
3
|
+
*
|
|
4
|
+
* Reports installation status for each managed tool (git, claude,
|
|
5
|
+
* opencode, chrome). The corresponding recipe is bundled so the
|
|
6
|
+
* frontend can render the install button state and manual fallback
|
|
7
|
+
* without a second round-trip.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
12
|
+
import { debug } from '$shared/utils/logger';
|
|
13
|
+
import { getToolStatus, resolveRecipe } from '$backend/engine/install-recipes';
|
|
14
|
+
import { getActiveSessionForTool } from '$backend/engine/install-runner';
|
|
15
|
+
|
|
16
|
+
const TOOL_UNION = t.Union([
|
|
17
|
+
t.Literal('git'),
|
|
18
|
+
t.Literal('claude'),
|
|
19
|
+
t.Literal('opencode'),
|
|
20
|
+
t.Literal('chrome')
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
const RECIPE_SCHEMA = t.Object({
|
|
24
|
+
tool: TOOL_UNION,
|
|
25
|
+
autoInstallable: t.Boolean(),
|
|
26
|
+
unavailableReason: t.Optional(t.String()),
|
|
27
|
+
displayCommand: t.Optional(t.String()),
|
|
28
|
+
missingPrereqs: t.Array(TOOL_UNION),
|
|
29
|
+
manualInstructions: t.Array(t.Object({
|
|
30
|
+
label: t.String(),
|
|
31
|
+
command: t.String(),
|
|
32
|
+
docs: t.Optional(t.String())
|
|
33
|
+
}))
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const STATUS_SCHEMA = t.Object({
|
|
37
|
+
tool: TOOL_UNION,
|
|
38
|
+
installed: t.Boolean(),
|
|
39
|
+
version: t.Union([t.String(), t.Null()]),
|
|
40
|
+
source: t.Union([t.String(), t.Null()])
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const ACTIVE_SESSION_SCHEMA = t.Union([
|
|
44
|
+
t.Null(),
|
|
45
|
+
t.Object({
|
|
46
|
+
sessionId: t.String(),
|
|
47
|
+
tool: TOOL_UNION,
|
|
48
|
+
status: t.Union([
|
|
49
|
+
t.Literal('running'),
|
|
50
|
+
t.Literal('success'),
|
|
51
|
+
t.Literal('failed'),
|
|
52
|
+
t.Literal('cancelled')
|
|
53
|
+
]),
|
|
54
|
+
exitCode: t.Union([t.Number(), t.Null()]),
|
|
55
|
+
startedAt: t.Number(),
|
|
56
|
+
endedAt: t.Union([t.Number(), t.Null()]),
|
|
57
|
+
totalLines: t.Number(),
|
|
58
|
+
recentLines: t.Array(t.String()),
|
|
59
|
+
displayCommand: t.String()
|
|
60
|
+
})
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
|
|
64
|
+
return {
|
|
65
|
+
tool,
|
|
66
|
+
autoInstallable: recipe.autoInstallable,
|
|
67
|
+
unavailableReason: recipe.unavailableReason,
|
|
68
|
+
displayCommand: recipe.displayCommand,
|
|
69
|
+
missingPrereqs: recipe.missingPrereqs,
|
|
70
|
+
manualInstructions: recipe.manualInstructions
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const systemToolsStatusHandler = createRouter()
|
|
75
|
+
.http('system-tools:status', {
|
|
76
|
+
data: t.Object({ tool: TOOL_UNION }),
|
|
77
|
+
response: t.Object({
|
|
78
|
+
status: STATUS_SCHEMA,
|
|
79
|
+
recipe: RECIPE_SCHEMA,
|
|
80
|
+
activeSession: ACTIVE_SESSION_SCHEMA
|
|
81
|
+
})
|
|
82
|
+
}, async ({ data }) => {
|
|
83
|
+
debug.log('path', `system-tools:status for ${data.tool}`);
|
|
84
|
+
const [status, recipe] = await Promise.all([
|
|
85
|
+
getToolStatus(data.tool),
|
|
86
|
+
resolveRecipe(data.tool)
|
|
87
|
+
]);
|
|
88
|
+
return {
|
|
89
|
+
status,
|
|
90
|
+
recipe: toRecipeDTO(data.tool, recipe),
|
|
91
|
+
activeSession: getActiveSessionForTool(data.tool)
|
|
92
|
+
};
|
|
93
|
+
})
|
|
94
|
+
.http('system-tools:status-all', {
|
|
95
|
+
data: t.Object({}),
|
|
96
|
+
response: t.Object({
|
|
97
|
+
tools: t.Array(t.Object({
|
|
98
|
+
status: STATUS_SCHEMA,
|
|
99
|
+
recipe: RECIPE_SCHEMA,
|
|
100
|
+
activeSession: ACTIVE_SESSION_SCHEMA
|
|
101
|
+
}))
|
|
102
|
+
})
|
|
103
|
+
}, async () => {
|
|
104
|
+
debug.log('path', 'system-tools:status-all');
|
|
105
|
+
const ids = ['git', 'claude', 'opencode', 'chrome'] as const;
|
|
106
|
+
const tools = await Promise.all(ids.map(async (id) => {
|
|
107
|
+
const [status, recipe] = await Promise.all([
|
|
108
|
+
getToolStatus(id),
|
|
109
|
+
resolveRecipe(id)
|
|
110
|
+
]);
|
|
111
|
+
return {
|
|
112
|
+
status,
|
|
113
|
+
recipe: toRecipeDTO(id, recipe),
|
|
114
|
+
activeSession: getActiveSessionForTool(id)
|
|
115
|
+
};
|
|
116
|
+
}));
|
|
117
|
+
return { tools };
|
|
118
|
+
});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-
|
|
2
|
-
import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-8urnNoR7.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-8urnNoR7.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-8urnNoR7.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-8urnNoR7.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-8urnNoR7.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-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};
|