@myrialabs/clopen 0.2.23 → 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.
- package/README.md +1 -1
- package/backend/chat/helpers.ts +2 -20
- package/backend/chat/stream-manager.ts +556 -547
- package/backend/database/migrations/027_create_opencode_providers_table.ts +27 -0
- package/backend/database/migrations/028_create_opencode_accounts_table.ts +25 -0
- package/backend/database/migrations/029_migrate_messages_to_unified.ts +1108 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/database/queries/engine-queries.ts +195 -36
- package/backend/database/queries/message-queries.ts +84 -139
- package/backend/database/queries/session-queries.ts +167 -21
- package/backend/database/queries/snapshot-queries.ts +5 -4
- package/backend/database/queries/utils-queries.ts +2 -2
- package/backend/engine/adapters/claude/environment.ts +4 -5
- package/backend/engine/adapters/claude/message-converter.ts +501 -0
- package/backend/engine/adapters/claude/stream.ts +52 -47
- package/backend/engine/adapters/opencode/config.ts +156 -0
- package/backend/engine/adapters/opencode/message-converter.ts +266 -326
- package/backend/engine/adapters/opencode/server.ts +54 -12
- package/backend/engine/adapters/opencode/stream.ts +84 -101
- package/backend/engine/types.ts +17 -11
- package/backend/project/status-manager.ts +10 -13
- package/backend/snapshot/helpers.ts +46 -90
- package/backend/snapshot/snapshot-service.ts +1 -1
- package/backend/utils/paths.ts +22 -1
- package/backend/ws/chat/index.ts +1 -11
- package/backend/ws/chat/stream.ts +101 -61
- package/backend/ws/engine/claude/accounts.ts +27 -7
- package/backend/ws/engine/claude/status.ts +3 -2
- package/backend/ws/engine/opencode/index.ts +3 -1
- package/backend/ws/engine/opencode/providers.ts +300 -0
- package/backend/ws/git/commit-message.ts +6 -8
- package/backend/ws/messages/crud.ts +4 -59
- package/backend/ws/sessions/crud.ts +78 -130
- package/backend/ws/sessions/index.ts +1 -9
- package/backend/ws/settings/crud.ts +14 -11
- package/backend/ws/snapshot/restore.ts +23 -26
- package/backend/ws/snapshot/timeline.ts +5 -5
- package/dist/assets/{index-BFFIy7ZX.js → index-B95VOHJY.js} +2 -2
- package/dist/assets/main-D1QNkcRL.js +257 -0
- package/dist/assets/main-rtLiuU_x.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -4
- package/shared/constants/engines.ts +141 -56
- package/shared/types/database/schema.ts +39 -40
- package/shared/types/stores/settings.ts +8 -4
- package/shared/types/unified/common.ts +21 -0
- package/shared/types/unified/display.ts +25 -0
- package/shared/types/unified/engine.ts +61 -0
- package/shared/types/unified/index.ts +108 -0
- package/shared/types/unified/message.ts +151 -0
- package/shared/types/unified/stream.ts +157 -0
- package/shared/types/unified/tool.ts +268 -0
- package/shared/utils/message-formatter.ts +9 -73
- package/shared/utils/path.ts +3 -2
- package/tsconfig.json +1 -1
- package/backend/engine/adapters/claude/path-utils.ts +0 -38
- package/backend/ws/chat/background.ts +0 -201
- package/dist/assets/main-CtNvgvwE.js +0 -249
- package/dist/assets/main-DmshCkFM.css +0 -1
- package/shared/types/engine/index.ts +0 -45
- package/shared/types/messaging/index.ts +0 -242
- package/shared/types/messaging/tool.ts +0 -374
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { snapshotQueries, messageQueries, checkpointQueries } from '../database/queries';
|
|
2
2
|
import { debug } from '$shared/utils/logger';
|
|
3
|
-
import
|
|
3
|
+
import { loadMessage } from '$shared/utils/message-formatter';
|
|
4
4
|
import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
5
|
+
import type { UnifiedMessage, UserMessage } from '$shared/types/unified';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Snapshot domain helper functions
|
|
@@ -37,50 +38,31 @@ export interface TimelineResponse {
|
|
|
37
38
|
/**
|
|
38
39
|
* Check if a user message is an internal/non-genuine user message.
|
|
39
40
|
*
|
|
40
|
-
*
|
|
41
|
-
* typed by the real human user:
|
|
41
|
+
* Internal messages include:
|
|
42
42
|
* 1. Tool-result confirmations — content contains `tool_result` blocks
|
|
43
|
-
* 2. Sub-agent / Task prompts —
|
|
44
|
-
* 3. Post-compaction synthetic summaries —
|
|
45
|
-
*
|
|
46
|
-
* Only messages that pass none of these checks are genuine user input.
|
|
43
|
+
* 2. Sub-agent / Task prompts — parentToolUseId is non-null
|
|
44
|
+
* 3. Post-compaction synthetic summaries — synthetic is true
|
|
47
45
|
*/
|
|
48
|
-
export function isInternalToolMessage(
|
|
49
|
-
if (
|
|
50
|
-
|
|
51
|
-
// Sub-agent or tool-result message (parent_tool_use_id is set)
|
|
52
|
-
if (sdkMessage.parent_tool_use_id != null) return true;
|
|
46
|
+
export function isInternalToolMessage(msg: UnifiedMessage): boolean {
|
|
47
|
+
if (msg.type !== 'user') return false;
|
|
48
|
+
const user = msg as UserMessage;
|
|
53
49
|
|
|
54
|
-
|
|
55
|
-
if (
|
|
50
|
+
if (user.parent.toolUseId != null) return true;
|
|
51
|
+
if (user.synthetic) return true;
|
|
56
52
|
|
|
57
|
-
|
|
58
|
-
if (!content) return false;
|
|
59
|
-
|
|
60
|
-
// Check if content is array and contains tool_result blocks
|
|
61
|
-
if (Array.isArray(content)) {
|
|
62
|
-
return content.some((block: any) => block.type === 'tool_result');
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
return false;
|
|
53
|
+
return user.content.some(block => block.type === 'tool_result');
|
|
66
54
|
}
|
|
67
55
|
|
|
68
56
|
/**
|
|
69
|
-
* Extract
|
|
57
|
+
* Extract text from a UnifiedMessage.
|
|
70
58
|
*/
|
|
71
|
-
export function extractMessageText(
|
|
72
|
-
if ('
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
(item: any) => typeof item === 'object' && 'text' in item
|
|
79
|
-
);
|
|
80
|
-
if (textBlock && 'text' in textBlock) {
|
|
81
|
-
return textBlock.text;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
59
|
+
export function extractMessageText(msg: UnifiedMessage): string {
|
|
60
|
+
if (msg.type === 'reasoning') return msg.text;
|
|
61
|
+
if (msg.type === 'compact_boundary') return '';
|
|
62
|
+
|
|
63
|
+
// user or assistant — both have content arrays
|
|
64
|
+
for (const block of msg.content) {
|
|
65
|
+
if (block.type === 'text' && block.text) return block.text;
|
|
84
66
|
}
|
|
85
67
|
return '';
|
|
86
68
|
}
|
|
@@ -88,13 +70,12 @@ export function extractMessageText(sdkMessage: SDKMessage): string {
|
|
|
88
70
|
/**
|
|
89
71
|
* Check if a database message is a checkpoint (real user message with text)
|
|
90
72
|
*/
|
|
91
|
-
export function isCheckpointMessage(
|
|
73
|
+
export function isCheckpointMessage(row: DatabaseMessage): boolean {
|
|
92
74
|
try {
|
|
93
|
-
const
|
|
94
|
-
if (
|
|
95
|
-
if (isInternalToolMessage(
|
|
96
|
-
|
|
97
|
-
return text.trim() !== '';
|
|
75
|
+
const msg = loadMessage(row);
|
|
76
|
+
if (msg.type !== 'user') return false;
|
|
77
|
+
if (isInternalToolMessage(msg)) return false;
|
|
78
|
+
return extractMessageText(msg).trim() !== '';
|
|
98
79
|
} catch {
|
|
99
80
|
return false;
|
|
100
81
|
}
|
|
@@ -224,7 +205,6 @@ export function findSessionEnd(
|
|
|
224
205
|
}
|
|
225
206
|
|
|
226
207
|
// Fallback: timestamp-based approach
|
|
227
|
-
// Walk chronologically through messages after checkpoint until next real user message
|
|
228
208
|
debug.log('snapshot', `findSessionEnd: parent-based returned checkpoint itself, trying timestamp fallback`);
|
|
229
209
|
const timestampResult = findSessionEndByTimestamp(checkpointMsg, allMessages);
|
|
230
210
|
|
|
@@ -237,6 +217,17 @@ export function findSessionEnd(
|
|
|
237
217
|
return checkpointMsg;
|
|
238
218
|
}
|
|
239
219
|
|
|
220
|
+
/**
|
|
221
|
+
* Check if a DatabaseMessage is a session continuation
|
|
222
|
+
* (assistant, internal user, or compact boundary — NOT a real user message).
|
|
223
|
+
*/
|
|
224
|
+
function isSessionContinuation(row: DatabaseMessage): boolean {
|
|
225
|
+
const msg = loadMessage(row);
|
|
226
|
+
if (msg.type === 'assistant' || msg.type === 'reasoning' || msg.type === 'compact_boundary') return true;
|
|
227
|
+
if (msg.type === 'user' && isInternalToolMessage(msg)) return true;
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
|
|
240
231
|
/**
|
|
241
232
|
* Parent-based session end finder.
|
|
242
233
|
* Walks through childrenMap (parent_message_id relationships).
|
|
@@ -260,36 +251,12 @@ function findSessionEndByParent(
|
|
|
260
251
|
|
|
261
252
|
while (true) {
|
|
262
253
|
const children = childrenMap.get(current.id) || [];
|
|
263
|
-
children.sort((a, b) => a.
|
|
264
|
-
|
|
265
|
-
let sessionContinuation: DatabaseMessage | null = null;
|
|
266
|
-
|
|
267
|
-
for (const child of children) {
|
|
268
|
-
try {
|
|
269
|
-
const sdk = JSON.parse(child.sdk_message);
|
|
270
|
-
if (sdk.type === 'assistant') {
|
|
271
|
-
sessionContinuation = child;
|
|
272
|
-
break;
|
|
273
|
-
}
|
|
274
|
-
if (sdk.type === 'user' && isInternalToolMessage(sdk)) {
|
|
275
|
-
sessionContinuation = child;
|
|
276
|
-
break;
|
|
277
|
-
}
|
|
278
|
-
// System messages (e.g. compact_boundary) are part of session continuation
|
|
279
|
-
if (sdk.type === 'system') {
|
|
280
|
-
sessionContinuation = child;
|
|
281
|
-
break;
|
|
282
|
-
}
|
|
283
|
-
} catch {
|
|
284
|
-
continue;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
254
|
+
children.sort((a, b) => a.created_at.localeCompare(b.created_at));
|
|
287
255
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
256
|
+
const continuation = children.find(child => isSessionContinuation(child));
|
|
257
|
+
if (!continuation) return lastValidEnd;
|
|
291
258
|
|
|
292
|
-
current =
|
|
259
|
+
current = continuation;
|
|
293
260
|
lastValidEnd = current;
|
|
294
261
|
}
|
|
295
262
|
}
|
|
@@ -303,7 +270,7 @@ function findSessionEndByTimestamp(
|
|
|
303
270
|
checkpointMsg: DatabaseMessage,
|
|
304
271
|
allMessages: DatabaseMessage[]
|
|
305
272
|
): DatabaseMessage {
|
|
306
|
-
const sorted = [...allMessages].sort((a, b) => a.
|
|
273
|
+
const sorted = [...allMessages].sort((a, b) => a.created_at.localeCompare(b.created_at));
|
|
307
274
|
|
|
308
275
|
const checkpointIndex = sorted.findIndex(m => m.id === checkpointMsg.id);
|
|
309
276
|
if (checkpointIndex === -1) return checkpointMsg;
|
|
@@ -311,23 +278,12 @@ function findSessionEndByTimestamp(
|
|
|
311
278
|
let lastValidEnd = checkpointMsg;
|
|
312
279
|
|
|
313
280
|
for (let i = checkpointIndex + 1; i < sorted.length; i++) {
|
|
314
|
-
const
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
} else if (sdk.type === 'user' && isInternalToolMessage(sdk)) {
|
|
321
|
-
lastValidEnd = msg;
|
|
322
|
-
} else if (sdk.type === 'system') {
|
|
323
|
-
// System messages (e.g. compact_boundary) are part of session continuation
|
|
324
|
-
lastValidEnd = msg;
|
|
325
|
-
} else if (sdk.type === 'user' && !isInternalToolMessage(sdk)) {
|
|
326
|
-
// Hit the next real user message (checkpoint) - stop
|
|
327
|
-
break;
|
|
328
|
-
}
|
|
329
|
-
} catch {
|
|
330
|
-
continue;
|
|
281
|
+
const row = sorted[i];
|
|
282
|
+
if (isSessionContinuation(row)) {
|
|
283
|
+
lastValidEnd = row;
|
|
284
|
+
} else {
|
|
285
|
+
// Hit a real user message — stop
|
|
286
|
+
break;
|
|
331
287
|
}
|
|
332
288
|
}
|
|
333
289
|
|
|
@@ -347,7 +347,7 @@ export class SnapshotService {
|
|
|
347
347
|
const headMsg = messageQueries.getById(currentHead);
|
|
348
348
|
if (headMsg) {
|
|
349
349
|
for (let i = sessionSnapshots.length - 1; i >= 0; i--) {
|
|
350
|
-
if (sessionSnapshots[i].created_at <= headMsg.
|
|
350
|
+
if (sessionSnapshots[i].created_at <= headMsg.created_at) {
|
|
351
351
|
if (sessionSnapshots[i].created_at < targetTime) {
|
|
352
352
|
referenceTime = sessionSnapshots[i].created_at;
|
|
353
353
|
}
|
package/backend/utils/paths.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { join } from 'path';
|
|
1
|
+
import { join, resolve } from 'path';
|
|
2
2
|
import { homedir } from 'os';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -9,3 +9,24 @@ import { homedir } from 'os';
|
|
|
9
9
|
export function getClopenDir(): string {
|
|
10
10
|
return join(homedir(), process.env.NODE_ENV === 'development' ? '.clopen-dev' : '.clopen');
|
|
11
11
|
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Resolve a path to an OS-native absolute path.
|
|
15
|
+
* On Windows: resolves relative paths, prepends drive letter, converts to backslashes.
|
|
16
|
+
* On POSIX: returns path as-is (already absolute from OS perspective).
|
|
17
|
+
*/
|
|
18
|
+
export function resolveOsPath(projectPath: string): string {
|
|
19
|
+
let resolved = projectPath;
|
|
20
|
+
if (process.platform === 'win32') {
|
|
21
|
+
if (!projectPath.match(/^[A-Za-z]:\\/)) {
|
|
22
|
+
if (projectPath.startsWith('\\')) {
|
|
23
|
+
const currentDrive = process.cwd().substring(0, 2);
|
|
24
|
+
resolved = currentDrive + projectPath;
|
|
25
|
+
} else {
|
|
26
|
+
resolved = resolve(projectPath);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
resolved = resolved.replace(/\//g, '\\');
|
|
30
|
+
}
|
|
31
|
+
return resolved;
|
|
32
|
+
}
|
package/backend/ws/chat/index.ts
CHANGED
|
@@ -2,20 +2,10 @@
|
|
|
2
2
|
* Chat Router
|
|
3
3
|
*
|
|
4
4
|
* Combines all chat WebSocket handlers into a single router.
|
|
5
|
-
* Replaces the old SSE-based chat streaming system.
|
|
6
|
-
*
|
|
7
|
-
* Structure:
|
|
8
|
-
* - stream.ts: Real-time chat streaming events (stream, cancel)
|
|
9
|
-
* - background.ts: Background streaming management (start, state, messages, cancel)
|
|
10
5
|
*/
|
|
11
6
|
|
|
12
7
|
import { createRouter } from '$shared/utils/ws-server';
|
|
13
8
|
import { streamHandler } from './stream';
|
|
14
|
-
import { backgroundHandler } from './background';
|
|
15
9
|
|
|
16
10
|
export const chatRouter = createRouter()
|
|
17
|
-
|
|
18
|
-
.merge(streamHandler)
|
|
19
|
-
|
|
20
|
-
// Background streaming
|
|
21
|
-
.merge(backgroundHandler);
|
|
11
|
+
.merge(streamHandler);
|
|
@@ -65,10 +65,10 @@ const chatSessionInputState = new Map<string, { text: string; senderId: string;
|
|
|
65
65
|
const chatSessionEditMode = new Map<string, { isEditing: boolean; messageId: string | null; messageTimestamp: string | null }>();
|
|
66
66
|
|
|
67
67
|
// In-memory store for model state per chat session (keyed by chatSessionId)
|
|
68
|
-
const chatSessionModelState = new Map<string, { engine: string;
|
|
68
|
+
const chatSessionModelState = new Map<string, { engine: string; provider: string; modelId: string; modelName: string; senderId: string }>();
|
|
69
69
|
|
|
70
70
|
// In-memory store for account state per chat session (keyed by chatSessionId)
|
|
71
|
-
const chatSessionAccountState = new Map<string, {
|
|
71
|
+
const chatSessionAccountState = new Map<string, { accountId: number | null; senderId: string }>();
|
|
72
72
|
|
|
73
73
|
export const streamHandler = createRouter()
|
|
74
74
|
// Join a chat session room (subscribe to chat events for this session)
|
|
@@ -101,14 +101,23 @@ export const streamHandler = createRouter()
|
|
|
101
101
|
sessionId: t.String(),
|
|
102
102
|
chatSessionId: t.String(),
|
|
103
103
|
projectPath: t.String(),
|
|
104
|
-
prompt: t.Any(), //
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
104
|
+
prompt: t.Any(), // UserMessage object
|
|
105
|
+
engine: t.Object({
|
|
106
|
+
type: t.Union([t.Literal('claude-code'), t.Literal('opencode')]),
|
|
107
|
+
provider: t.String(),
|
|
108
|
+
model: t.Object({
|
|
109
|
+
id: t.String(),
|
|
110
|
+
name: t.String()
|
|
111
|
+
}),
|
|
112
|
+
account: t.Object({
|
|
113
|
+
id: t.Number(),
|
|
114
|
+
name: t.String()
|
|
115
|
+
})
|
|
116
|
+
}),
|
|
117
|
+
sender: t.Object({
|
|
118
|
+
id: t.String(),
|
|
119
|
+
name: t.String()
|
|
120
|
+
})
|
|
112
121
|
})
|
|
113
122
|
}, async ({ data, conn }) => {
|
|
114
123
|
const projectId = ws.getProjectId(conn);
|
|
@@ -116,8 +125,7 @@ export const streamHandler = createRouter()
|
|
|
116
125
|
try {
|
|
117
126
|
debug.log('chat', 'WS chat:stream received:', {
|
|
118
127
|
chatSessionId: data.chatSessionId,
|
|
119
|
-
projectId
|
|
120
|
-
messagesCount: data.messages?.length || 0
|
|
128
|
+
projectId
|
|
121
129
|
});
|
|
122
130
|
|
|
123
131
|
// Start background stream
|
|
@@ -125,14 +133,9 @@ export const streamHandler = createRouter()
|
|
|
125
133
|
projectPath: data.projectPath,
|
|
126
134
|
projectId,
|
|
127
135
|
prompt: data.prompt,
|
|
128
|
-
messages: data.messages || [],
|
|
129
136
|
chatSessionId: data.chatSessionId,
|
|
130
|
-
engine: data.engine
|
|
131
|
-
|
|
132
|
-
temperature: data.temperature,
|
|
133
|
-
senderId: data.senderId,
|
|
134
|
-
senderName: data.senderName,
|
|
135
|
-
claudeAccountId: data.claudeAccountId
|
|
137
|
+
engine: data.engine,
|
|
138
|
+
sender: data.sender
|
|
136
139
|
});
|
|
137
140
|
|
|
138
141
|
debug.log('chat', 'Stream started with ID:', streamId);
|
|
@@ -452,6 +455,63 @@ export const streamHandler = createRouter()
|
|
|
452
455
|
}
|
|
453
456
|
})
|
|
454
457
|
|
|
458
|
+
// Get active stream state (for reconnect after browser refresh / project switch)
|
|
459
|
+
.http('chat:stream-state', {
|
|
460
|
+
data: t.Object({
|
|
461
|
+
chatSessionId: t.Optional(t.String())
|
|
462
|
+
}),
|
|
463
|
+
response: t.Object({
|
|
464
|
+
streamId: t.String(),
|
|
465
|
+
status: t.Union([
|
|
466
|
+
t.Literal('active'),
|
|
467
|
+
t.Literal('completed'),
|
|
468
|
+
t.Literal('error'),
|
|
469
|
+
t.Literal('cancelled')
|
|
470
|
+
]),
|
|
471
|
+
processId: t.String(),
|
|
472
|
+
messages: t.Array(t.Any()),
|
|
473
|
+
currentPartialText: t.Optional(t.String()),
|
|
474
|
+
currentReasoningText: t.Optional(t.String()),
|
|
475
|
+
error: t.Optional(t.String()),
|
|
476
|
+
startedAt: t.String(),
|
|
477
|
+
completedAt: t.Optional(t.String())
|
|
478
|
+
})
|
|
479
|
+
}, async ({ data, conn }) => {
|
|
480
|
+
const projectId = ws.getProjectId(conn);
|
|
481
|
+
|
|
482
|
+
const streamState = data.chatSessionId
|
|
483
|
+
? streamManager.getSessionStream(data.chatSessionId, projectId)
|
|
484
|
+
: undefined;
|
|
485
|
+
|
|
486
|
+
// Return a "not found" response instead of throwing
|
|
487
|
+
// This happens normally when a stream was cancelled/completed and cleaned up
|
|
488
|
+
if (!streamState) {
|
|
489
|
+
return {
|
|
490
|
+
streamId: data.chatSessionId || '',
|
|
491
|
+
status: 'completed' as const,
|
|
492
|
+
processId: '',
|
|
493
|
+
messages: [],
|
|
494
|
+
currentPartialText: undefined,
|
|
495
|
+
currentReasoningText: undefined,
|
|
496
|
+
error: undefined,
|
|
497
|
+
startedAt: new Date().toISOString(),
|
|
498
|
+
completedAt: new Date().toISOString()
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
return {
|
|
503
|
+
streamId: streamState.streamId,
|
|
504
|
+
status: streamState.status,
|
|
505
|
+
processId: streamState.processId,
|
|
506
|
+
messages: streamState.messages,
|
|
507
|
+
currentPartialText: streamState.currentPartialText,
|
|
508
|
+
currentReasoningText: streamState.currentReasoningText,
|
|
509
|
+
error: streamState.error,
|
|
510
|
+
startedAt: streamState.startedAt.toISOString(),
|
|
511
|
+
completedAt: streamState.completedAt?.toISOString()
|
|
512
|
+
};
|
|
513
|
+
})
|
|
514
|
+
|
|
455
515
|
// Cancel stream
|
|
456
516
|
.on('chat:cancel', {
|
|
457
517
|
data: t.Object({
|
|
@@ -601,7 +661,9 @@ export const streamHandler = createRouter()
|
|
|
601
661
|
senderId: t.String(),
|
|
602
662
|
chatSessionId: t.String(),
|
|
603
663
|
engine: t.String(),
|
|
604
|
-
|
|
664
|
+
provider: t.String(),
|
|
665
|
+
modelId: t.String(),
|
|
666
|
+
modelName: t.String()
|
|
605
667
|
})
|
|
606
668
|
}, ({ data }) => {
|
|
607
669
|
const chatSessionId = data.chatSessionId;
|
|
@@ -609,14 +671,16 @@ export const streamHandler = createRouter()
|
|
|
609
671
|
// Store latest model state on server for late joiners / refresh
|
|
610
672
|
chatSessionModelState.set(chatSessionId, {
|
|
611
673
|
engine: data.engine,
|
|
612
|
-
|
|
674
|
+
provider: data.provider,
|
|
675
|
+
modelId: data.modelId,
|
|
676
|
+
modelName: data.modelName,
|
|
613
677
|
senderId: data.senderId
|
|
614
678
|
});
|
|
615
679
|
|
|
616
680
|
// Persist engine/model to the session record in the database
|
|
617
681
|
// so refreshes and late joiners get the correct model
|
|
618
682
|
try {
|
|
619
|
-
sessionQueries.updateEngineModel(chatSessionId, data.engine, data.
|
|
683
|
+
sessionQueries.updateEngineModel(chatSessionId, data.engine, data.provider, data.modelId, data.modelName);
|
|
620
684
|
} catch (err) {
|
|
621
685
|
debug.error('chat', 'Failed to persist model sync to DB:', err);
|
|
622
686
|
}
|
|
@@ -625,45 +689,32 @@ export const streamHandler = createRouter()
|
|
|
625
689
|
ws.emit.chatSession(chatSessionId, 'chat:model-sync', {
|
|
626
690
|
senderId: data.senderId,
|
|
627
691
|
engine: data.engine,
|
|
628
|
-
|
|
692
|
+
provider: data.provider,
|
|
693
|
+
modelId: data.modelId,
|
|
694
|
+
modelName: data.modelName
|
|
629
695
|
});
|
|
630
696
|
})
|
|
631
697
|
|
|
632
|
-
// Get current model state for a chat session (for refresh / late joiners)
|
|
633
|
-
.http('chat:get-model-state', {
|
|
634
|
-
data: t.Object({
|
|
635
|
-
chatSessionId: t.Optional(t.String())
|
|
636
|
-
}),
|
|
637
|
-
response: t.Object({
|
|
638
|
-
engine: t.String(),
|
|
639
|
-
model: t.String(),
|
|
640
|
-
senderId: t.String()
|
|
641
|
-
})
|
|
642
|
-
}, ({ data }) => {
|
|
643
|
-
const chatSessionId = data.chatSessionId || '';
|
|
644
|
-
const state = chatSessionModelState.get(chatSessionId);
|
|
645
|
-
return state || { engine: '', model: '', senderId: '' };
|
|
646
|
-
})
|
|
647
|
-
|
|
648
698
|
// Collaborative account sync - broadcast account changes to other users in the same chat session
|
|
649
699
|
.on('chat:account-sync', {
|
|
650
700
|
data: t.Object({
|
|
651
701
|
senderId: t.String(),
|
|
652
702
|
chatSessionId: t.String(),
|
|
653
|
-
|
|
703
|
+
accountId: t.Union([t.Number(), t.Null()]),
|
|
704
|
+
accountName: t.Optional(t.Union([t.String(), t.Null()]))
|
|
654
705
|
})
|
|
655
706
|
}, ({ data }) => {
|
|
656
707
|
const chatSessionId = data.chatSessionId;
|
|
657
708
|
|
|
658
709
|
// Store latest account state on server for late joiners / refresh
|
|
659
710
|
chatSessionAccountState.set(chatSessionId, {
|
|
660
|
-
|
|
711
|
+
accountId: data.accountId,
|
|
661
712
|
senderId: data.senderId
|
|
662
713
|
});
|
|
663
714
|
|
|
664
|
-
// Persist
|
|
715
|
+
// Persist account to the session record in the database
|
|
665
716
|
try {
|
|
666
|
-
sessionQueries.
|
|
717
|
+
sessionQueries.updateAccount(chatSessionId, data.accountId, data.accountName ?? null);
|
|
667
718
|
} catch (err) {
|
|
668
719
|
debug.error('chat', 'Failed to persist account sync to DB:', err);
|
|
669
720
|
}
|
|
@@ -671,25 +722,11 @@ export const streamHandler = createRouter()
|
|
|
671
722
|
// Broadcast to all users in the same chat session
|
|
672
723
|
ws.emit.chatSession(chatSessionId, 'chat:account-sync', {
|
|
673
724
|
senderId: data.senderId,
|
|
674
|
-
|
|
725
|
+
accountId: data.accountId,
|
|
726
|
+
accountName: data.accountName ?? null
|
|
675
727
|
});
|
|
676
728
|
})
|
|
677
729
|
|
|
678
|
-
// Get current account state for a chat session (for refresh / late joiners)
|
|
679
|
-
.http('chat:get-account-state', {
|
|
680
|
-
data: t.Object({
|
|
681
|
-
chatSessionId: t.Optional(t.String())
|
|
682
|
-
}),
|
|
683
|
-
response: t.Object({
|
|
684
|
-
claudeAccountId: t.Union([t.Number(), t.Null()]),
|
|
685
|
-
senderId: t.String()
|
|
686
|
-
})
|
|
687
|
-
}, ({ data }) => {
|
|
688
|
-
const chatSessionId = data.chatSessionId || '';
|
|
689
|
-
const state = chatSessionAccountState.get(chatSessionId);
|
|
690
|
-
return state || { claudeAccountId: null, senderId: '' };
|
|
691
|
-
})
|
|
692
|
-
|
|
693
730
|
// Event declarations
|
|
694
731
|
.emit('chat:edit-mode', t.Object({
|
|
695
732
|
senderId: t.String(),
|
|
@@ -714,12 +751,15 @@ export const streamHandler = createRouter()
|
|
|
714
751
|
.emit('chat:model-sync', t.Object({
|
|
715
752
|
senderId: t.String(),
|
|
716
753
|
engine: t.String(),
|
|
717
|
-
|
|
754
|
+
provider: t.String(),
|
|
755
|
+
modelId: t.String(),
|
|
756
|
+
modelName: t.String()
|
|
718
757
|
}))
|
|
719
758
|
|
|
720
759
|
.emit('chat:account-sync', t.Object({
|
|
721
760
|
senderId: t.String(),
|
|
722
|
-
|
|
761
|
+
accountId: t.Union([t.Number(), t.Null()]),
|
|
762
|
+
accountName: t.Union([t.String(), t.Null()])
|
|
723
763
|
}))
|
|
724
764
|
|
|
725
765
|
.emit('chat:connection', t.Object({
|
|
@@ -127,7 +127,9 @@ export const accountsHandler = createRouter()
|
|
|
127
127
|
}))
|
|
128
128
|
})
|
|
129
129
|
}, async () => {
|
|
130
|
-
const
|
|
130
|
+
const provider = engineQueries.getProviderBySlug('claude-code', 'anthropic');
|
|
131
|
+
if (!provider) return { accounts: [] };
|
|
132
|
+
const accounts = engineQueries.getAccountsByProvider(provider.id);
|
|
131
133
|
return {
|
|
132
134
|
accounts: accounts.map(a => ({
|
|
133
135
|
id: a.id,
|
|
@@ -142,7 +144,7 @@ export const accountsHandler = createRouter()
|
|
|
142
144
|
data: t.Object({ id: t.Number() }),
|
|
143
145
|
response: t.Object({ success: t.Boolean() })
|
|
144
146
|
}, async ({ data }) => {
|
|
145
|
-
engineQueries.
|
|
147
|
+
engineQueries.switchAccount(data.id);
|
|
146
148
|
resetEnvironment();
|
|
147
149
|
return { success: true };
|
|
148
150
|
})
|
|
@@ -151,8 +153,8 @@ export const accountsHandler = createRouter()
|
|
|
151
153
|
data: t.Object({ id: t.Number() }),
|
|
152
154
|
response: t.Object({ success: t.Boolean() })
|
|
153
155
|
}, async ({ data }) => {
|
|
154
|
-
const active = engineQueries.
|
|
155
|
-
engineQueries.
|
|
156
|
+
const active = engineQueries.getActiveAccountForEngine('claude-code');
|
|
157
|
+
engineQueries.deleteAccount(data.id);
|
|
156
158
|
if (active?.id === data.id) resetEnvironment();
|
|
157
159
|
return { success: true };
|
|
158
160
|
})
|
|
@@ -161,7 +163,7 @@ export const accountsHandler = createRouter()
|
|
|
161
163
|
data: t.Object({ id: t.Number(), name: t.String({ minLength: 1 }) }),
|
|
162
164
|
response: t.Object({ success: t.Boolean() })
|
|
163
165
|
}, async ({ data }) => {
|
|
164
|
-
engineQueries.
|
|
166
|
+
engineQueries.renameAccount(data.id, data.name);
|
|
165
167
|
return { success: true };
|
|
166
168
|
})
|
|
167
169
|
|
|
@@ -258,7 +260,16 @@ export const accountsHandler = createRouter()
|
|
|
258
260
|
entry.phase = 'done';
|
|
259
261
|
debug.log('engine', `[${setupId}] Token captured`);
|
|
260
262
|
|
|
261
|
-
const
|
|
263
|
+
const provider = engineQueries.getProviderBySlug('claude-code', 'anthropic');
|
|
264
|
+
if (!provider) {
|
|
265
|
+
ws.emit.user(userId, 'engine:claude-account-setup-error', {
|
|
266
|
+
setupId,
|
|
267
|
+
message: 'Anthropic provider not found in DB'
|
|
268
|
+
});
|
|
269
|
+
cleanupSetup(setupId);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const account = engineQueries.createAccount(provider.id, entry.accountName, token);
|
|
262
273
|
resetEnvironment();
|
|
263
274
|
|
|
264
275
|
ws.emit.user(userId, 'engine:claude-account-setup-complete', {
|
|
@@ -303,7 +314,16 @@ export const accountsHandler = createRouter()
|
|
|
303
314
|
const token = extractOAuthToken(clean);
|
|
304
315
|
if (token) {
|
|
305
316
|
debug.log('engine', `[${setupId}] Token found in final buffer`);
|
|
306
|
-
const
|
|
317
|
+
const provider = engineQueries.getProviderBySlug('claude-code', 'anthropic');
|
|
318
|
+
if (!provider) {
|
|
319
|
+
ws.emit.user(userId, 'engine:claude-account-setup-error', {
|
|
320
|
+
setupId,
|
|
321
|
+
message: 'Anthropic provider not found in DB'
|
|
322
|
+
});
|
|
323
|
+
cleanupSetup(setupId);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const account = engineQueries.createAccount(provider.id, entry.accountName, token);
|
|
307
327
|
resetEnvironment();
|
|
308
328
|
ws.emit.user(userId, 'engine:claude-account-setup-complete', {
|
|
309
329
|
setupId,
|
|
@@ -31,8 +31,9 @@ export const claudeCodeStatusHandler = createRouter()
|
|
|
31
31
|
debug.log('engine', 'Checking Claude Code status...');
|
|
32
32
|
|
|
33
33
|
const { installed, version } = await getStatus('claude');
|
|
34
|
-
const
|
|
35
|
-
const
|
|
34
|
+
const provider = engineQueries.getProviderBySlug('claude-code', 'anthropic');
|
|
35
|
+
const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
|
|
36
|
+
const activeAccount = engineQueries.getActiveAccountForEngine('claude-code');
|
|
36
37
|
|
|
37
38
|
return {
|
|
38
39
|
installed,
|
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
import { createRouter } from '$shared/utils/ws-server';
|
|
8
8
|
import { openCodeStatusHandler } from './status';
|
|
9
|
+
import { openCodeProviderHandler } from './providers';
|
|
9
10
|
|
|
10
11
|
export const openCodeEngineRouter = createRouter()
|
|
11
|
-
.merge(openCodeStatusHandler)
|
|
12
|
+
.merge(openCodeStatusHandler)
|
|
13
|
+
.merge(openCodeProviderHandler);
|