@myrialabs/clopen 0.2.22 → 0.2.24
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/database/migrations/027_create_opencode_providers_table.ts +27 -0
- package/backend/database/migrations/028_create_opencode_accounts_table.ts +25 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/database/queries/opencode-provider-queries.ts +190 -0
- package/backend/engine/adapters/opencode/config.ts +156 -0
- package/backend/engine/adapters/opencode/server.ts +57 -15
- package/backend/engine/adapters/opencode/stream.ts +4 -2
- package/backend/git/git-executor.ts +4 -1
- package/backend/terminal/shell-utils.ts +7 -13
- package/backend/utils/cli.ts +27 -0
- package/backend/utils/index.ts +7 -1
- package/backend/utils/os.ts +7 -0
- package/backend/ws/engine/claude/accounts.ts +2 -2
- package/backend/ws/engine/claude/status.ts +3 -2
- package/backend/ws/engine/opencode/index.ts +3 -1
- package/backend/ws/engine/opencode/providers.ts +299 -0
- package/backend/ws/engine/opencode/status.ts +3 -2
- package/dist/assets/{index-BFFIy7ZX.js → index-w7Uwi2Jz.js} +2 -2
- package/dist/assets/{main-CtNvgvwE.js → main-B4q8wX9B.js} +197 -189
- package/dist/assets/main-Bfz5Urp3.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/backend/ws/engine/utils.ts +0 -68
- package/dist/assets/main-DmshCkFM.css +0 -1
|
@@ -21,7 +21,6 @@ import { engineQueries } from '../../../database/queries';
|
|
|
21
21
|
import { resetEnvironment, getClaudeUserConfigDir } from '../../../engine/adapters/claude/environment';
|
|
22
22
|
import { debug } from '$shared/utils/logger';
|
|
23
23
|
import { getCleanSpawnEnv } from '../../../utils/env';
|
|
24
|
-
import { resolveCommand } from '../utils';
|
|
25
24
|
|
|
26
25
|
// ── Helpers ──
|
|
27
26
|
|
|
@@ -189,7 +188,8 @@ export const accountsHandler = createRouter()
|
|
|
189
188
|
ptyEnv['CLAUDE_CONFIG_DIR'] = getClaudeUserConfigDir();
|
|
190
189
|
ptyEnv['BROWSER'] = 'false';
|
|
191
190
|
|
|
192
|
-
const claudeCmd =
|
|
191
|
+
const claudeCmd = Bun.which('claude');
|
|
192
|
+
if (!claudeCmd) throw new Error('claude binary not found on PATH');
|
|
193
193
|
let pty: ReturnType<typeof spawn>;
|
|
194
194
|
try {
|
|
195
195
|
pty = spawn(claudeCmd, ['setup-token'], {
|
|
@@ -8,7 +8,8 @@ import { t } from 'elysia';
|
|
|
8
8
|
import { createRouter } from '$shared/utils/ws-server';
|
|
9
9
|
import { engineQueries } from '../../../database/queries';
|
|
10
10
|
import { debug } from '$shared/utils/logger';
|
|
11
|
-
import { getBackendOS
|
|
11
|
+
import { getBackendOS } from '../../../utils/os';
|
|
12
|
+
import { getStatus } from '../../../utils/cli';
|
|
12
13
|
|
|
13
14
|
export const claudeCodeStatusHandler = createRouter()
|
|
14
15
|
.http('engine:claude-status', {
|
|
@@ -29,7 +30,7 @@ export const claudeCodeStatusHandler = createRouter()
|
|
|
29
30
|
}, async () => {
|
|
30
31
|
debug.log('engine', 'Checking Claude Code status...');
|
|
31
32
|
|
|
32
|
-
const { installed, version } = await
|
|
33
|
+
const { installed, version } = await getStatus('claude');
|
|
33
34
|
const accounts = engineQueries.getClaudeAccounts();
|
|
34
35
|
const activeAccount = engineQueries.getActiveClaudeAccount();
|
|
35
36
|
|
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
import { createRouter } from '$shared/utils/ws-server';
|
|
8
8
|
import { openCodeStatusHandler } from './status';
|
|
9
|
+
import { openCodeProviderHandler } from './providers';
|
|
9
10
|
|
|
10
11
|
export const openCodeEngineRouter = createRouter()
|
|
11
|
-
.merge(openCodeStatusHandler)
|
|
12
|
+
.merge(openCodeStatusHandler)
|
|
13
|
+
.merge(openCodeProviderHandler);
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode Provider Management Handlers
|
|
3
|
+
*
|
|
4
|
+
* CRUD for providers and accounts, models.dev catalog, and server restart.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { t } from 'elysia';
|
|
8
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
9
|
+
import { opencodeProviderQueries } from '../../../database/queries';
|
|
10
|
+
import {
|
|
11
|
+
fetchAndCacheModelsDevCatalog,
|
|
12
|
+
getCachedModelsDevCatalog,
|
|
13
|
+
} from '../../../engine/adapters/opencode/config';
|
|
14
|
+
import { disposeOpenCodeClient } from '../../../engine/adapters/opencode/server';
|
|
15
|
+
import { disposeEngine } from '../../../engine';
|
|
16
|
+
import { streamManager } from '../../../chat';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
|
|
19
|
+
// Shared typebox schemas
|
|
20
|
+
const AccountSchema = t.Object({
|
|
21
|
+
id: t.Number(),
|
|
22
|
+
name: t.String(),
|
|
23
|
+
isActive: t.Boolean(),
|
|
24
|
+
createdAt: t.String(),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const ProviderSchema = t.Object({
|
|
28
|
+
id: t.Number(),
|
|
29
|
+
providerId: t.String(),
|
|
30
|
+
name: t.String(),
|
|
31
|
+
npm: t.String(),
|
|
32
|
+
apiUrl: t.Union([t.String(), t.Null()]),
|
|
33
|
+
options: t.String(),
|
|
34
|
+
isEnabled: t.Boolean(),
|
|
35
|
+
createdAt: t.String(),
|
|
36
|
+
accounts: t.Array(AccountSchema),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
export const openCodeProviderHandler = createRouter()
|
|
40
|
+
|
|
41
|
+
// ═══════════════════════════════════════
|
|
42
|
+
// Provider CRUD
|
|
43
|
+
// ═══════════════════════════════════════
|
|
44
|
+
|
|
45
|
+
.http('engine:opencode-providers-list', {
|
|
46
|
+
data: t.Object({}),
|
|
47
|
+
response: t.Object({
|
|
48
|
+
providers: t.Array(ProviderSchema)
|
|
49
|
+
})
|
|
50
|
+
}, async () => {
|
|
51
|
+
const providers = opencodeProviderQueries.getProvidersWithAccounts();
|
|
52
|
+
return {
|
|
53
|
+
providers: providers.map(p => ({
|
|
54
|
+
id: p.id,
|
|
55
|
+
providerId: p.provider_id,
|
|
56
|
+
name: p.name,
|
|
57
|
+
npm: p.npm,
|
|
58
|
+
apiUrl: p.api_url,
|
|
59
|
+
options: p.options,
|
|
60
|
+
isEnabled: p.is_enabled === 1,
|
|
61
|
+
createdAt: p.created_at,
|
|
62
|
+
accounts: p.accounts.map(a => ({
|
|
63
|
+
id: a.id,
|
|
64
|
+
name: a.name,
|
|
65
|
+
isActive: a.is_active === 1,
|
|
66
|
+
createdAt: a.created_at,
|
|
67
|
+
})),
|
|
68
|
+
}))
|
|
69
|
+
};
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
.http('engine:opencode-provider-add', {
|
|
73
|
+
data: t.Object({
|
|
74
|
+
providerId: t.String({ minLength: 1 }),
|
|
75
|
+
name: t.String({ minLength: 1 }),
|
|
76
|
+
npm: t.String({ minLength: 1 }),
|
|
77
|
+
apiUrl: t.Optional(t.String()),
|
|
78
|
+
options: t.Optional(t.String()),
|
|
79
|
+
accountName: t.String({ minLength: 1 }),
|
|
80
|
+
apiKey: t.String({ minLength: 1 }),
|
|
81
|
+
}),
|
|
82
|
+
response: t.Object({
|
|
83
|
+
provider: ProviderSchema
|
|
84
|
+
})
|
|
85
|
+
}, async ({ data }) => {
|
|
86
|
+
// Check if provider already exists
|
|
87
|
+
const existing = opencodeProviderQueries.getProviderByProviderId(data.providerId);
|
|
88
|
+
if (existing) {
|
|
89
|
+
throw new Error(`Provider "${data.providerId}" already configured`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Create provider
|
|
93
|
+
const provider = opencodeProviderQueries.createProvider({
|
|
94
|
+
providerId: data.providerId,
|
|
95
|
+
name: data.name,
|
|
96
|
+
npm: data.npm,
|
|
97
|
+
apiUrl: data.apiUrl,
|
|
98
|
+
options: data.options,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// Create first account (auto-active)
|
|
102
|
+
const account = opencodeProviderQueries.createAccount(provider.id, data.accountName, data.apiKey);
|
|
103
|
+
|
|
104
|
+
debug.log('engine', `OpenCode provider added: ${data.providerId} with account "${data.accountName}"`);
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
provider: {
|
|
108
|
+
id: provider.id,
|
|
109
|
+
providerId: provider.provider_id,
|
|
110
|
+
name: provider.name,
|
|
111
|
+
npm: provider.npm,
|
|
112
|
+
apiUrl: provider.api_url,
|
|
113
|
+
options: provider.options,
|
|
114
|
+
isEnabled: provider.is_enabled === 1,
|
|
115
|
+
createdAt: provider.created_at,
|
|
116
|
+
accounts: [{
|
|
117
|
+
id: account.id,
|
|
118
|
+
name: account.name,
|
|
119
|
+
isActive: account.is_active === 1,
|
|
120
|
+
createdAt: account.created_at,
|
|
121
|
+
}],
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
.http('engine:opencode-provider-remove', {
|
|
127
|
+
data: t.Object({ id: t.Number() }),
|
|
128
|
+
response: t.Object({ success: t.Boolean() })
|
|
129
|
+
}, async ({ data }) => {
|
|
130
|
+
opencodeProviderQueries.deleteProvider(data.id);
|
|
131
|
+
debug.log('engine', `OpenCode provider removed: ${data.id}`);
|
|
132
|
+
return { success: true };
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
.http('engine:opencode-provider-toggle', {
|
|
136
|
+
data: t.Object({ id: t.Number(), enabled: t.Boolean() }),
|
|
137
|
+
response: t.Object({ success: t.Boolean() })
|
|
138
|
+
}, async ({ data }) => {
|
|
139
|
+
opencodeProviderQueries.toggleProvider(data.id, data.enabled);
|
|
140
|
+
return { success: true };
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
.http('engine:opencode-provider-update-options', {
|
|
144
|
+
data: t.Object({ id: t.Number(), options: t.String() }),
|
|
145
|
+
response: t.Object({ success: t.Boolean() })
|
|
146
|
+
}, async ({ data }) => {
|
|
147
|
+
// Validate JSON
|
|
148
|
+
try { JSON.parse(data.options); } catch { throw new Error('Invalid JSON for options'); }
|
|
149
|
+
opencodeProviderQueries.updateProviderOptions(data.id, data.options);
|
|
150
|
+
return { success: true };
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
// ═══════════════════════════════════════
|
|
154
|
+
// Account CRUD
|
|
155
|
+
// ═══════════════════════════════════════
|
|
156
|
+
|
|
157
|
+
.http('engine:opencode-account-add', {
|
|
158
|
+
data: t.Object({
|
|
159
|
+
providerDbId: t.Number(),
|
|
160
|
+
name: t.String({ minLength: 1 }),
|
|
161
|
+
apiKey: t.String({ minLength: 1 }),
|
|
162
|
+
}),
|
|
163
|
+
response: t.Object({
|
|
164
|
+
account: AccountSchema
|
|
165
|
+
})
|
|
166
|
+
}, async ({ data }) => {
|
|
167
|
+
const account = opencodeProviderQueries.createAccount(data.providerDbId, data.name, data.apiKey);
|
|
168
|
+
debug.log('engine', `OpenCode account added: "${data.name}" for provider ${data.providerDbId}`);
|
|
169
|
+
return {
|
|
170
|
+
account: {
|
|
171
|
+
id: account.id,
|
|
172
|
+
name: account.name,
|
|
173
|
+
isActive: account.is_active === 1,
|
|
174
|
+
createdAt: account.created_at,
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
.http('engine:opencode-account-switch', {
|
|
180
|
+
data: t.Object({ accountId: t.Number() }),
|
|
181
|
+
response: t.Object({ success: t.Boolean() })
|
|
182
|
+
}, async ({ data }) => {
|
|
183
|
+
opencodeProviderQueries.switchAccount(data.accountId);
|
|
184
|
+
return { success: true };
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
.http('engine:opencode-account-delete', {
|
|
188
|
+
data: t.Object({ accountId: t.Number() }),
|
|
189
|
+
response: t.Object({ success: t.Boolean() })
|
|
190
|
+
}, async ({ data }) => {
|
|
191
|
+
opencodeProviderQueries.deleteAccount(data.accountId);
|
|
192
|
+
return { success: true };
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
.http('engine:opencode-account-rename', {
|
|
196
|
+
data: t.Object({ accountId: t.Number(), name: t.String({ minLength: 1 }) }),
|
|
197
|
+
response: t.Object({ success: t.Boolean() })
|
|
198
|
+
}, async ({ data }) => {
|
|
199
|
+
opencodeProviderQueries.renameAccount(data.accountId, data.name);
|
|
200
|
+
return { success: true };
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
// ═══════════════════════════════════════
|
|
204
|
+
// Models.dev Catalog
|
|
205
|
+
// ═══════════════════════════════════════
|
|
206
|
+
|
|
207
|
+
.http('engine:opencode-models-dev-list', {
|
|
208
|
+
data: t.Object({}),
|
|
209
|
+
response: t.Object({
|
|
210
|
+
catalog: t.Array(t.Object({
|
|
211
|
+
id: t.String(),
|
|
212
|
+
name: t.String(),
|
|
213
|
+
npm: t.String(),
|
|
214
|
+
env: t.Array(t.String()),
|
|
215
|
+
api: t.Union([t.String(), t.Null()]),
|
|
216
|
+
})),
|
|
217
|
+
cachedAt: t.Union([t.String(), t.Null()]),
|
|
218
|
+
})
|
|
219
|
+
}, async () => {
|
|
220
|
+
const cached = getCachedModelsDevCatalog();
|
|
221
|
+
if (cached) {
|
|
222
|
+
return { catalog: cached.catalog, cachedAt: cached.cachedAt };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// First time: fetch and cache
|
|
226
|
+
try {
|
|
227
|
+
const catalog = await fetchAndCacheModelsDevCatalog();
|
|
228
|
+
return { catalog, cachedAt: new Date().toISOString() };
|
|
229
|
+
} catch (error) {
|
|
230
|
+
debug.error('engine', 'Failed to fetch models.dev catalog:', error);
|
|
231
|
+
return { catalog: [], cachedAt: null };
|
|
232
|
+
}
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
.http('engine:opencode-models-dev-fetch', {
|
|
236
|
+
data: t.Object({}),
|
|
237
|
+
response: t.Object({
|
|
238
|
+
catalog: t.Array(t.Object({
|
|
239
|
+
id: t.String(),
|
|
240
|
+
name: t.String(),
|
|
241
|
+
npm: t.String(),
|
|
242
|
+
env: t.Array(t.String()),
|
|
243
|
+
api: t.Union([t.String(), t.Null()]),
|
|
244
|
+
})),
|
|
245
|
+
cachedAt: t.String(),
|
|
246
|
+
})
|
|
247
|
+
}, async () => {
|
|
248
|
+
const catalog = await fetchAndCacheModelsDevCatalog();
|
|
249
|
+
return { catalog, cachedAt: new Date().toISOString() };
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
// ═══════════════════════════════════════
|
|
253
|
+
// Server Restart
|
|
254
|
+
// ═══════════════════════════════════════
|
|
255
|
+
|
|
256
|
+
.http('engine:opencode-server-restart', {
|
|
257
|
+
data: t.Object({
|
|
258
|
+
force: t.Optional(t.Boolean()),
|
|
259
|
+
}),
|
|
260
|
+
response: t.Object({
|
|
261
|
+
success: t.Boolean(),
|
|
262
|
+
activeChats: t.Optional(t.Number()),
|
|
263
|
+
needsConfirmation: t.Optional(t.Boolean()),
|
|
264
|
+
})
|
|
265
|
+
}, async ({ data }) => {
|
|
266
|
+
// Check for active opencode streams
|
|
267
|
+
const activeStreams = streamManager.getActiveStreams()
|
|
268
|
+
.filter(s => s.engine === 'opencode');
|
|
269
|
+
|
|
270
|
+
if (activeStreams.length > 0 && !data.force) {
|
|
271
|
+
return {
|
|
272
|
+
success: false,
|
|
273
|
+
activeChats: activeStreams.length,
|
|
274
|
+
needsConfirmation: true,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Force: abort all active opencode streams first
|
|
279
|
+
if (activeStreams.length > 0) {
|
|
280
|
+
debug.log('engine', `Force-aborting ${activeStreams.length} active OpenCode streams before restart`);
|
|
281
|
+
for (const stream of activeStreams) {
|
|
282
|
+
try {
|
|
283
|
+
await streamManager.cancelStream(stream.streamId);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
debug.warn('engine', `Failed to abort stream ${stream.streamId}:`, error);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Dispose global opencode engine + shared client/server.
|
|
291
|
+
// forRestart=true ensures the server is killed even if we didn't
|
|
292
|
+
// spawn it, and the stored URL is purged so next init() spawns fresh.
|
|
293
|
+
await disposeEngine('opencode');
|
|
294
|
+
await disposeOpenCodeClient(true);
|
|
295
|
+
|
|
296
|
+
debug.log('engine', 'OpenCode server disposed. Will re-initialize on next use.');
|
|
297
|
+
|
|
298
|
+
return { success: true };
|
|
299
|
+
});
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
import { t } from 'elysia';
|
|
8
8
|
import { createRouter } from '$shared/utils/ws-server';
|
|
9
9
|
import { debug } from '$shared/utils/logger';
|
|
10
|
-
import { getBackendOS
|
|
10
|
+
import { getBackendOS } from '../../../utils/os';
|
|
11
|
+
import { getStatus } from '../../../utils/cli';
|
|
11
12
|
|
|
12
13
|
export const openCodeStatusHandler = createRouter()
|
|
13
14
|
.http('engine:opencode-status', {
|
|
@@ -20,7 +21,7 @@ export const openCodeStatusHandler = createRouter()
|
|
|
20
21
|
}, async () => {
|
|
21
22
|
debug.log('engine', 'Checking Open Code status...');
|
|
22
23
|
|
|
23
|
-
const { installed, version } = await
|
|
24
|
+
const { installed, version } = await getStatus('opencode');
|
|
24
25
|
|
|
25
26
|
return {
|
|
26
27
|
installed,
|
|
@@ -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-CtNvgvwE.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-CtNvgvwE.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-CtNvgvwE.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-CtNvgvwE.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-CtNvgvwE.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-B4q8wX9B.js","assets/main-Bfz5Urp3.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-B4q8wX9B.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-B4q8wX9B.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-B4q8wX9B.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-B4q8wX9B.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-B4q8wX9B.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};
|