@myrialabs/clopen 0.3.6 → 0.3.8

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.
Files changed (54) hide show
  1. package/README.md +4 -4
  2. package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
  3. package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
  4. package/backend/database/migrations/index.ts +14 -0
  5. package/backend/database/queries/db-client-connection-queries.ts +237 -0
  6. package/backend/database/queries/db-client-query-history-queries.ts +113 -0
  7. package/backend/database/queries/index.ts +3 -1
  8. package/backend/database/queries/project-queries.ts +23 -0
  9. package/backend/db-client/connection-manager.ts +257 -0
  10. package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
  11. package/backend/db-client/drivers/mongodb.ts +358 -0
  12. package/backend/db-client/drivers/mysql.ts +385 -0
  13. package/backend/db-client/drivers/postgres.ts +446 -0
  14. package/backend/db-client/drivers/redis.ts +267 -0
  15. package/backend/db-client/drivers/sql-builders.ts +215 -0
  16. package/backend/db-client/drivers/sqlite.ts +346 -0
  17. package/backend/db-client/drivers/types.ts +92 -0
  18. package/backend/db-client/query-executor.ts +126 -0
  19. package/backend/db-client/ssh-tunnel.ts +122 -0
  20. package/backend/engine/install-recipes.ts +216 -137
  21. package/backend/engine/install-runner.ts +39 -0
  22. package/backend/git/git-service.ts +12 -0
  23. package/backend/mcp/servers/browser-automation/index.ts +6 -6
  24. package/backend/preview/browser/browser-pool.ts +10 -9
  25. package/backend/preview/browser/scripts/video-stream.ts +9 -3
  26. package/backend/tunnel/cloudflared/binary.ts +22 -4
  27. package/backend/tunnel/cloudflared/index.ts +2 -1
  28. package/backend/tunnel/cloudflared/tunnel.ts +17 -4
  29. package/backend/tunnel/global-tunnel-manager.ts +29 -51
  30. package/backend/tunnel/project-tunnel-manager.ts +14 -53
  31. package/backend/ws/db-client/connections.ts +180 -0
  32. package/backend/ws/db-client/index.ts +17 -0
  33. package/backend/ws/db-client/io.ts +458 -0
  34. package/backend/ws/db-client/query.ts +162 -0
  35. package/backend/ws/db-client/schema.ts +76 -0
  36. package/backend/ws/db-client/structure.ts +218 -0
  37. package/backend/ws/files/index.ts +5 -1
  38. package/backend/ws/files/read.ts +32 -0
  39. package/backend/ws/files/state.ts +39 -0
  40. package/backend/ws/index.ts +6 -2
  41. package/backend/ws/system-tools/install.ts +2 -1
  42. package/backend/ws/system-tools/status.ts +5 -4
  43. package/dist/assets/{index-BU8wB4Fg.js → index-DqAGCTFT.js} +2 -2
  44. package/dist/assets/{main-cQx6vfxB.js → main-DsED0rLr.js} +244 -192
  45. package/dist/assets/main-eWY9R8g9.css +1 -0
  46. package/dist/index.html +2 -2
  47. package/package.json +4 -2
  48. package/shared/constants/preview.ts +48 -4
  49. package/shared/types/database/schema.ts +48 -1
  50. package/shared/types/db-client/connection.ts +60 -0
  51. package/shared/types/db-client/index.ts +6 -0
  52. package/shared/types/db-client/query.ts +77 -0
  53. package/shared/utils/logger.ts +1 -0
  54. package/dist/assets/main-B3tMwjjU.css +0 -1
@@ -0,0 +1,218 @@
1
+ /**
2
+ * db-client — structure (DDL) WS handlers.
3
+ */
4
+
5
+ import { t } from 'elysia';
6
+ import { createRouter } from '$shared/utils/ws-server';
7
+ import { connectionManager } from '../../db-client/connection-manager';
8
+ import type { AlterOperation, IndexDefinition, TableDefinition } from '../../db-client/drivers/types';
9
+
10
+ const columnDefinitionSchema = t.Object({
11
+ name: t.String({ minLength: 1 }),
12
+ type: t.String({ minLength: 1 }),
13
+ nullable: t.Optional(t.Boolean()),
14
+ default: t.Optional(t.Nullable(t.String())),
15
+ primary: t.Optional(t.Boolean()),
16
+ unique: t.Optional(t.Boolean()),
17
+ autoIncrement: t.Optional(t.Boolean())
18
+ });
19
+
20
+ const tableDefinitionSchema = t.Object({
21
+ name: t.String({ minLength: 1 }),
22
+ columns: t.Array(columnDefinitionSchema),
23
+ primaryKey: t.Optional(t.Array(t.String()))
24
+ });
25
+
26
+ const alterOpSchema = t.Union([
27
+ t.Object({ kind: t.Literal('add-column'), column: columnDefinitionSchema }),
28
+ t.Object({ kind: t.Literal('drop-column'), name: t.String() }),
29
+ t.Object({ kind: t.Literal('rename-column'), name: t.String(), newName: t.String() }),
30
+ t.Object({ kind: t.Literal('modify-column'), column: columnDefinitionSchema })
31
+ ]);
32
+
33
+ const indexDefinitionSchema = t.Object({
34
+ name: t.String({ minLength: 1 }),
35
+ columns: t.Array(t.String()),
36
+ unique: t.Optional(t.Boolean())
37
+ });
38
+
39
+ export const structureHandler = createRouter()
40
+ .http('db-client:structure:create-database', {
41
+ data: t.Object({
42
+ connectionId: t.String({ minLength: 1 }),
43
+ name: t.String({ minLength: 1 })
44
+ }),
45
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
46
+ }, async ({ data }) => {
47
+ const adapter = await connectionManager.get(data.connectionId);
48
+ if (!adapter.createDatabase) throw new Error('Driver does not support database creation');
49
+ const ddl = await adapter.createDatabase(data.name);
50
+ return { ok: true, ddl };
51
+ })
52
+
53
+ .http('db-client:structure:create-table', {
54
+ data: t.Object({
55
+ connectionId: t.String({ minLength: 1 }),
56
+ database: t.Optional(t.String()),
57
+ schema: t.Optional(t.String()),
58
+ definition: tableDefinitionSchema
59
+ }),
60
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
61
+ }, async ({ data }) => {
62
+ const adapter = await connectionManager.get(data.connectionId);
63
+ if (!adapter.createTable) throw new Error('Driver does not support createTable');
64
+ const ddl = await adapter.createTable(data.definition as TableDefinition, {
65
+ database: data.database,
66
+ schema: data.schema
67
+ });
68
+ return { ok: true, ddl };
69
+ })
70
+
71
+ .http('db-client:structure:alter-table', {
72
+ data: t.Object({
73
+ connectionId: t.String({ minLength: 1 }),
74
+ database: t.Optional(t.String()),
75
+ schema: t.Optional(t.String()),
76
+ name: t.String({ minLength: 1 }),
77
+ operations: t.Array(alterOpSchema)
78
+ }),
79
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
80
+ }, async ({ data }) => {
81
+ const adapter = await connectionManager.get(data.connectionId);
82
+ if (!adapter.alterTable) throw new Error('Driver does not support alterTable');
83
+ const ddl = await adapter.alterTable(data.name, data.operations as AlterOperation[], {
84
+ database: data.database,
85
+ schema: data.schema
86
+ });
87
+ return { ok: true, ddl };
88
+ })
89
+
90
+ .http('db-client:structure:drop-table', {
91
+ data: t.Object({
92
+ connectionId: t.String({ minLength: 1 }),
93
+ database: t.Optional(t.String()),
94
+ schema: t.Optional(t.String()),
95
+ name: t.String({ minLength: 1 })
96
+ }),
97
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
98
+ }, async ({ data }) => {
99
+ const adapter = await connectionManager.get(data.connectionId);
100
+ if (!adapter.dropTable) throw new Error('Driver does not support dropTable');
101
+ const ddl = await adapter.dropTable(data.name, {
102
+ database: data.database,
103
+ schema: data.schema
104
+ });
105
+ return { ok: true, ddl };
106
+ })
107
+
108
+ .http('db-client:structure:truncate-table', {
109
+ data: t.Object({
110
+ connectionId: t.String({ minLength: 1 }),
111
+ database: t.Optional(t.String()),
112
+ schema: t.Optional(t.String()),
113
+ name: t.String({ minLength: 1 })
114
+ }),
115
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
116
+ }, async ({ data }) => {
117
+ const adapter = await connectionManager.get(data.connectionId);
118
+ if (!adapter.truncateTable) throw new Error('Driver does not support truncateTable');
119
+ const ddl = await adapter.truncateTable(data.name, {
120
+ database: data.database,
121
+ schema: data.schema
122
+ });
123
+ return { ok: true, ddl };
124
+ })
125
+
126
+ .http('db-client:structure:rename-table', {
127
+ data: t.Object({
128
+ connectionId: t.String({ minLength: 1 }),
129
+ database: t.Optional(t.String()),
130
+ schema: t.Optional(t.String()),
131
+ name: t.String({ minLength: 1 }),
132
+ newName: t.String({ minLength: 1 })
133
+ }),
134
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
135
+ }, async ({ data }) => {
136
+ const adapter = await connectionManager.get(data.connectionId);
137
+ if (!adapter.renameTable) throw new Error('Driver does not support renameTable');
138
+ const ddl = await adapter.renameTable(data.name, data.newName, {
139
+ database: data.database,
140
+ schema: data.schema
141
+ });
142
+ return { ok: true, ddl };
143
+ })
144
+
145
+ .http('db-client:structure:create-index', {
146
+ data: t.Object({
147
+ connectionId: t.String({ minLength: 1 }),
148
+ database: t.Optional(t.String()),
149
+ schema: t.Optional(t.String()),
150
+ tableName: t.String({ minLength: 1 }),
151
+ indexDef: indexDefinitionSchema
152
+ }),
153
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
154
+ }, async ({ data }) => {
155
+ const adapter = await connectionManager.get(data.connectionId);
156
+ if (!adapter.createIndex) throw new Error('Driver does not support createIndex');
157
+ const ddl = await adapter.createIndex(data.tableName, data.indexDef as IndexDefinition, {
158
+ database: data.database,
159
+ schema: data.schema
160
+ });
161
+ return { ok: true, ddl };
162
+ })
163
+
164
+ .http('db-client:structure:drop-index', {
165
+ data: t.Object({
166
+ connectionId: t.String({ minLength: 1 }),
167
+ database: t.Optional(t.String()),
168
+ schema: t.Optional(t.String()),
169
+ tableName: t.String({ minLength: 1 }),
170
+ indexName: t.String({ minLength: 1 })
171
+ }),
172
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
173
+ }, async ({ data }) => {
174
+ const adapter = await connectionManager.get(data.connectionId);
175
+ if (!adapter.dropIndex) throw new Error('Driver does not support dropIndex');
176
+ const ddl = await adapter.dropIndex(data.tableName, data.indexName, {
177
+ database: data.database,
178
+ schema: data.schema
179
+ });
180
+ return { ok: true, ddl };
181
+ })
182
+
183
+ .http('db-client:structure:create-view', {
184
+ data: t.Object({
185
+ connectionId: t.String({ minLength: 1 }),
186
+ database: t.Optional(t.String()),
187
+ schema: t.Optional(t.String()),
188
+ name: t.String({ minLength: 1 }),
189
+ query: t.String({ minLength: 1 })
190
+ }),
191
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
192
+ }, async ({ data }) => {
193
+ const adapter = await connectionManager.get(data.connectionId);
194
+ if (!adapter.createView) throw new Error('Driver does not support createView');
195
+ const ddl = await adapter.createView(data.name, data.query, {
196
+ database: data.database,
197
+ schema: data.schema
198
+ });
199
+ return { ok: true, ddl };
200
+ })
201
+
202
+ .http('db-client:structure:drop-view', {
203
+ data: t.Object({
204
+ connectionId: t.String({ minLength: 1 }),
205
+ database: t.Optional(t.String()),
206
+ schema: t.Optional(t.String()),
207
+ name: t.String({ minLength: 1 })
208
+ }),
209
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
210
+ }, async ({ data }) => {
211
+ const adapter = await connectionManager.get(data.connectionId);
212
+ if (!adapter.dropView) throw new Error('Driver does not support dropView');
213
+ const ddl = await adapter.dropView(data.name, {
214
+ database: data.database,
215
+ schema: data.schema
216
+ });
217
+ return { ok: true, ddl };
218
+ });
@@ -15,6 +15,7 @@ import { readHandler } from './read';
15
15
  import { writeHandler } from './write';
16
16
  import { fileSearchHandler } from './search';
17
17
  import { watchHandler } from './watch';
18
+ import { filesStateHandler } from './state';
18
19
 
19
20
  export const filesRouter = createRouter()
20
21
  // Read Operations (HTTP)
@@ -27,4 +28,7 @@ export const filesRouter = createRouter()
27
28
  .merge(fileSearchHandler)
28
29
 
29
30
  // Watch Operations (Events)
30
- .merge(watchHandler);
31
+ .merge(watchHandler)
32
+
33
+ // Panel state (HTTP)
34
+ .merge(filesStateHandler);
@@ -18,6 +18,9 @@ import {
18
18
  readFileContents
19
19
  } from '../../files/file-reading';
20
20
  import { handlePathBrowsing } from '../../files/path-browsing';
21
+ import { gitService } from '../../git/git-service';
22
+ import { projectQueries } from '../../database/queries/project-queries';
23
+ import { isAbsolute, relative } from 'node:path';
21
24
 
22
25
  // Bun-compatible existsSync implementation
23
26
  async function existsSync(path: string): Promise<boolean> {
@@ -154,6 +157,35 @@ export const readHandler = createRouter()
154
157
  return result;
155
158
  })
156
159
 
160
+ // Read file content at a git ref (e.g. HEAD) for diff comparison
161
+ .http('files:read-file-at', {
162
+ data: t.Object({
163
+ projectId: t.String(),
164
+ filePath: t.String(),
165
+ ref: t.Optional(t.String())
166
+ }),
167
+ response: t.Object({
168
+ content: t.Union([t.String(), t.Null()]),
169
+ ref: t.String()
170
+ })
171
+ }, async ({ data }) => {
172
+ const project = projectQueries.getById(data.projectId);
173
+ if (!project) throw new Error('Project not found');
174
+
175
+ const ref = data.ref || 'HEAD';
176
+
177
+ // Make filePath relative to project root for `git show`
178
+ let relativePath = data.filePath;
179
+ if (isAbsolute(data.filePath)) {
180
+ relativePath = relative(project.path, data.filePath);
181
+ }
182
+ // Normalize path separators for git
183
+ relativePath = relativePath.replace(/\\/g, '/');
184
+
185
+ const content = await gitService.getFileAtRef(project.path, ref, relativePath);
186
+ return { content, ref };
187
+ })
188
+
157
189
  // Read file content (binary - for images, etc.) as base64
158
190
  .http('files:read-content', {
159
191
  data: t.Object({
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Files Panel State Handlers
3
+ *
4
+ * Persist per-user-per-project files panel state (expanded folders,
5
+ * open tabs, scroll positions, view mode). Single source of truth in DB
6
+ * so that the state survives browser refresh and follows the user across
7
+ * devices.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { createRouter } from '$shared/utils/ws-server';
12
+ import { projectQueries } from '../../database/queries/project-queries';
13
+ import { ws as wsServer } from '../../utils/ws';
14
+
15
+ export const filesStateHandler = createRouter()
16
+ .http('files:get-panel-state', {
17
+ data: t.Object({
18
+ projectId: t.String()
19
+ }),
20
+ response: t.Object({
21
+ state: t.Union([t.String(), t.Null()])
22
+ })
23
+ }, async ({ data, conn }) => {
24
+ const userId = wsServer.getUserId(conn);
25
+ const state = projectQueries.getFilesPanelState(userId, data.projectId);
26
+ return { state };
27
+ })
28
+
29
+ .http('files:set-panel-state', {
30
+ data: t.Object({
31
+ projectId: t.String(),
32
+ state: t.Union([t.String(), t.Null()])
33
+ }),
34
+ response: t.Object({ ok: t.Boolean() })
35
+ }, async ({ data, conn }) => {
36
+ const userId = wsServer.getUserId(conn);
37
+ projectQueries.setFilesPanelState(userId, data.projectId, data.state);
38
+ return { ok: true };
39
+ });
@@ -29,6 +29,7 @@ import { tunnelRouter } from './tunnel';
29
29
  import { gitRouter } from './git';
30
30
  import { engineRouter } from './engine';
31
31
  import { systemToolsRouter } from './system-tools';
32
+ import { dbClientRouter } from './db-client';
32
33
 
33
34
  // ============================================
34
35
  // Main App Router - Merge All Module Routers
@@ -66,8 +67,11 @@ export const wsRouter = createRouter()
66
67
  // AI Engine Management
67
68
  .merge(engineRouter)
68
69
 
69
- // System Tools (install Git, Claude Code, OpenCode, Chromium binaries)
70
- .merge(systemToolsRouter);
70
+ // System Tools (install Git, Claude Code, OpenCode, Chrome binaries)
71
+ .merge(systemToolsRouter)
72
+
73
+ // DB Client (global database management)
74
+ .merge(dbClientRouter);
71
75
 
72
76
  // Export API type for frontend type-safe access
73
77
  export type WSAPI = typeof wsRouter['$api'];
@@ -23,7 +23,8 @@ const TOOL_UNION = t.Union([
23
23
  t.Literal('git'),
24
24
  t.Literal('claude'),
25
25
  t.Literal('opencode'),
26
- t.Literal('chromium')
26
+ t.Literal('chrome'),
27
+ t.Literal('cloudflared')
27
28
  ]);
28
29
 
29
30
  const STATUS_UNION = t.Union([
@@ -2,7 +2,7 @@
2
2
  * System Tool Status Handlers
3
3
  *
4
4
  * Reports installation status for each managed tool (git, claude,
5
- * opencode, chromium). The corresponding recipe is bundled so the
5
+ * opencode, chrome). The corresponding recipe is bundled so the
6
6
  * frontend can render the install button state and manual fallback
7
7
  * without a second round-trip.
8
8
  */
@@ -17,7 +17,8 @@ const TOOL_UNION = t.Union([
17
17
  t.Literal('git'),
18
18
  t.Literal('claude'),
19
19
  t.Literal('opencode'),
20
- t.Literal('chromium')
20
+ t.Literal('chrome'),
21
+ t.Literal('cloudflared')
21
22
  ]);
22
23
 
23
24
  const RECIPE_SCHEMA = t.Object({
@@ -66,7 +67,7 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
66
67
  })
67
68
  ]);
68
69
 
69
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chromium', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
70
+ function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
70
71
  return {
71
72
  tool,
72
73
  autoInstallable: recipe.autoInstallable,
@@ -109,7 +110,7 @@ export const systemToolsStatusHandler = createRouter()
109
110
  })
110
111
  }, async () => {
111
112
  debug.log('path', 'system-tools:status-all');
112
- const ids = ['git', 'claude', 'opencode', 'chromium'] as const;
113
+ const ids = ['git', 'claude', 'opencode', 'chrome', 'cloudflared'] as const;
113
114
  const tools = await Promise.all(ids.map(async (id) => {
114
115
  const [status, recipe] = await Promise.all([
115
116
  getToolStatus(id),
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-cQx6vfxB.js","assets/main-B3tMwjjU.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-cQx6vfxB.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-cQx6vfxB.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-cQx6vfxB.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-cQx6vfxB.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-cQx6vfxB.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-DsED0rLr.js","assets/main-eWY9R8g9.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-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};