@myrialabs/clopen 0.3.8 → 0.3.9
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/backend/auth/permissions.ts +41 -2
- package/backend/chat/stream-manager.ts +71 -0
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +29 -1
- package/backend/database/queries/db-client-connection-queries.ts +160 -54
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/project-queries.ts +10 -5
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +573 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +5 -115
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +380 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/chat/stream.ts +36 -12
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +31 -17
- package/backend/ws/db-client/io.ts +7 -9
- package/backend/ws/db-client/query.ts +83 -31
- package/backend/ws/db-client/schema.ts +9 -4
- package/backend/ws/db-client/structure.ts +22 -10
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/read.ts +3 -1
- package/backend/ws/files/state.ts +3 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +5 -40
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +4 -10
- package/backend/ws/projects/status.ts +2 -0
- package/backend/ws/sessions/crud.ts +22 -33
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +12 -6
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-DqAGCTFT.js → index-D8V2wj9B.js} +2 -2
- package/dist/assets/{main-DsED0rLr.js → main-C9nYVmnw.js} +206 -198
- package/dist/assets/main-hspyFOoK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +1 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-eWY9R8g9.css +0 -1
|
@@ -14,15 +14,18 @@ import { debug } from '$shared/utils/logger';
|
|
|
14
14
|
import {
|
|
15
15
|
startInstall,
|
|
16
16
|
cancelInstall,
|
|
17
|
-
getSession,
|
|
18
17
|
InstallAlreadyRunningError,
|
|
19
18
|
InstallNotAutoInstallableError
|
|
20
19
|
} from '$backend/engine/install-runner';
|
|
20
|
+
import { requireInstallSessionAccess } from './access';
|
|
21
21
|
|
|
22
22
|
const TOOL_UNION = t.Union([
|
|
23
23
|
t.Literal('git'),
|
|
24
24
|
t.Literal('claude'),
|
|
25
25
|
t.Literal('opencode'),
|
|
26
|
+
t.Literal('copilot'),
|
|
27
|
+
t.Literal('codex'),
|
|
28
|
+
t.Literal('qwen'),
|
|
26
29
|
t.Literal('chrome'),
|
|
27
30
|
t.Literal('cloudflared')
|
|
28
31
|
]);
|
|
@@ -71,7 +74,10 @@ export const systemToolsInstallHandler = createRouter()
|
|
|
71
74
|
.http('system-tools:install-cancel', {
|
|
72
75
|
data: t.Object({ sessionId: t.String() }),
|
|
73
76
|
response: t.Object({ cancelled: t.Boolean() })
|
|
74
|
-
}, async ({ data }) => {
|
|
77
|
+
}, async ({ data, conn }) => {
|
|
78
|
+
const userId = ws.getUserId(conn);
|
|
79
|
+
if (!userId) throw new Error('Not authenticated');
|
|
80
|
+
requireInstallSessionAccess(conn, data.sessionId);
|
|
75
81
|
const cancelled = cancelInstall(data.sessionId);
|
|
76
82
|
return { cancelled };
|
|
77
83
|
})
|
|
@@ -94,8 +100,11 @@ export const systemToolsInstallHandler = createRouter()
|
|
|
94
100
|
})
|
|
95
101
|
])
|
|
96
102
|
})
|
|
97
|
-
}, async ({ data }) => {
|
|
98
|
-
|
|
103
|
+
}, async ({ data, conn }) => {
|
|
104
|
+
const userId = ws.getUserId(conn);
|
|
105
|
+
if (!userId) throw new Error('Not authenticated');
|
|
106
|
+
const session = requireInstallSessionAccess(conn, data.sessionId);
|
|
107
|
+
return { session };
|
|
99
108
|
})
|
|
100
109
|
|
|
101
110
|
// ═══ Server → client events ═══
|
|
@@ -17,6 +17,9 @@ const TOOL_UNION = t.Union([
|
|
|
17
17
|
t.Literal('git'),
|
|
18
18
|
t.Literal('claude'),
|
|
19
19
|
t.Literal('opencode'),
|
|
20
|
+
t.Literal('copilot'),
|
|
21
|
+
t.Literal('codex'),
|
|
22
|
+
t.Literal('qwen'),
|
|
20
23
|
t.Literal('chrome'),
|
|
21
24
|
t.Literal('cloudflared')
|
|
22
25
|
]);
|
|
@@ -67,7 +70,7 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
|
|
|
67
70
|
})
|
|
68
71
|
]);
|
|
69
72
|
|
|
70
|
-
function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
|
|
73
|
+
function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
|
|
71
74
|
return {
|
|
72
75
|
tool,
|
|
73
76
|
autoInstallable: recipe.autoInstallable,
|
|
@@ -110,7 +113,7 @@ export const systemToolsStatusHandler = createRouter()
|
|
|
110
113
|
})
|
|
111
114
|
}, async () => {
|
|
112
115
|
debug.log('path', 'system-tools:status-all');
|
|
113
|
-
const ids = ['git', 'claude', 'opencode', 'chrome', 'cloudflared'] as const;
|
|
116
|
+
const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome', 'cloudflared'] as const;
|
|
114
117
|
const tools = await Promise.all(ids.map(async (id) => {
|
|
115
118
|
const [status, recipe] = await Promise.all([
|
|
116
119
|
getToolStatus(id),
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal access guards.
|
|
3
|
+
*
|
|
4
|
+
* Resolves terminal-owned resources (PTY sessions, headless streams) to their
|
|
5
|
+
* owning project, then defers to the global `requireProjectAccess` helper.
|
|
6
|
+
* Centralising the lookup keeps every handler from re-implementing the
|
|
7
|
+
* "manager.getSession → null check → project guard" boilerplate.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
11
|
+
import { requireProjectAccess } from '../access';
|
|
12
|
+
import { ptySessionManager, type PtySession } from '../../terminal/pty-session-manager';
|
|
13
|
+
import { terminalStreamManager } from '../../terminal/stream-manager';
|
|
14
|
+
|
|
15
|
+
type TerminalStream = NonNullable<ReturnType<typeof terminalStreamManager.getStream>>;
|
|
16
|
+
|
|
17
|
+
export function requirePtySessionAccess(conn: WSConnection, sessionId: string): PtySession {
|
|
18
|
+
const session = ptySessionManager.getSession(sessionId);
|
|
19
|
+
if (!session || !session.projectId) {
|
|
20
|
+
throw new Error('Session not found');
|
|
21
|
+
}
|
|
22
|
+
requireProjectAccess(conn, session.projectId);
|
|
23
|
+
return session;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function requireTerminalStreamAccess(conn: WSConnection, streamId: string): TerminalStream {
|
|
27
|
+
const stream = terminalStreamManager.getStream(streamId);
|
|
28
|
+
if (!stream || !stream.projectId) {
|
|
29
|
+
throw new Error('Stream not found');
|
|
30
|
+
}
|
|
31
|
+
requireProjectAccess(conn, stream.projectId);
|
|
32
|
+
return stream;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Resolve a (sessionId, optional streamId) pair to its owning project.
|
|
37
|
+
* Used by `terminal:missed-output` which accepts either or both ids.
|
|
38
|
+
* Throws if neither resolves to an accessible project.
|
|
39
|
+
*/
|
|
40
|
+
export function requireTerminalLookupAccess(
|
|
41
|
+
conn: WSConnection,
|
|
42
|
+
sessionId: string,
|
|
43
|
+
streamId?: string
|
|
44
|
+
): { projectId: string; stream: TerminalStream | null; session: PtySession | null } {
|
|
45
|
+
const session = ptySessionManager.getSession(sessionId) ?? null;
|
|
46
|
+
const stream = streamId
|
|
47
|
+
? terminalStreamManager.getStream(streamId) ?? null
|
|
48
|
+
: terminalStreamManager.getStreamBySession(sessionId) ?? null;
|
|
49
|
+
|
|
50
|
+
const projectId = session?.projectId || stream?.projectId;
|
|
51
|
+
if (!projectId) {
|
|
52
|
+
throw new Error('Session not found');
|
|
53
|
+
}
|
|
54
|
+
requireProjectAccess(conn, projectId);
|
|
55
|
+
return { projectId, stream, session };
|
|
56
|
+
}
|
|
@@ -13,6 +13,7 @@ import { terminalStreamManager } from '../../terminal/stream-manager';
|
|
|
13
13
|
import { debug } from '$shared/utils/logger';
|
|
14
14
|
import { ws } from '$backend/utils/ws';
|
|
15
15
|
import { ptySessionManager } from '../../terminal/pty-session-manager';
|
|
16
|
+
import { requireTerminalStreamAccess, requireTerminalLookupAccess } from './access';
|
|
16
17
|
|
|
17
18
|
export const persistenceHandler = createRouter()
|
|
18
19
|
// Get stream status
|
|
@@ -21,9 +22,11 @@ export const persistenceHandler = createRouter()
|
|
|
21
22
|
streamId: t.String()
|
|
22
23
|
}),
|
|
23
24
|
response: t.Any()
|
|
24
|
-
}, async ({ data }) => {
|
|
25
|
+
}, async ({ data, conn }) => {
|
|
25
26
|
const { streamId } = data;
|
|
26
27
|
|
|
28
|
+
requireTerminalStreamAccess(conn, streamId);
|
|
29
|
+
|
|
27
30
|
const status = terminalStreamManager.getStreamStatus(streamId);
|
|
28
31
|
|
|
29
32
|
if (!status) {
|
|
@@ -46,9 +49,11 @@ export const persistenceHandler = createRouter()
|
|
|
46
49
|
status: t.String(),
|
|
47
50
|
timestamp: t.String()
|
|
48
51
|
})
|
|
49
|
-
}, async ({ data }) => {
|
|
52
|
+
}, async ({ data, conn }) => {
|
|
50
53
|
const { sessionId, streamId } = data;
|
|
51
54
|
|
|
55
|
+
requireTerminalLookupAccess(conn, sessionId, streamId);
|
|
56
|
+
|
|
52
57
|
// Get serialized terminal state from headless xterm
|
|
53
58
|
let output = '';
|
|
54
59
|
|
|
@@ -77,17 +82,18 @@ export const persistenceHandler = createRouter()
|
|
|
77
82
|
})
|
|
78
83
|
}, async ({ data, conn }) => {
|
|
79
84
|
const { streamId, sessionId } = data;
|
|
80
|
-
const projectId = ws.getProjectId(conn);
|
|
81
85
|
|
|
82
86
|
const stream = terminalStreamManager.getStream(streamId);
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
ws.emit.project(
|
|
87
|
+
if (!stream || !stream.projectId) {
|
|
88
|
+
const fallbackProjectId = ws.getProjectId(conn);
|
|
89
|
+
ws.emit.project(fallbackProjectId, 'terminal:error', {
|
|
86
90
|
sessionId,
|
|
87
91
|
error: 'Stream not found'
|
|
88
92
|
});
|
|
89
93
|
return;
|
|
90
94
|
}
|
|
95
|
+
requireTerminalStreamAccess(conn, streamId);
|
|
96
|
+
const projectId = stream.projectId;
|
|
91
97
|
|
|
92
98
|
try {
|
|
93
99
|
// Send serialized terminal state (frontend writes it to xterm to restore)
|
|
@@ -20,6 +20,8 @@ import { isWindows } from '../../terminal/shell-utils';
|
|
|
20
20
|
import { existsSync } from '../../terminal/helpers';
|
|
21
21
|
import { ws } from '$backend/utils/ws';
|
|
22
22
|
import { activePtyProcesses } from '../../terminal/pty-manager';
|
|
23
|
+
import { requireProjectAccess, requireCurrentProjectAccess } from '../access';
|
|
24
|
+
import { requirePtySessionAccess } from './access';
|
|
23
25
|
|
|
24
26
|
export const sessionHandler = createRouter()
|
|
25
27
|
// Create new terminal session
|
|
@@ -50,7 +52,14 @@ export const sessionHandler = createRouter()
|
|
|
50
52
|
rows = 24
|
|
51
53
|
} = data;
|
|
52
54
|
|
|
53
|
-
const projectId =
|
|
55
|
+
const { projectId } = requireCurrentProjectAccess(conn);
|
|
56
|
+
|
|
57
|
+
// If a PTY session already exists for this id, it must belong to the
|
|
58
|
+
// caller's current project. Prevents hijacking another project's PTY id.
|
|
59
|
+
const existingForOwnership = ptySessionManager.getSession(sessionId);
|
|
60
|
+
if (existingForOwnership && existingForOwnership.projectId && existingForOwnership.projectId !== projectId) {
|
|
61
|
+
throw new Error('Session not found');
|
|
62
|
+
}
|
|
54
63
|
|
|
55
64
|
debug.log('terminal', `🌐 WebSocket: Creating PTY session: ${sessionId}`);
|
|
56
65
|
|
|
@@ -219,8 +228,9 @@ export const sessionHandler = createRouter()
|
|
|
219
228
|
response: t.Object({
|
|
220
229
|
sessionId: t.String()
|
|
221
230
|
})
|
|
222
|
-
}, async ({ data }) => {
|
|
231
|
+
}, async ({ data, conn }) => {
|
|
223
232
|
const { sessionId } = data;
|
|
233
|
+
requirePtySessionAccess(conn, sessionId);
|
|
224
234
|
terminalStreamManager.clearHeadlessTerminal(sessionId);
|
|
225
235
|
return { sessionId };
|
|
226
236
|
})
|
|
@@ -237,9 +247,11 @@ export const sessionHandler = createRouter()
|
|
|
237
247
|
cols: t.Number(),
|
|
238
248
|
rows: t.Number()
|
|
239
249
|
})
|
|
240
|
-
}, async ({ data }) => {
|
|
250
|
+
}, async ({ data, conn }) => {
|
|
241
251
|
const { sessionId, cols, rows } = data;
|
|
242
252
|
|
|
253
|
+
requirePtySessionAccess(conn, sessionId);
|
|
254
|
+
|
|
243
255
|
debug.log('terminal', `🔧 Resizing PTY session ${sessionId} to ${cols}x${rows}`);
|
|
244
256
|
|
|
245
257
|
const success = ptySessionManager.resize(sessionId, cols, rows);
|
|
@@ -263,16 +275,12 @@ export const sessionHandler = createRouter()
|
|
|
263
275
|
sessionId: t.String(),
|
|
264
276
|
pid: t.Number()
|
|
265
277
|
})
|
|
266
|
-
}, async ({ data }) => {
|
|
278
|
+
}, async ({ data, conn }) => {
|
|
267
279
|
const { sessionId } = data;
|
|
268
280
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const session = ptySessionManager.getSession(sessionId);
|
|
281
|
+
const session = requirePtySessionAccess(conn, sessionId);
|
|
272
282
|
|
|
273
|
-
|
|
274
|
-
throw new Error('No active PTY process found for this session');
|
|
275
|
-
}
|
|
283
|
+
debug.log('terminal', `🛑 Sending Ctrl+C signal to PTY session: ${sessionId}`);
|
|
276
284
|
|
|
277
285
|
const pid = session.pty.pid;
|
|
278
286
|
|
|
@@ -299,14 +307,16 @@ export const sessionHandler = createRouter()
|
|
|
299
307
|
}, async ({ data, conn }) => {
|
|
300
308
|
const { sessionId } = data;
|
|
301
309
|
|
|
302
|
-
debug.log('terminal', `💀 [kill-session] Killing PTY session: ${sessionId}`);
|
|
303
|
-
|
|
304
310
|
const session = ptySessionManager.getSession(sessionId);
|
|
305
311
|
|
|
306
312
|
if (!session) {
|
|
307
313
|
debug.log('terminal', `💀 [kill-session] No active PTY session found for: ${sessionId}`);
|
|
308
314
|
return { sessionId };
|
|
309
315
|
}
|
|
316
|
+
if (!session.projectId) throw new Error('Session not found');
|
|
317
|
+
requireProjectAccess(conn, session.projectId);
|
|
318
|
+
|
|
319
|
+
debug.log('terminal', `💀 [kill-session] Killing PTY session: ${sessionId}`);
|
|
310
320
|
|
|
311
321
|
const pid = session.pty?.pid;
|
|
312
322
|
debug.log('terminal', `💀 [kill-session] Found PTY session with PID: ${pid}`);
|
|
@@ -393,9 +403,19 @@ export const sessionHandler = createRouter()
|
|
|
393
403
|
pid: t.Optional(t.Number()),
|
|
394
404
|
message: t.Optional(t.String())
|
|
395
405
|
})
|
|
396
|
-
}, async ({ data }) => {
|
|
406
|
+
}, async ({ data, conn }) => {
|
|
397
407
|
const { sessionId } = data;
|
|
398
408
|
|
|
409
|
+
const ptySession = ptySessionManager.getSession(sessionId);
|
|
410
|
+
if (!ptySession || !ptySession.projectId) {
|
|
411
|
+
return {
|
|
412
|
+
isActive: false,
|
|
413
|
+
sessionId,
|
|
414
|
+
message: 'PTY not found'
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
requireProjectAccess(conn, ptySession.projectId);
|
|
418
|
+
|
|
399
419
|
const pty = activePtyProcesses.get(sessionId);
|
|
400
420
|
|
|
401
421
|
if (pty) {
|
|
@@ -430,8 +450,9 @@ export const sessionHandler = createRouter()
|
|
|
430
450
|
lastActivityAt: t.String()
|
|
431
451
|
}))
|
|
432
452
|
})
|
|
433
|
-
}, async ({ data }) => {
|
|
453
|
+
}, async ({ data, conn }) => {
|
|
434
454
|
const { projectId } = data;
|
|
455
|
+
requireProjectAccess(conn, projectId);
|
|
435
456
|
|
|
436
457
|
const allSessions = ptySessionManager.getAllSessions();
|
|
437
458
|
const projectSessions = allSessions
|
|
@@ -14,6 +14,7 @@ import { createRouter } from '$shared/utils/ws-server';
|
|
|
14
14
|
import { ptySessionManager } from '../../terminal/pty-session-manager';
|
|
15
15
|
import { debug } from '$shared/utils/logger';
|
|
16
16
|
import { ws } from '$backend/utils/ws';
|
|
17
|
+
import { requirePtySessionAccess } from './access';
|
|
17
18
|
|
|
18
19
|
export const streamHandler = createRouter()
|
|
19
20
|
// Send keyboard input to terminal
|
|
@@ -24,7 +25,9 @@ export const streamHandler = createRouter()
|
|
|
24
25
|
})
|
|
25
26
|
}, async ({ data, conn }) => {
|
|
26
27
|
const { sessionId, data: input } = data;
|
|
27
|
-
|
|
28
|
+
|
|
29
|
+
const ptySession = requirePtySessionAccess(conn, sessionId);
|
|
30
|
+
const projectId = ptySession.projectId!;
|
|
28
31
|
|
|
29
32
|
try {
|
|
30
33
|
// Write to PTY stdin
|
|
@@ -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-DsED0rLr.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-DsED0rLr.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-DsED0rLr.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-DsED0rLr.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-DsED0rLr.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-C9nYVmnw.js","assets/main-hspyFOoK.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-C9nYVmnw.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-C9nYVmnw.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-C9nYVmnw.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-C9nYVmnw.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-C9nYVmnw.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};
|