@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
@@ -1,5 +1,7 @@
1
1
  import { getDatabase } from '../index';
2
- import type { ChatSession, Branch } from '$shared/types/database/schema';
2
+ import type { ChatSession, Branch, DatabaseMessage } from '$shared/types/database/schema';
3
+ import { loadMessage } from '$shared/utils/message-formatter';
4
+ import { extractMessageText } from '../../snapshot/helpers';
3
5
 
4
6
  export const sessionQueries = {
5
7
  getAll(): ChatSession[] {
@@ -32,15 +34,15 @@ export const sessionQueries = {
32
34
  const newSession = { id, ...session };
33
35
 
34
36
  db.prepare(`
35
- INSERT INTO chat_sessions (id, project_id, title, engine, latest_sdk_session_id, current_head_message_id, started_at, ended_at)
37
+ INSERT INTO chat_sessions (id, project_id, title, engine, head_session_id, head_message_id, started_at, ended_at)
36
38
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
37
39
  `).run(
38
40
  id,
39
41
  session.project_id,
40
42
  session.title || null,
41
43
  session.engine || 'claude-code',
42
- session.latest_sdk_session_id || null,
43
- session.current_head_message_id || null,
44
+ session.head_session_id || null,
45
+ session.head_message_id || null,
44
46
  session.started_at,
45
47
  session.ended_at || null
46
48
  );
@@ -57,40 +59,184 @@ export const sessionQueries = {
57
59
  `).run(title, id);
58
60
  },
59
61
 
60
- updateLatestSdkSessionId(id: string, sdkSessionId: string): void {
62
+ updateSessionId(id: string, sessionId: string): void {
61
63
  const db = getDatabase();
62
64
  db.prepare(`
63
65
  UPDATE chat_sessions
64
- SET latest_sdk_session_id = ?
66
+ SET head_session_id = ?
65
67
  WHERE id = ?
66
- `).run(sdkSessionId, id);
68
+ `).run(sessionId, id);
67
69
  },
68
70
 
69
- clearLatestSdkSessionId(id: string): void {
71
+ clearSessionId(id: string): void {
70
72
  const db = getDatabase();
71
73
  db.prepare(`
72
74
  UPDATE chat_sessions
73
- SET latest_sdk_session_id = NULL
75
+ SET head_session_id = NULL
74
76
  WHERE id = ?
75
77
  `).run(id);
76
78
  },
77
79
 
78
- updateEngineModel(id: string, engine: string, model: string): void {
80
+ updateEngineModel(id: string, engine: string, provider: string, modelId: string, modelName: string): void {
79
81
  const db = getDatabase();
80
82
  db.prepare(`
81
83
  UPDATE chat_sessions
82
- SET engine = ?, model = ?
84
+ SET engine = ?, provider = ?, model_id = ?, model_name = ?
83
85
  WHERE id = ?
84
- `).run(engine, model, id);
86
+ `).run(engine, provider, modelId, modelName, id);
85
87
  },
86
88
 
87
- updateClaudeAccountId(id: string, claudeAccountId: number | null): void {
89
+ updateAccountId(id: string, accountId: number | null): void {
88
90
  const db = getDatabase();
89
91
  db.prepare(`
90
92
  UPDATE chat_sessions
91
- SET claude_account_id = ?
93
+ SET account_id = ?
92
94
  WHERE id = ?
93
- `).run(claudeAccountId, id);
95
+ `).run(accountId, id);
96
+ },
97
+
98
+ updateAccount(id: string, accountId: number | null, accountName: string | null): void {
99
+ const db = getDatabase();
100
+ db.prepare(`
101
+ UPDATE chat_sessions
102
+ SET account_id = ?, account_name = ?
103
+ WHERE id = ?
104
+ `).run(accountId, accountName, id);
105
+ },
106
+
107
+ /**
108
+ * Update session metadata after a message is saved.
109
+ * Increments counts, updates sender, timestamps, and HEAD content snapshot.
110
+ */
111
+ updateOnMessage(id: string, opts: {
112
+ messageType: string;
113
+ senderId?: string | null;
114
+ senderName?: string | null;
115
+ timestamp: string;
116
+ headTitle?: string | null;
117
+ headSummary?: string | null;
118
+ isFirstUserMessage?: boolean;
119
+ title?: string;
120
+ }): void {
121
+ const db = getDatabase();
122
+ const sets: string[] = [
123
+ 'message_count = COALESCE(message_count, 0) + 1',
124
+ 'last_message_at = ?',
125
+ ];
126
+ const params: (string | number | null)[] = [opts.timestamp];
127
+
128
+ if (opts.messageType === 'user') {
129
+ sets.push('user_count = COALESCE(user_count, 0) + 1');
130
+ }
131
+
132
+ if (opts.senderId !== undefined) {
133
+ sets.push('sender_id = ?');
134
+ params.push(opts.senderId ?? null);
135
+ }
136
+ if (opts.senderName !== undefined) {
137
+ sets.push('sender_name = ?');
138
+ params.push(opts.senderName ?? null);
139
+ }
140
+
141
+ if (opts.headTitle !== undefined) {
142
+ sets.push('head_title = ?');
143
+ params.push(opts.headTitle ?? null);
144
+ }
145
+ if (opts.headSummary !== undefined) {
146
+ sets.push('head_summary = ?');
147
+ params.push(opts.headSummary ?? null);
148
+ }
149
+
150
+ // Auto-set title from first user message
151
+ if (opts.isFirstUserMessage && opts.title) {
152
+ sets.push('title = ?');
153
+ params.push(opts.title);
154
+ }
155
+
156
+ params.push(id);
157
+ db.prepare(`UPDATE chat_sessions SET ${sets.join(', ')} WHERE id = ?`).run(...params);
158
+ },
159
+
160
+ /**
161
+ * Re-derive HEAD content snapshot from the HEAD chain.
162
+ * Called after undo/redo/restore when HEAD changes.
163
+ */
164
+ updateHeadSnapshot(id: string, headTitle: string | null, headSummary: string | null): void {
165
+ const db = getDatabase();
166
+ db.prepare(`
167
+ UPDATE chat_sessions
168
+ SET head_title = ?, head_summary = ?
169
+ WHERE id = ?
170
+ `).run(headTitle, headSummary, id);
171
+ },
172
+
173
+ /**
174
+ * Re-derive HEAD snapshot by walking the HEAD chain.
175
+ * Called after undo/redo/restore when HEAD changes.
176
+ */
177
+ rederiveHeadSnapshot(sessionId: string): void {
178
+ const db = getDatabase();
179
+ const session = db.prepare('SELECT head_message_id FROM chat_sessions WHERE id = ?')
180
+ .get(sessionId) as { head_message_id: string | null } | null;
181
+
182
+ if (!session?.head_message_id) {
183
+ // HEAD cleared (initial state) — clear snapshot
184
+ this.updateHeadSnapshot(sessionId, null, null);
185
+ return;
186
+ }
187
+
188
+ // Build lookup for HEAD chain walk
189
+ const allMsgs = db.prepare(
190
+ 'SELECT id, data, parent_message_id FROM messages WHERE session_id = ?'
191
+ ).all(sessionId) as DatabaseMessage[];
192
+ const msgLookup = new Map(allMsgs.map(m => [m.id, m]));
193
+
194
+ let headTitle: string | null = null;
195
+ let headSummary: string | null = null;
196
+ let walkId: string | null = session.head_message_id;
197
+
198
+ while (walkId) {
199
+ const row = msgLookup.get(walkId);
200
+ if (!row) break;
201
+
202
+ const msg = loadMessage(row);
203
+
204
+ if (!headSummary && msg.type === 'assistant') {
205
+ const text = extractMessageText(msg);
206
+ const clean = text.replace(/```[\s\S]*?```/g, '').trim();
207
+ if (clean) {
208
+ headSummary = clean.slice(0, 200) + (clean.length > 200 ? '...' : '');
209
+ }
210
+ }
211
+ if (!headTitle && msg.type === 'user') {
212
+ const text = extractMessageText(msg).trim();
213
+ if (text) {
214
+ headTitle = text.slice(0, 80) + (text.length > 80 ? '...' : '');
215
+ }
216
+ }
217
+
218
+ if (headTitle && headSummary) break;
219
+ walkId = row.parent_message_id || null;
220
+ }
221
+
222
+ this.updateHeadSnapshot(sessionId, headTitle, headSummary);
223
+ },
224
+
225
+ /**
226
+ * Search sessions by message content.
227
+ * Returns session IDs that have matching messages.
228
+ */
229
+ searchByMessageContent(projectId: string, query: string, limit: number = 20): string[] {
230
+ const db = getDatabase();
231
+ const rows = db.prepare(`
232
+ SELECT DISTINCT m.session_id
233
+ FROM messages m
234
+ INNER JOIN chat_sessions cs ON cs.id = m.session_id
235
+ WHERE cs.project_id = ?
236
+ AND m.data LIKE ?
237
+ LIMIT ?
238
+ `).all(projectId, `%${query}%`, limit) as { session_id: string }[];
239
+ return rows.map(r => r.session_id);
94
240
  },
95
241
 
96
242
  end(id: string): void {
@@ -213,7 +359,7 @@ export const sessionQueries = {
213
359
  title: `Shared Chat - ${projectName} (${new Date().toLocaleString()})`,
214
360
  started_at: now,
215
361
  ended_at: undefined,
216
- latest_sdk_session_id: undefined
362
+ head_session_id: undefined
217
363
  });
218
364
  },
219
365
 
@@ -227,7 +373,7 @@ export const sessionQueries = {
227
373
  const db = getDatabase();
228
374
  db.prepare(`
229
375
  UPDATE chat_sessions
230
- SET current_head_message_id = ?
376
+ SET head_message_id = ?
231
377
  WHERE id = ?
232
378
  `).run(messageId, sessionId);
233
379
  },
@@ -240,7 +386,7 @@ export const sessionQueries = {
240
386
  const db = getDatabase();
241
387
  db.prepare(`
242
388
  UPDATE chat_sessions
243
- SET current_head_message_id = NULL
389
+ SET head_message_id = NULL
244
390
  WHERE id = ?
245
391
  `).run(sessionId);
246
392
  },
@@ -251,10 +397,10 @@ export const sessionQueries = {
251
397
  getHead(sessionId: string): string | null {
252
398
  const db = getDatabase();
253
399
  const session = db.prepare(`
254
- SELECT current_head_message_id FROM chat_sessions WHERE id = ?
255
- `).get(sessionId) as { current_head_message_id: string | null } | null;
400
+ SELECT head_message_id FROM chat_sessions WHERE id = ?
401
+ `).get(sessionId) as { head_message_id: string | null } | null;
256
402
 
257
- return session?.current_head_message_id || null;
403
+ return session?.head_message_id || null;
258
404
  },
259
405
 
260
406
  /**
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { MessageSnapshot, SessionRelationship } from '$shared/types/database/schema';
7
7
  import { getDatabase } from '../index';
8
+ import type { UnifiedMessage } from '$shared/types/unified';
8
9
 
9
10
  import { debug } from '$shared/utils/logger';
10
11
  export const snapshotQueries = {
@@ -160,12 +161,12 @@ export const snapshotQueries = {
160
161
 
161
162
  // Get snapshots with their associated messages to determine type
162
163
  const allSnapshots = db.prepare(`
163
- SELECT ms.id, ms.created_at, ms.message_id, m.sdk_message
164
+ SELECT ms.id, ms.created_at, ms.message_id, m.data
164
165
  FROM message_snapshots ms
165
166
  JOIN messages m ON ms.message_id = m.id
166
167
  WHERE ms.session_id = ?
167
168
  ORDER BY ms.created_at ASC
168
- `).all(sessionId) as { id: string; created_at: string; message_id: string; sdk_message: string }[];
169
+ `).all(sessionId) as { id: string; created_at: string; message_id: string; data: string }[];
169
170
 
170
171
  // Find the checkpoint snapshot index
171
172
  const checkpointIndex = allSnapshots.findIndex(snap => snap.created_at === checkpointTimestamp);
@@ -178,8 +179,8 @@ export const snapshotQueries = {
178
179
  // Find next USER message snapshot after checkpoint
179
180
  let deleteFromIndex = -1;
180
181
  for (let i = checkpointIndex + 1; i < allSnapshots.length; i++) {
181
- const sdkMessage = JSON.parse(allSnapshots[i].sdk_message);
182
- if (sdkMessage.type === 'user') {
182
+ const msg = JSON.parse(allSnapshots[i].data) as UnifiedMessage;
183
+ if (msg.type === 'user') {
183
184
  deleteFromIndex = i;
184
185
  break;
185
186
  }
@@ -30,8 +30,8 @@ export const dbUtils = {
30
30
  FROM messages m
31
31
  JOIN chat_sessions cs ON m.session_id = cs.id
32
32
  JOIN projects p ON cs.project_id = p.id
33
- WHERE m.content LIKE ?
34
- ORDER BY m.timestamp DESC
33
+ WHERE m.data LIKE ?
34
+ ORDER BY m.created_at DESC
35
35
  LIMIT ?
36
36
  `).all(`%${query}%`, limit) as (DatabaseMessage & { project_name: string })[];
37
37
  },
@@ -68,10 +68,9 @@ export function getEngineEnv(accountId?: number): Record<string, string> {
68
68
  // Override with specific account token if requested
69
69
  if (accountId !== undefined) {
70
70
  try {
71
- const accounts = engineQueries.getClaudeAccounts();
72
- const account = accounts.find(a => a.id === accountId);
71
+ const account = engineQueries.getAccount(accountId);
73
72
  if (account) {
74
- env['CLAUDE_CODE_OAUTH_TOKEN'] = account.oauth_token;
73
+ env['CLAUDE_CODE_OAUTH_TOKEN'] = account.credential;
75
74
  debug.log('engine', `Claude Code: Per-session account override → "${account.name}"`);
76
75
  }
77
76
  } catch {
@@ -95,9 +94,9 @@ async function _doSetup(): Promise<void> {
95
94
 
96
95
  // Inject OAuth token from active account (if any)
97
96
  try {
98
- const activeAccount = engineQueries.getActiveClaudeAccount();
97
+ const activeAccount = engineQueries.getActiveAccountForEngine('claude-code');
99
98
  if (activeAccount) {
100
- overrides['CLAUDE_CODE_OAUTH_TOKEN'] = activeAccount.oauth_token;
99
+ overrides['CLAUDE_CODE_OAUTH_TOKEN'] = activeAccount.credential;
101
100
  debug.log('engine', `✅ Claude Code: Using account "${activeAccount.name}"`);
102
101
  }
103
102
  } catch {