@myrialabs/clopen 0.2.24 → 0.3.0

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 (60) hide show
  1. package/README.md +1 -1
  2. package/backend/chat/helpers.ts +2 -20
  3. package/backend/chat/stream-manager.ts +556 -547
  4. package/backend/database/migrations/029_migrate_messages_to_unified.ts +1108 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/engine-queries.ts +195 -36
  7. package/backend/database/queries/index.ts +1 -2
  8. package/backend/database/queries/message-queries.ts +84 -139
  9. package/backend/database/queries/session-queries.ts +167 -21
  10. package/backend/database/queries/snapshot-queries.ts +5 -4
  11. package/backend/database/queries/utils-queries.ts +2 -2
  12. package/backend/engine/adapters/claude/environment.ts +4 -5
  13. package/backend/engine/adapters/claude/message-converter.ts +501 -0
  14. package/backend/engine/adapters/claude/stream.ts +52 -47
  15. package/backend/engine/adapters/opencode/config.ts +7 -7
  16. package/backend/engine/adapters/opencode/message-converter.ts +266 -326
  17. package/backend/engine/adapters/opencode/stream.ts +84 -101
  18. package/backend/engine/types.ts +17 -11
  19. package/backend/project/status-manager.ts +10 -13
  20. package/backend/snapshot/helpers.ts +46 -90
  21. package/backend/snapshot/snapshot-service.ts +1 -1
  22. package/backend/utils/paths.ts +22 -1
  23. package/backend/ws/chat/index.ts +1 -11
  24. package/backend/ws/chat/stream.ts +101 -61
  25. package/backend/ws/engine/claude/accounts.ts +27 -7
  26. package/backend/ws/engine/claude/status.ts +3 -2
  27. package/backend/ws/engine/opencode/providers.ts +25 -24
  28. package/backend/ws/git/commit-message.ts +6 -8
  29. package/backend/ws/messages/crud.ts +4 -59
  30. package/backend/ws/sessions/crud.ts +78 -130
  31. package/backend/ws/sessions/index.ts +1 -9
  32. package/backend/ws/settings/crud.ts +14 -11
  33. package/backend/ws/snapshot/restore.ts +23 -26
  34. package/backend/ws/snapshot/timeline.ts +5 -5
  35. package/dist/assets/{index-w7Uwi2Jz.js → index-B95VOHJY.js} +2 -2
  36. package/dist/assets/main-D1QNkcRL.js +257 -0
  37. package/dist/assets/main-rtLiuU_x.css +1 -0
  38. package/dist/index.html +2 -2
  39. package/package.json +4 -4
  40. package/shared/constants/engines.ts +141 -56
  41. package/shared/types/database/schema.ts +39 -40
  42. package/shared/types/stores/settings.ts +8 -4
  43. package/shared/types/unified/common.ts +21 -0
  44. package/shared/types/unified/display.ts +25 -0
  45. package/shared/types/unified/engine.ts +61 -0
  46. package/shared/types/unified/index.ts +108 -0
  47. package/shared/types/unified/message.ts +151 -0
  48. package/shared/types/unified/stream.ts +157 -0
  49. package/shared/types/unified/tool.ts +268 -0
  50. package/shared/utils/message-formatter.ts +9 -73
  51. package/shared/utils/path.ts +3 -2
  52. package/tsconfig.json +1 -1
  53. package/backend/database/queries/opencode-provider-queries.ts +0 -190
  54. package/backend/engine/adapters/claude/path-utils.ts +0 -38
  55. package/backend/ws/chat/background.ts +0 -201
  56. package/dist/assets/main-B4q8wX9B.js +0 -257
  57. package/dist/assets/main-Bfz5Urp3.css +0 -1
  58. package/shared/types/engine/index.ts +0 -45
  59. package/shared/types/messaging/index.ts +0 -242
  60. package/shared/types/messaging/tool.ts +0 -374
@@ -12,7 +12,8 @@
12
12
 
13
13
  import { t } from 'elysia';
14
14
  import { createRouter } from '$shared/utils/ws-server';
15
- import type { EngineType } from '$shared/types/engine';
15
+ import type { EngineType } from '$shared/types/unified';
16
+ import type { ChatSession } from '$shared/types/database/schema';
16
17
  import { sessionQueries, messageQueries, projectQueries, snapshotQueries } from '../../database/queries';
17
18
  import { ws } from '$backend/utils/ws';
18
19
  import { streamManager } from '../../chat/stream-manager';
@@ -21,22 +22,62 @@ import { blobStore } from '../../snapshot/blob-store';
21
22
  import { broadcastPresence } from '../projects/status';
22
23
  import { debug } from '$shared/utils/logger';
23
24
 
25
+ /** Elysia schema for ChatSession responses — all optional fields use t.Optional */
26
+ const sessionSchema = t.Object({
27
+ // Identity
28
+ id: t.String(),
29
+ project_id: t.String(),
30
+ started_at: t.String(),
31
+ ended_at: t.Optional(t.String()),
32
+ // Session preferences
33
+ title: t.Optional(t.String()),
34
+ engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
35
+ model_id: t.Optional(t.String()),
36
+ model_name: t.Optional(t.String()),
37
+ account_id: t.Optional(t.Number()),
38
+ account_name: t.Optional(t.String()),
39
+ // HEAD state
40
+ head_message_id: t.Optional(t.String()),
41
+ head_session_id: t.Optional(t.String()),
42
+ head_title: t.Optional(t.String()),
43
+ head_summary: t.Optional(t.String()),
44
+ // Activity tracking
45
+ sender_id: t.Optional(t.String()),
46
+ sender_name: t.Optional(t.String()),
47
+ message_count: t.Optional(t.Number()),
48
+ user_count: t.Optional(t.Number()),
49
+ last_message_at: t.Optional(t.String()),
50
+ });
51
+
52
+ /** Convert ChatSession DB row → response (null → undefined for Elysia optional fields) */
53
+ function serializeSession(session: ChatSession) {
54
+ return {
55
+ ...session,
56
+ title: session.title ?? undefined,
57
+ engine: session.engine ?? 'claude-code' as const,
58
+ model_id: session.model_id ?? undefined,
59
+ model_name: session.model_name ?? undefined,
60
+ account_id: session.account_id ?? undefined,
61
+ account_name: session.account_name ?? undefined,
62
+ head_message_id: session.head_message_id ?? undefined,
63
+ head_session_id: session.head_session_id ?? undefined,
64
+ ended_at: session.ended_at ?? undefined,
65
+ sender_id: session.sender_id ?? undefined,
66
+ sender_name: session.sender_name ?? undefined,
67
+ head_title: session.head_title ?? undefined,
68
+ head_summary: session.head_summary ?? undefined,
69
+ message_count: session.message_count ?? undefined,
70
+ user_count: session.user_count ?? undefined,
71
+ last_message_at: session.last_message_at ?? undefined,
72
+ };
73
+ }
74
+
24
75
  export const crudHandler = createRouter()
25
76
  // List sessions (includes server-saved current session ID for refresh restore)
26
77
  .http('sessions:list', {
27
78
  data: t.Object({}),
28
79
  response: t.Object({
29
- sessions: t.Array(t.Object({
30
- id: t.String(),
31
- project_id: t.String(),
32
- title: t.Optional(t.String()),
33
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
34
- model: t.Optional(t.String()),
35
- latest_sdk_session_id: t.Optional(t.String()),
36
- current_head_message_id: t.Optional(t.String()),
37
- started_at: t.String(),
38
- ended_at: t.Optional(t.String())
39
- })),
80
+ sessions: t.Array(sessionSchema),
40
81
  currentSessionId: t.Optional(t.String()),
41
82
  unreadSessionIds: t.Array(t.Object({
42
83
  sessionId: t.String(),
@@ -55,17 +96,8 @@ export const crudHandler = createRouter()
55
96
  const unreadRows = sessionQueries.getUnreadSessions(userId, projectId);
56
97
  debug.log('session', `[unread] sessions:list — user=${userId}, project=${projectId}, unreadCount=${unreadRows.length}`, unreadRows);
57
98
 
58
- // Convert null to undefined for TypeScript optional fields
59
99
  return {
60
- sessions: sessions.map(session => ({
61
- ...session,
62
- title: session.title ?? undefined,
63
- engine: session.engine ?? 'claude-code',
64
- model: session.model ?? undefined,
65
- latest_sdk_session_id: session.latest_sdk_session_id ?? undefined,
66
- current_head_message_id: session.current_head_message_id ?? undefined,
67
- ended_at: session.ended_at ?? undefined
68
- })),
100
+ sessions: sessions.map(serializeSession),
69
101
  currentSessionId: currentSessionId ?? undefined,
70
102
  unreadSessionIds: unreadRows.map(r => ({ sessionId: r.session_id, projectId: r.project_id }))
71
103
  };
@@ -74,30 +106,11 @@ export const crudHandler = createRouter()
74
106
  // List active (non-ended) sessions for current project
75
107
  .http('sessions:list-active', {
76
108
  data: t.Object({}),
77
- response: t.Array(t.Object({
78
- id: t.String(),
79
- project_id: t.String(),
80
- title: t.Optional(t.String()),
81
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
82
- model: t.Optional(t.String()),
83
- latest_sdk_session_id: t.Optional(t.String()),
84
- current_head_message_id: t.Optional(t.String()),
85
- started_at: t.String(),
86
- ended_at: t.Optional(t.String())
87
- }))
109
+ response: t.Array(sessionSchema)
88
110
  }, async ({ conn }) => {
89
111
  const projectId = ws.getProjectId(conn);
90
112
  const sessions = sessionQueries.getActiveSessionsForProject(projectId);
91
-
92
- return sessions.map(session => ({
93
- ...session,
94
- title: session.title ?? undefined,
95
- engine: session.engine ?? 'claude-code',
96
- model: session.model ?? undefined,
97
- latest_sdk_session_id: session.latest_sdk_session_id ?? undefined,
98
- current_head_message_id: session.current_head_message_id ?? undefined,
99
- ended_at: session.ended_at ?? undefined
100
- }));
113
+ return sessions.map(serializeSession);
101
114
  })
102
115
 
103
116
  // Create new session
@@ -106,17 +119,7 @@ export const crudHandler = createRouter()
106
119
  title: t.Optional(t.String()),
107
120
  engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')]))
108
121
  }),
109
- response: t.Object({
110
- id: t.String(),
111
- project_id: t.String(),
112
- title: t.Optional(t.String()),
113
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
114
- model: t.Optional(t.String()),
115
- latest_sdk_session_id: t.Optional(t.String()),
116
- current_head_message_id: t.Optional(t.String()),
117
- started_at: t.String(),
118
- ended_at: t.Optional(t.String())
119
- })
122
+ response: sessionSchema
120
123
  }, async ({ data, conn }) => {
121
124
  const projectId = ws.getProjectId(conn);
122
125
  const now = new Date().toISOString();
@@ -128,16 +131,7 @@ export const crudHandler = createRouter()
128
131
  started_at: now
129
132
  });
130
133
 
131
- // Convert null to undefined for TypeScript optional fields
132
- return {
133
- ...session,
134
- title: session.title ?? undefined,
135
- engine: session.engine ?? 'claude-code',
136
- model: session.model ?? undefined,
137
- latest_sdk_session_id: session.latest_sdk_session_id ?? undefined,
138
- current_head_message_id: session.current_head_message_id ?? undefined,
139
- ended_at: session.ended_at ?? undefined
140
- };
134
+ return serializeSession(session);
141
135
  })
142
136
 
143
137
  // Get session by ID (with messages)
@@ -146,17 +140,7 @@ export const crudHandler = createRouter()
146
140
  id: t.String({ minLength: 1 })
147
141
  }),
148
142
  response: t.Object({
149
- session: t.Object({
150
- id: t.String(),
151
- project_id: t.String(),
152
- title: t.Optional(t.String()),
153
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
154
- model: t.Optional(t.String()),
155
- latest_sdk_session_id: t.Optional(t.String()),
156
- current_head_message_id: t.Optional(t.String()),
157
- started_at: t.String(),
158
- ended_at: t.Optional(t.String())
159
- }),
143
+ session: sessionSchema,
160
144
  messages: t.Array(t.Any())
161
145
  })
162
146
  }, async ({ data }) => {
@@ -169,17 +153,8 @@ export const crudHandler = createRouter()
169
153
  // Also get messages for this session
170
154
  const messages = messageQueries.getBySessionId(data.id);
171
155
 
172
- // Convert null to undefined for TypeScript optional fields
173
156
  return {
174
- session: {
175
- ...session,
176
- title: session.title ?? undefined,
177
- engine: session.engine ?? undefined,
178
- model: session.model ?? undefined,
179
- latest_sdk_session_id: session.latest_sdk_session_id ?? undefined,
180
- current_head_message_id: session.current_head_message_id ?? undefined,
181
- ended_at: session.ended_at ?? undefined
182
- },
157
+ session: serializeSession(session),
183
158
  messages
184
159
  };
185
160
  })
@@ -189,17 +164,7 @@ export const crudHandler = createRouter()
189
164
  data: t.Object({
190
165
  forceNew: t.Optional(t.Boolean())
191
166
  }),
192
- response: t.Object({
193
- id: t.String(),
194
- project_id: t.String(),
195
- title: t.Optional(t.String()),
196
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
197
- model: t.Optional(t.String()),
198
- latest_sdk_session_id: t.Optional(t.String()),
199
- current_head_message_id: t.Optional(t.String()),
200
- started_at: t.String(),
201
- ended_at: t.Optional(t.String())
202
- })
167
+ response: sessionSchema
203
168
  }, async ({ data, conn }) => {
204
169
  const projectId = ws.getProjectId(conn);
205
170
 
@@ -219,15 +184,7 @@ export const crudHandler = createRouter()
219
184
  data.forceNew || false
220
185
  );
221
186
 
222
- const sessionResponse = {
223
- ...session,
224
- title: session.title ?? undefined,
225
- engine: session.engine ?? 'claude-code',
226
- model: session.model ?? undefined,
227
- latest_sdk_session_id: session.latest_sdk_session_id ?? undefined,
228
- current_head_message_id: session.current_head_message_id ?? undefined,
229
- ended_at: session.ended_at ?? undefined
230
- };
187
+ const sessionResponse = serializeSession(session);
231
188
 
232
189
  // Broadcast when a NEW session was actually created.
233
190
  // Covers both forceNew=true and the case where no active session existed.
@@ -251,50 +208,27 @@ export const crudHandler = createRouter()
251
208
  reactivate: t.Optional(t.Boolean()),
252
209
  end_session: t.Optional(t.Boolean())
253
210
  }),
254
- response: t.Object({
255
- id: t.String(),
256
- project_id: t.String(),
257
- title: t.Optional(t.String()),
258
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode')])),
259
- model: t.Optional(t.String()),
260
- latest_sdk_session_id: t.Optional(t.String()),
261
- current_head_message_id: t.Optional(t.String()),
262
- started_at: t.String(),
263
- ended_at: t.Optional(t.String())
264
- })
211
+ response: sessionSchema
265
212
  }, async ({ data }) => {
266
213
  const session = sessionQueries.getById(data.id);
267
214
  if (!session) {
268
215
  throw new Error('Session not found');
269
216
  }
270
217
 
271
- // Update session title if provided
272
218
  if (data.title) {
273
219
  sessionQueries.updateTitle(data.id, data.title);
274
220
  }
275
221
 
276
- // Reactivate session if requested (clear ended_at and end other sessions in same project)
277
222
  if (data.reactivate) {
278
223
  sessionQueries.reactivate(data.id);
279
224
  }
280
225
 
281
- // End session if requested
282
226
  if (data.end_session) {
283
227
  sessionQueries.end(data.id);
284
228
  }
285
229
 
286
230
  const updatedSession = sessionQueries.getById(data.id)!;
287
-
288
- // Convert null to undefined for TypeScript optional fields
289
- return {
290
- ...updatedSession,
291
- title: updatedSession.title ?? undefined,
292
- engine: updatedSession.engine ?? 'claude-code',
293
- model: updatedSession.model ?? undefined,
294
- latest_sdk_session_id: updatedSession.latest_sdk_session_id ?? undefined,
295
- current_head_message_id: updatedSession.current_head_message_id ?? undefined,
296
- ended_at: updatedSession.ended_at ?? undefined
297
- };
231
+ return serializeSession(updatedSession);
298
232
  })
299
233
 
300
234
  // Delete session (with full related data cleanup)
@@ -473,4 +407,18 @@ export const crudHandler = createRouter()
473
407
  const userId = ws.getUserId(conn);
474
408
  sessionQueries.markUnread(userId, data.sessionId, data.projectId);
475
409
  debug.log('session', `[unread] Marked session ${data.sessionId} as UNREAD for user ${userId} in project ${data.projectId}`);
410
+ })
411
+
412
+ // Search sessions by message content (deep search)
413
+ .http('sessions:search', {
414
+ data: t.Object({
415
+ query: t.String({ minLength: 1 })
416
+ }),
417
+ response: t.Object({
418
+ sessionIds: t.Array(t.String())
419
+ })
420
+ }, async ({ data, conn }) => {
421
+ const projectId = ws.getProjectId(conn);
422
+ const sessionIds = sessionQueries.searchByMessageContent(projectId, data.query);
423
+ return { sessionIds };
476
424
  });
@@ -16,15 +16,7 @@ export const sessionsRouter = createRouter()
16
16
  // Collaborative broadcast events (Server → Client)
17
17
  // Notification: a new session is available (no auto-switch)
18
18
  .emit('sessions:session-available', t.Object({
19
- session: t.Object({
20
- id: t.String(),
21
- project_id: t.String(),
22
- title: t.Optional(t.String()),
23
- latest_sdk_session_id: t.Optional(t.String()),
24
- current_head_message_id: t.Optional(t.String()),
25
- started_at: t.String(),
26
- ended_at: t.Optional(t.String())
27
- })
19
+ session: t.Any()
28
20
  }))
29
21
  // Notification: a session was deleted by another user
30
22
  .emit('sessions:session-deleted', t.Object({
@@ -12,7 +12,7 @@ import { createRouter } from '$shared/utils/ws-server';
12
12
  import { settingsQueries } from '../../database/queries';
13
13
  import { initializeEngine } from '../../engine';
14
14
  import { CLAUDE_CODE_MODELS, registerModels } from '$shared/constants/engines';
15
- import type { EngineType } from '$shared/types/engine';
15
+ import type { EngineType } from '$shared/types/unified';
16
16
 
17
17
  export const crudHandler = createRouter()
18
18
  // Get settings
@@ -82,16 +82,19 @@ export const crudHandler = createRouter()
82
82
  engine: t.Union([t.Literal('claude-code'), t.Literal('opencode')])
83
83
  }),
84
84
  response: t.Array(t.Object({
85
- id: t.String(),
86
- engine: t.Union([t.Literal('claude-code'), t.Literal('opencode')]),
87
- modelId: t.String(),
88
- name: t.String(),
89
- provider: t.String(),
90
- description: t.String(),
91
- capabilities: t.Array(t.String()),
92
- contextWindow: t.Number(),
93
- category: t.Union([t.Literal('latest'), t.Literal('stable'), t.Literal('legacy')]),
94
- recommended: t.Optional(t.Boolean())
85
+ engine: t.Object({
86
+ type: t.Union([t.Literal('claude-code'), t.Literal('opencode')]),
87
+ provider: t.String(),
88
+ model: t.Object({ id: t.String(), name: t.String() }),
89
+ account: t.Object({ id: t.Number(), name: t.String() }),
90
+ }),
91
+ limit: t.Object({ input: t.Number(), output: t.Number() }),
92
+ modalities: t.Object({
93
+ input: t.Object({ text: t.Boolean(), image: t.Boolean(), audio: t.Boolean(), video: t.Boolean(), pdf: t.Boolean() }),
94
+ output: t.Object({ text: t.Boolean(), image: t.Boolean(), audio: t.Boolean(), video: t.Boolean(), pdf: t.Boolean() }),
95
+ }),
96
+ capabilities: t.Object({ reasoning: t.Boolean(), tools: t.Boolean(), structuredOutput: t.Boolean() }),
97
+ cost: t.Object({ input: t.Number(), output: t.Number() }),
95
98
  }))
96
99
  }, async ({ data }) => {
97
100
  const engineType: EngineType = data.engine;
@@ -11,6 +11,7 @@ import { createRouter } from '$shared/utils/ws-server';
11
11
  import { messageQueries, sessionQueries, projectQueries, checkpointQueries } from '../../database/queries';
12
12
  import { snapshotService } from '../../snapshot/snapshot-service';
13
13
  import { debug } from '$shared/utils/logger';
14
+ import type { UnifiedMessage } from '$shared/types/unified';
14
15
  import {
15
16
  buildCheckpointTree,
16
17
  getCheckpointPathToRoot,
@@ -118,11 +119,12 @@ export const restoreHandler = createRouter()
118
119
  if (isInitialRestore) {
119
120
  // Clear HEAD (no messages active)
120
121
  sessionQueries.clearHead(sessionId);
122
+ sessionQueries.rederiveHeadSnapshot(sessionId);
121
123
  debug.log('snapshot', 'HEAD cleared (initial state)');
122
124
 
123
- // Clear latest_sdk_session_id so next chat starts fresh
125
+ // Clear head_session_id so next chat starts fresh
124
126
  const db = (await import('../../database')).getDatabase();
125
- db.prepare(`UPDATE chat_sessions SET latest_sdk_session_id = NULL WHERE id = ?`).run(sessionId);
127
+ db.prepare(`UPDATE chat_sessions SET head_session_id = NULL WHERE id = ?`).run(sessionId);
126
128
 
127
129
  // Clear checkpoint_tree_state
128
130
  checkpointQueries.deleteForSession(sessionId);
@@ -198,9 +200,10 @@ export const restoreHandler = createRouter()
198
200
 
199
201
  // 5. Update HEAD to session end
200
202
  sessionQueries.updateHead(sessionId, sessionEnd.id);
203
+ sessionQueries.rederiveHeadSnapshot(sessionId);
201
204
  debug.log('snapshot', `HEAD updated to: ${sessionEnd.id}`);
202
205
 
203
- // 5b. Update latest_sdk_session_id so resume works correctly.
206
+ // 5b. Update head_session_id so resume works correctly.
204
207
  // Claude Code: skip cancelled fork session_ids (partial messages from cancelStream).
205
208
  // OpenCode: simple walk — any session_id is valid (sessions created synchronously).
206
209
  {
@@ -209,15 +212,15 @@ export const restoreHandler = createRouter()
209
212
  const sessionRecord = sessionQueries.getById(sessionId);
210
213
  const isClaudeCode = sessionRecord?.engine === 'claude-code';
211
214
 
212
- // Claude Code only: detect cancelled stream by partialText marker on sessionEnd
215
+ // Claude Code only: detect cancelled stream by stopReason on sessionEnd
213
216
  let cancelledSessionId: string | null = null;
214
217
  if (isClaudeCode) {
215
218
  try {
216
219
  const endMsg = msgLookup.get(sessionEnd.id);
217
220
  if (endMsg) {
218
- const endSdk = JSON.parse(endMsg.sdk_message);
219
- if (endSdk.partialText) {
220
- cancelledSessionId = endSdk.session_id || null;
221
+ const endParsed = JSON.parse(endMsg.data) as UnifiedMessage;
222
+ if (endParsed.type === 'assistant' && endParsed.stopReason === 'interrupted') {
223
+ cancelledSessionId = endParsed.sessionId || null;
221
224
  }
222
225
  }
223
226
  } catch { /* skip */ }
@@ -229,29 +232,23 @@ export const restoreHandler = createRouter()
229
232
  if (!walkMsg) break;
230
233
 
231
234
  try {
232
- const sdk = JSON.parse(walkMsg.sdk_message);
235
+ const msg = JSON.parse(walkMsg.data) as UnifiedMessage;
233
236
 
234
- // Claude Code only: skip partial messages (from cancelled streams)
235
- if (isClaudeCode && sdk.partialText) {
237
+ // Claude Code only: skip interrupted messages (from cancelled streams)
238
+ if (isClaudeCode && msg.type === 'assistant' && msg.stopReason === 'interrupted') {
236
239
  walkId = walkMsg.parent_message_id || null;
237
240
  continue;
238
241
  }
239
242
 
240
- // Claude Code only: skip assistant messages from the same cancelled fork
241
- if (isClaudeCode && cancelledSessionId && sdk.session_id === cancelledSessionId) {
243
+ // Claude Code only: skip messages from the same cancelled fork
244
+ if (isClaudeCode && cancelledSessionId && msg.sessionId === cancelledSessionId) {
242
245
  walkId = walkMsg.parent_message_id || null;
243
246
  continue;
244
247
  }
245
248
 
246
- // Claude Code only: user message's `resume` field records the last valid session_id
247
- if (isClaudeCode && sdk.type === 'user' && 'resume' in sdk) {
248
- foundSdkSessionId = sdk.resume || null;
249
- break;
250
- }
251
-
252
- // Any engine: message with session_id
253
- if (sdk.session_id) {
254
- foundSdkSessionId = sdk.session_id;
249
+ // Any engine: message with sessionId
250
+ if (msg.sessionId) {
251
+ foundSdkSessionId = msg.sessionId;
255
252
  break;
256
253
  }
257
254
  } catch { /* skip */ }
@@ -260,11 +257,11 @@ export const restoreHandler = createRouter()
260
257
  }
261
258
 
262
259
  if (foundSdkSessionId) {
263
- sessionQueries.updateLatestSdkSessionId(sessionId, foundSdkSessionId);
264
- debug.log('snapshot', `latest_sdk_session_id updated to: ${foundSdkSessionId}`);
260
+ sessionQueries.updateSessionId(sessionId, foundSdkSessionId);
261
+ debug.log('snapshot', `head_session_id updated to: ${foundSdkSessionId}`);
265
262
  } else {
266
- sessionQueries.clearLatestSdkSessionId(sessionId);
267
- debug.log('snapshot', 'latest_sdk_session_id cleared (no valid session found in restored chain)');
263
+ sessionQueries.clearSessionId(sessionId);
264
+ debug.log('snapshot', 'head_session_id cleared (no valid session found in restored chain)');
268
265
  }
269
266
  }
270
267
 
@@ -315,7 +312,7 @@ export const restoreHandler = createRouter()
315
312
  return {
316
313
  restoredTo: {
317
314
  messageId: sessionEnd.id,
318
- timestamp: sessionEnd.timestamp
315
+ timestamp: sessionEnd.created_at
319
316
  },
320
317
  filesRestored,
321
318
  filesSkipped
@@ -9,6 +9,7 @@ import { t } from 'elysia';
9
9
  import { createRouter } from '$shared/utils/ws-server';
10
10
  import { messageQueries, sessionQueries, checkpointQueries, snapshotQueries } from '../../database/queries';
11
11
  import { debug } from '$shared/utils/logger';
12
+ import { loadMessage } from '$shared/utils/message-formatter';
12
13
  import {
13
14
  extractMessageText,
14
15
  buildCheckpointTree,
@@ -19,7 +20,6 @@ import {
19
20
  INITIAL_NODE_ID
20
21
  } from '../../snapshot/helpers';
21
22
  import type { CheckpointNode, TimelineResponse } from '../../snapshot/helpers';
22
- import type { SDKMessage } from '$shared/types/messaging';
23
23
 
24
24
  export const timelineHandler = createRouter()
25
25
  .http('snapshot:get-timeline', {
@@ -119,8 +119,8 @@ export const timelineHandler = createRouter()
119
119
  });
120
120
 
121
121
  for (const cp of checkpoints) {
122
- const sdk = JSON.parse(cp.sdk_message) as SDKMessage;
123
- const messageText = extractMessageText(sdk).trim().slice(0, 100);
122
+ const msg = loadMessage(cp);
123
+ const messageText = extractMessageText(msg).trim().slice(0, 100);
124
124
  const parentCpId = parentMap.get(cp.id) || null;
125
125
  const activeChildId = activeChildrenMap.get(cp.id) || null;
126
126
  const isOnActivePath = activePathIds.has(cp.id);
@@ -147,13 +147,13 @@ export const timelineHandler = createRouter()
147
147
  // Root checkpoints have initial node as parent
148
148
  parentId: parentCpId || INITIAL_NODE_ID,
149
149
  activeChildId,
150
- timestamp: cp.timestamp,
150
+ timestamp: cp.created_at,
151
151
  messageText,
152
152
  isOnActivePath,
153
153
  isOrphaned,
154
154
  isCurrent,
155
155
  hasSnapshot: !!snapshot,
156
- senderName: cp.sender_name,
156
+ senderName: msg.type === 'user' ? msg.sender?.name || null : null,
157
157
  filesChanged: stats.filesChanged,
158
158
  insertions: stats.insertions,
159
159
  deletions: stats.deletions
@@ -1,2 +1,2 @@
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};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-D1QNkcRL.js","assets/main-rtLiuU_x.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-D1QNkcRL.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-D1QNkcRL.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-D1QNkcRL.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-D1QNkcRL.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-D1QNkcRL.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};