@myrialabs/clopen 0.2.24 → 0.3.1
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/029_migrate_messages_to_unified.ts +1108 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/engine-queries.ts +195 -36
- package/backend/database/queries/index.ts +1 -2
- 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 +552 -0
- package/backend/engine/adapters/claude/stream.ts +59 -47
- package/backend/engine/adapters/opencode/config.ts +7 -7
- package/backend/engine/adapters/opencode/message-converter.ts +328 -352
- 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/providers.ts +25 -24
- 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-w7Uwi2Jz.js → index-BVWBZlgD.js} +2 -2
- package/dist/assets/main-Cgbs6dR7.js +246 -0
- package/dist/assets/main-TEa2MRnh.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 +130 -0
- package/shared/types/unified/message.ts +151 -0
- package/shared/types/unified/stream.ts +157 -0
- package/shared/types/unified/tool.ts +409 -0
- package/shared/utils/message-formatter.ts +9 -73
- package/shared/utils/path.ts +3 -2
- package/tsconfig.json +1 -1
- package/backend/database/queries/opencode-provider-queries.ts +0 -190
- package/backend/engine/adapters/claude/path-utils.ts +0 -38
- package/backend/ws/chat/background.ts +0 -201
- package/dist/assets/main-B4q8wX9B.js +0 -257
- package/dist/assets/main-Bfz5Urp3.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
|
@@ -9,15 +9,35 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { EventEmitter } from 'events';
|
|
12
|
-
import type {
|
|
12
|
+
import type {
|
|
13
|
+
EngineOutput,
|
|
14
|
+
UnifiedMessage,
|
|
15
|
+
UserMessage,
|
|
16
|
+
AssistantMessage,
|
|
17
|
+
ReasoningMessage,
|
|
18
|
+
CompactBoundaryMessage,
|
|
19
|
+
StreamEvent as UnifiedStreamEvent,
|
|
20
|
+
TextDeltaEvent,
|
|
21
|
+
StreamLifecycleEvent,
|
|
22
|
+
SuccessResultEvent,
|
|
23
|
+
ErrorResultEvent,
|
|
24
|
+
SystemInitEvent,
|
|
25
|
+
RateLimitEvent,
|
|
26
|
+
TokenUsage,
|
|
27
|
+
StopReason,
|
|
28
|
+
UserContentBlock,
|
|
29
|
+
StreamRequest,
|
|
30
|
+
} from '$shared/types/unified';
|
|
31
|
+
import type { EngineType } from '$shared/types/unified';
|
|
13
32
|
import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
14
|
-
import type { EngineType } from '$shared/types/engine';
|
|
15
33
|
import { getProjectEngine, initializeProjectEngine } from '../engine';
|
|
16
34
|
import { messageQueries, sessionQueries } from '../database/queries';
|
|
17
35
|
import { snapshotService } from '../snapshot/snapshot-service';
|
|
18
36
|
import { projectContextService } from '../mcp/project-context';
|
|
19
37
|
import { browserMcpControl } from '../preview';
|
|
38
|
+
import { extractMessageText } from '../snapshot/helpers';
|
|
20
39
|
import { debug } from '$shared/utils/logger';
|
|
40
|
+
import { DEFAULT_MODEL_ID, DEFAULT_MODEL_NAME } from '$shared/constants/engines';
|
|
21
41
|
|
|
22
42
|
// ============================================================================
|
|
23
43
|
// Types
|
|
@@ -33,31 +53,98 @@ export interface StreamState {
|
|
|
33
53
|
status: 'active' | 'completed' | 'error' | 'cancelled';
|
|
34
54
|
startedAt: Date;
|
|
35
55
|
completedAt?: Date;
|
|
36
|
-
messages:
|
|
37
|
-
currentMessage?:
|
|
56
|
+
messages: unknown[];
|
|
57
|
+
currentMessage?: UnifiedMessage;
|
|
38
58
|
currentPartialText?: string;
|
|
39
59
|
currentReasoningText?: string;
|
|
40
60
|
error?: string;
|
|
41
61
|
abortController?: AbortController;
|
|
42
62
|
streamPromise?: Promise<void>;
|
|
43
63
|
sdkSessionId?: string;
|
|
44
|
-
|
|
64
|
+
preStreamSessionId?: string | null;
|
|
45
65
|
hasCompactBoundary?: boolean;
|
|
46
|
-
eventSeq: number;
|
|
66
|
+
eventSeq: number;
|
|
47
67
|
}
|
|
48
68
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
// ============================================================================
|
|
70
|
+
// SDK → Unified Prompt Converter
|
|
71
|
+
// ============================================================================
|
|
72
|
+
|
|
73
|
+
/** Normalize raw UserMessage prompt from WS handler into a validated UserMessage */
|
|
74
|
+
function convertRawPromptToUserMessage(
|
|
75
|
+
rawPrompt: any,
|
|
76
|
+
senderId?: string,
|
|
77
|
+
senderName?: string,
|
|
78
|
+
): UserMessage {
|
|
79
|
+
const content: UserContentBlock[] = Array.isArray(rawPrompt?.content) && rawPrompt.content.length > 0
|
|
80
|
+
? rawPrompt.content as UserContentBlock[]
|
|
81
|
+
: [{ type: 'text', text: '' }];
|
|
82
|
+
|
|
83
|
+
// Build engine object from raw prompt
|
|
84
|
+
const rawEngine = rawPrompt?.engine;
|
|
85
|
+
const engineObj = rawEngine && typeof rawEngine === 'object'
|
|
86
|
+
? rawEngine
|
|
87
|
+
: {
|
|
88
|
+
type: rawEngine || 'claude-code',
|
|
89
|
+
provider: '',
|
|
90
|
+
model: {
|
|
91
|
+
id: rawPrompt?.model?.id ?? rawPrompt?.modelId ?? '',
|
|
92
|
+
name: rawPrompt?.model?.name ?? rawPrompt?.modelName ?? '',
|
|
93
|
+
},
|
|
94
|
+
account: { id: rawPrompt?.account?.id ?? 0, name: rawPrompt?.account?.name ?? '' },
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
type: 'user',
|
|
99
|
+
createdAt: rawPrompt?.createdAt || new Date().toISOString(),
|
|
100
|
+
messageId: rawPrompt?.messageId || rawPrompt?.id || crypto.randomUUID(),
|
|
101
|
+
sessionId: null, // User messages from the frontend have no SDK session ID
|
|
102
|
+
parent: {
|
|
103
|
+
messageId: rawPrompt?.parent?.messageId ?? rawPrompt?.parentMessageId ?? null,
|
|
104
|
+
sessionId: rawPrompt?.parent?.sessionId ?? rawPrompt?.parentSessionId ?? null,
|
|
105
|
+
toolUseId: rawPrompt?.parent?.toolUseId ?? rawPrompt?.parentToolUseId ?? null,
|
|
106
|
+
},
|
|
107
|
+
engine: engineObj,
|
|
108
|
+
sender: {
|
|
109
|
+
id: senderId || rawPrompt?.sender?.id || '',
|
|
110
|
+
name: senderName || rawPrompt?.sender?.name || '',
|
|
111
|
+
},
|
|
112
|
+
content,
|
|
113
|
+
synthetic: rawPrompt?.synthetic ?? false,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Request-level engine context injected into every SDK-emitted message */
|
|
118
|
+
interface RequestEngineContext {
|
|
119
|
+
accountId: number;
|
|
120
|
+
accountName: string;
|
|
121
|
+
modelName: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Enrich a message's engine block with request-level data that SDK adapters
|
|
126
|
+
* cannot know (display-name for the selected account and the human-readable
|
|
127
|
+
* model name). The adapter supplies type/provider/model.id; stream-manager
|
|
128
|
+
* is the single source of truth for the rest.
|
|
129
|
+
*/
|
|
130
|
+
function enrichMessageEngine(
|
|
131
|
+
message: UnifiedMessage,
|
|
132
|
+
ctx: RequestEngineContext,
|
|
133
|
+
): UnifiedMessage {
|
|
134
|
+
return {
|
|
135
|
+
...message,
|
|
136
|
+
engine: {
|
|
137
|
+
...message.engine,
|
|
138
|
+
model: {
|
|
139
|
+
...message.engine.model,
|
|
140
|
+
name: ctx.modelName || message.engine.model.name,
|
|
141
|
+
},
|
|
142
|
+
account: {
|
|
143
|
+
id: ctx.accountId || message.engine.account.id,
|
|
144
|
+
name: ctx.accountName || message.engine.account.name,
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
};
|
|
61
148
|
}
|
|
62
149
|
|
|
63
150
|
// ============================================================================
|
|
@@ -134,7 +221,7 @@ class StreamManager extends EventEmitter {
|
|
|
134
221
|
const existingStream = this.activeStreams.get(existingStreamId);
|
|
135
222
|
if (existingStream && existingStream.status === 'active') {
|
|
136
223
|
if (existingStream.projectId === request.projectId) {
|
|
137
|
-
if (
|
|
224
|
+
if (request.engine.type === 'claude-code') {
|
|
138
225
|
// Claude Code: cancel existing stream to prevent message loss from race condition.
|
|
139
226
|
// Claude Code SDK only returns session_id inside yielded messages, so a cancelled
|
|
140
227
|
// stream may never have established a valid session — safe to cancel and restart.
|
|
@@ -156,7 +243,7 @@ class StreamManager extends EventEmitter {
|
|
|
156
243
|
projectId: request.projectId,
|
|
157
244
|
projectPath: request.projectPath,
|
|
158
245
|
processId,
|
|
159
|
-
engine: request.engine
|
|
246
|
+
engine: request.engine.type,
|
|
160
247
|
status: 'active',
|
|
161
248
|
startedAt: new Date(),
|
|
162
249
|
messages: [],
|
|
@@ -170,14 +257,15 @@ class StreamManager extends EventEmitter {
|
|
|
170
257
|
// Save engine+model+account to session for persistence across refresh/switch
|
|
171
258
|
if (request.chatSessionId) {
|
|
172
259
|
try {
|
|
173
|
-
const compoundModelId = `${request.engine || 'claude-code'}:${request.model || 'sonnet'}`;
|
|
174
260
|
sessionQueries.updateEngineModel(
|
|
175
261
|
request.chatSessionId,
|
|
176
|
-
request.engine
|
|
177
|
-
|
|
262
|
+
request.engine.type,
|
|
263
|
+
request.engine.provider,
|
|
264
|
+
request.engine.model.id || DEFAULT_MODEL_ID,
|
|
265
|
+
request.engine.model.name || DEFAULT_MODEL_NAME
|
|
178
266
|
);
|
|
179
|
-
if (request.
|
|
180
|
-
sessionQueries.
|
|
267
|
+
if (request.engine.account.id) {
|
|
268
|
+
sessionQueries.updateAccount(request.chatSessionId, request.engine.account.id, request.engine.account.name || null);
|
|
181
269
|
}
|
|
182
270
|
} catch (error) {
|
|
183
271
|
debug.error('chat', 'Failed to save engine/model to session:', error);
|
|
@@ -228,7 +316,8 @@ class StreamManager extends EventEmitter {
|
|
|
228
316
|
// Increment sequence number for deduplication
|
|
229
317
|
streamState.eventSeq++;
|
|
230
318
|
|
|
231
|
-
// Attach engine type to
|
|
319
|
+
// Attach engine type string to event data for frontend routing metadata
|
|
320
|
+
// (stream-level metadata, distinct from message.engine which is the full MessageEngine object)
|
|
232
321
|
if (data && typeof data === 'object') {
|
|
233
322
|
data.engine = streamState.engine;
|
|
234
323
|
}
|
|
@@ -274,13 +363,11 @@ class StreamManager extends EventEmitter {
|
|
|
274
363
|
}
|
|
275
364
|
|
|
276
365
|
/**
|
|
277
|
-
* Process stream in background
|
|
366
|
+
* Process stream in background — routes EngineOutput events by type discriminant
|
|
278
367
|
*/
|
|
279
368
|
private async processStream(streamState: StreamState, requestData: StreamRequest): Promise<void> {
|
|
280
|
-
// Track user message ID for stream-end snapshot capture
|
|
281
369
|
let userMessageId: string | undefined;
|
|
282
370
|
|
|
283
|
-
// Initialize session baseline for snapshot system (non-blocking)
|
|
284
371
|
if (requestData.projectPath && requestData.chatSessionId) {
|
|
285
372
|
snapshotService.initializeSessionBaseline(
|
|
286
373
|
requestData.projectPath,
|
|
@@ -289,132 +376,124 @@ class StreamManager extends EventEmitter {
|
|
|
289
376
|
}
|
|
290
377
|
|
|
291
378
|
try {
|
|
292
|
-
const { projectPath, prompt, chatSessionId, engine:
|
|
379
|
+
const { projectPath, prompt: rawPrompt, chatSessionId, engine: requestEngine, sender: requestSender } = requestData;
|
|
293
380
|
|
|
294
|
-
//
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
const actualProjectPath = projectPath;
|
|
381
|
+
// Engine context that stream-manager injects into every SDK-emitted message.
|
|
382
|
+
// (SDK adapters cannot know these values; only the request layer can.)
|
|
383
|
+
const engineCtx: RequestEngineContext = {
|
|
384
|
+
accountId: requestEngine.account.id,
|
|
385
|
+
accountName: requestEngine.account.name,
|
|
386
|
+
modelName: requestEngine.model.name,
|
|
387
|
+
};
|
|
303
388
|
|
|
304
|
-
|
|
389
|
+
const projectPathExists = projectPath ? await this.existsSync(projectPath) : false;
|
|
390
|
+
if (!projectPath) throw new Error('Project path is required. Please select a valid project directory.');
|
|
391
|
+
if (!projectPathExists) throw new Error(`Project path does not exist: ${projectPath}. Please select a valid project directory.`);
|
|
392
|
+
|
|
393
|
+
// Get resume session ID (branch-aware).
|
|
394
|
+
// Primary: use parentSessionId carried by the UserMessage — set by the
|
|
395
|
+
// frontend from the last assistant/reasoning sessionId in the current branch.
|
|
396
|
+
// Fallback: walk the HEAD chain in the DB (handles messages sent from
|
|
397
|
+
// older clients or tool-result user messages that lack parentSessionId).
|
|
305
398
|
let resumeSessionId: string | undefined = undefined;
|
|
306
399
|
if (chatSessionId) {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
400
|
+
// Primary source: parent.sessionId on the raw prompt
|
|
401
|
+
const promptParentSessionId = rawPrompt?.parent?.sessionId;
|
|
402
|
+
if (promptParentSessionId && promptParentSessionId !== chatSessionId) {
|
|
403
|
+
resumeSessionId = promptParentSessionId;
|
|
404
|
+
} else {
|
|
405
|
+
// Fallback: walk HEAD chain
|
|
406
|
+
try {
|
|
407
|
+
const head = sessionQueries.getHead(chatSessionId);
|
|
408
|
+
if (head) {
|
|
409
|
+
const chain = messageQueries.getPathToRoot(head);
|
|
410
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
411
|
+
try {
|
|
412
|
+
const msg = JSON.parse(chain[i].data) as UnifiedMessage;
|
|
413
|
+
if (msg.type === 'user') continue;
|
|
414
|
+
if (msg.sessionId && msg.sessionId !== chatSessionId) {
|
|
415
|
+
resumeSessionId = msg.sessionId;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
} catch { /* skip unparseable blobs */ }
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
} catch (error) {
|
|
422
|
+
debug.error('chat', 'Failed to get resume session ID from HEAD chain:', error);
|
|
311
423
|
}
|
|
312
|
-
} catch (error) {
|
|
313
|
-
debug.error('chat', 'Failed to get chat session for resume:', error);
|
|
314
424
|
}
|
|
315
425
|
}
|
|
426
|
+
streamState.preStreamSessionId = resumeSessionId ?? null;
|
|
316
427
|
|
|
317
|
-
//
|
|
318
|
-
|
|
428
|
+
// Convert raw SDK prompt → UserMessage (unified)
|
|
429
|
+
const userMessage = convertRawPromptToUserMessage(rawPrompt, requestSender.id, requestSender.name);
|
|
319
430
|
|
|
320
|
-
//
|
|
321
|
-
const userMessage = {
|
|
322
|
-
...(prompt as SDKMessage),
|
|
323
|
-
resume: resumeSessionId ?? null
|
|
324
|
-
} as SDKMessage & { resume: string | null };
|
|
325
|
-
|
|
326
|
-
// Save user message
|
|
431
|
+
// Save user message to DB
|
|
327
432
|
const userMessageTimestamp = new Date().toISOString();
|
|
328
433
|
const savedMessage = await this.saveMessage(
|
|
329
|
-
userMessage
|
|
434
|
+
userMessage,
|
|
330
435
|
chatSessionId,
|
|
331
|
-
userMessageTimestamp
|
|
332
|
-
requestData.senderId,
|
|
333
|
-
requestData.senderName
|
|
436
|
+
userMessageTimestamp
|
|
334
437
|
);
|
|
335
|
-
|
|
336
|
-
// Track user message ID for stream-end snapshot
|
|
337
438
|
userMessageId = savedMessage?.id;
|
|
338
439
|
|
|
339
|
-
// Add user message to stream state and emit
|
|
340
|
-
// Keep SDK message clean — non-SDK info goes as transport fields
|
|
341
440
|
streamState.messages.push({
|
|
342
441
|
processId: streamState.processId,
|
|
343
|
-
message: userMessage,
|
|
442
|
+
message: userMessage as any,
|
|
344
443
|
timestamp: userMessageTimestamp,
|
|
345
444
|
message_id: savedMessage?.id,
|
|
346
445
|
parent_message_id: savedMessage?.parent_message_id || null,
|
|
347
|
-
sender_id:
|
|
348
|
-
sender_name:
|
|
446
|
+
sender_id: requestSender.id,
|
|
447
|
+
sender_name: requestSender.name
|
|
349
448
|
});
|
|
350
449
|
|
|
351
|
-
// Emit user message event
|
|
352
450
|
this.emitStreamEvent(streamState, 'message', {
|
|
353
451
|
processId: streamState.processId,
|
|
354
452
|
message: userMessage,
|
|
355
453
|
timestamp: userMessageTimestamp,
|
|
356
454
|
message_id: savedMessage?.id,
|
|
357
455
|
parent_message_id: savedMessage?.parent_message_id || null,
|
|
358
|
-
sender_id:
|
|
359
|
-
sender_name:
|
|
456
|
+
sender_id: requestSender.id,
|
|
457
|
+
sender_name: requestSender.name
|
|
360
458
|
});
|
|
361
459
|
|
|
362
|
-
// Check for cancellation after saving user message (async DB operation)
|
|
363
460
|
if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
|
|
364
461
|
debug.log('chat', 'Stream cancelled after saving user message, skipping query');
|
|
365
462
|
return;
|
|
366
463
|
}
|
|
367
464
|
|
|
368
|
-
let sdkSessionId: string |
|
|
369
|
-
// Track last assistant text for deduplication — some engines (Claude Code) can
|
|
370
|
-
// emit identical error messages multiple times (e.g. on process exit retry).
|
|
465
|
+
let sdkSessionId: string | undefined;
|
|
371
466
|
let lastAssistantTextContent: string | null = null;
|
|
372
|
-
|
|
373
|
-
// Get per-project engine instance for stream isolation.
|
|
374
|
-
// Each project gets its own engine so cancel/abort only affects this project.
|
|
375
467
|
const projectId = streamState.projectId || 'default';
|
|
376
468
|
|
|
377
|
-
// Check if already cancelled BEFORE initializing the engine.
|
|
378
|
-
// This prevents starting a new engine query with an already-aborted controller,
|
|
379
|
-
// which can cause unhandled rejections in the SDK and crash the server.
|
|
380
|
-
// Note: status is mutated to 'cancelled' by cancelStream() from a different async context;
|
|
381
|
-
// TypeScript's control flow analysis doesn't track this, so we cast to string.
|
|
382
469
|
if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
|
|
383
470
|
debug.log('chat', 'Stream cancelled before engine initialization, skipping query');
|
|
384
471
|
return;
|
|
385
472
|
}
|
|
386
473
|
|
|
387
|
-
const engine = await initializeProjectEngine(projectId,
|
|
474
|
+
const engine = await initializeProjectEngine(projectId, requestEngine.type);
|
|
388
475
|
|
|
389
|
-
// Check again after async engine initialization — cancellation may have occurred
|
|
390
|
-
// while awaiting initialization
|
|
391
476
|
if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
|
|
392
477
|
debug.log('chat', 'Stream cancelled during engine initialization, skipping query');
|
|
393
478
|
return;
|
|
394
479
|
}
|
|
395
480
|
|
|
396
|
-
// Detect orphaned user messages and prepend context (claude-code only)
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
// We prepend those orphaned messages as context so the AI has full history.
|
|
400
|
-
let enginePrompt = prompt;
|
|
401
|
-
if (engineType === 'claude-code' && chatSessionId) {
|
|
481
|
+
// Detect orphaned user messages and prepend context (claude-code only)
|
|
482
|
+
let enginePrompt = userMessage;
|
|
483
|
+
if (requestEngine.type === 'claude-code' && chatSessionId) {
|
|
402
484
|
try {
|
|
403
485
|
const head = sessionQueries.getHead(chatSessionId);
|
|
404
486
|
if (head) {
|
|
405
487
|
const chain = messageQueries.getPathToRoot(head);
|
|
406
|
-
// Remove the current user message (last in chain, just saved)
|
|
407
488
|
const previousChain = chain.slice(0, -1);
|
|
408
489
|
|
|
409
490
|
if (previousChain.length > 0) {
|
|
410
|
-
// Find boundary: last message with session_id matching resumeSessionId
|
|
411
491
|
let boundaryIndex = -1;
|
|
412
|
-
|
|
413
492
|
if (resumeSessionId) {
|
|
414
493
|
for (let i = previousChain.length - 1; i >= 0; i--) {
|
|
415
494
|
try {
|
|
416
|
-
const
|
|
417
|
-
if (
|
|
495
|
+
const msg = JSON.parse(previousChain[i].data) as UnifiedMessage;
|
|
496
|
+
if (msg.sessionId === resumeSessionId) {
|
|
418
497
|
boundaryIndex = i;
|
|
419
498
|
break;
|
|
420
499
|
}
|
|
@@ -422,33 +501,22 @@ class StreamManager extends EventEmitter {
|
|
|
422
501
|
}
|
|
423
502
|
}
|
|
424
503
|
|
|
425
|
-
// Collect orphaned user messages after boundary
|
|
426
504
|
const orphanedUserTexts: string[] = [];
|
|
427
505
|
for (let i = boundaryIndex + 1; i < previousChain.length; i++) {
|
|
428
506
|
try {
|
|
429
|
-
const
|
|
430
|
-
if (
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
text = content;
|
|
435
|
-
} else if (Array.isArray(content)) {
|
|
436
|
-
text = content
|
|
437
|
-
.filter((block: any) => block.type === 'text')
|
|
438
|
-
.map((block: any) => block.text)
|
|
507
|
+
const msg = JSON.parse(previousChain[i].data) as UnifiedMessage;
|
|
508
|
+
if (msg.type === 'user') {
|
|
509
|
+
const text = msg.content
|
|
510
|
+
.filter(block => block.type === 'text')
|
|
511
|
+
.map(block => block.text)
|
|
439
512
|
.join('\n');
|
|
440
|
-
|
|
441
|
-
if (text.trim()) {
|
|
442
|
-
orphanedUserTexts.push(text.trim());
|
|
443
|
-
}
|
|
513
|
+
if (text.trim()) orphanedUserTexts.push(text.trim());
|
|
444
514
|
}
|
|
445
515
|
} catch { /* skip unparseable */ }
|
|
446
516
|
}
|
|
447
517
|
|
|
448
|
-
// Prepend context if there are orphaned messages
|
|
449
518
|
if (orphanedUserTexts.length > 0) {
|
|
450
519
|
debug.log('chat', `Prepending ${orphanedUserTexts.length} orphaned user message(s) as context`);
|
|
451
|
-
|
|
452
520
|
const contextPrefix = [
|
|
453
521
|
'[Previous unprocessed messages from the user:]',
|
|
454
522
|
...orphanedUserTexts.map((text, i) => `${i + 1}. "${text}"`),
|
|
@@ -456,27 +524,13 @@ class StreamManager extends EventEmitter {
|
|
|
456
524
|
'[Current message:]'
|
|
457
525
|
].join('\n');
|
|
458
526
|
|
|
459
|
-
const originalContent = prompt.message.content;
|
|
460
|
-
let modifiedContent: typeof originalContent;
|
|
461
|
-
|
|
462
|
-
if (typeof originalContent === 'string') {
|
|
463
|
-
modifiedContent = contextPrefix + '\n' + originalContent;
|
|
464
|
-
} else if (Array.isArray(originalContent)) {
|
|
465
|
-
modifiedContent = [
|
|
466
|
-
{ type: 'text' as const, text: contextPrefix },
|
|
467
|
-
...originalContent
|
|
468
|
-
];
|
|
469
|
-
} else {
|
|
470
|
-
modifiedContent = originalContent;
|
|
471
|
-
}
|
|
472
|
-
|
|
473
527
|
enginePrompt = {
|
|
474
|
-
...
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
content
|
|
478
|
-
|
|
479
|
-
}
|
|
528
|
+
...userMessage,
|
|
529
|
+
content: [
|
|
530
|
+
{ type: 'text' as const, text: contextPrefix },
|
|
531
|
+
...userMessage.content,
|
|
532
|
+
],
|
|
533
|
+
};
|
|
480
534
|
}
|
|
481
535
|
}
|
|
482
536
|
}
|
|
@@ -485,16 +539,16 @@ class StreamManager extends EventEmitter {
|
|
|
485
539
|
}
|
|
486
540
|
}
|
|
487
541
|
|
|
488
|
-
// Stream
|
|
489
|
-
// Wrap in execution context so MCP tool handlers can access chatSessionId/projectId
|
|
542
|
+
// Stream EngineOutput events through the engine adapter
|
|
490
543
|
const streamIterable = engine.streamQuery({
|
|
491
|
-
projectPath
|
|
544
|
+
projectPath,
|
|
492
545
|
prompt: enginePrompt,
|
|
493
546
|
resume: resumeSessionId,
|
|
494
|
-
|
|
547
|
+
providerSlug: requestEngine.provider,
|
|
548
|
+
modelId: requestEngine.model.id,
|
|
495
549
|
includePartialMessages: true,
|
|
496
550
|
abortController: streamState.abortController,
|
|
497
|
-
...(
|
|
551
|
+
...(requestEngine.account.id !== 0 && { accountId: requestEngine.account.id }),
|
|
498
552
|
...(projectId && chatSessionId && {
|
|
499
553
|
mcpContext: { projectId, chatSessionId, streamId: streamState.streamId }
|
|
500
554
|
}),
|
|
@@ -502,126 +556,97 @@ class StreamManager extends EventEmitter {
|
|
|
502
556
|
|
|
503
557
|
await projectContextService.runWithContextAsync(
|
|
504
558
|
{ chatSessionId, projectId, streamId: streamState.streamId },
|
|
505
|
-
async () => { for await (const
|
|
506
|
-
// Check if cancelled (cancelStream() already set status and emitted event)
|
|
559
|
+
async () => { for await (const output of streamIterable) {
|
|
507
560
|
if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
|
|
508
561
|
break;
|
|
509
562
|
}
|
|
510
563
|
|
|
511
|
-
//
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
564
|
+
// ── Route by type discriminant ──────────────────────────────
|
|
565
|
+
|
|
566
|
+
// Extract session ID from first event that has one
|
|
567
|
+
if (!sdkSessionId) {
|
|
568
|
+
const eventSessionId = 'sessionId' in output ? (output as any).sessionId : null;
|
|
569
|
+
if (eventSessionId) {
|
|
570
|
+
sdkSessionId = eventSessionId;
|
|
571
|
+
streamState.sdkSessionId = sdkSessionId;
|
|
572
|
+
if (chatSessionId) {
|
|
573
|
+
try { sessionQueries.updateSessionId(chatSessionId, sdkSessionId!); }
|
|
574
|
+
catch { /* ignore */ }
|
|
520
575
|
}
|
|
521
576
|
}
|
|
522
577
|
}
|
|
523
578
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
// Check for failed MCP servers
|
|
531
|
-
if (systemMessage.mcp_servers && Array.isArray(systemMessage.mcp_servers)) {
|
|
532
|
-
const failedServers = systemMessage.mcp_servers.filter(
|
|
533
|
-
(server: any) => server.status !== 'connected'
|
|
534
|
-
);
|
|
535
|
-
|
|
536
|
-
// Emit warning notification for each failed server
|
|
537
|
-
failedServers.forEach((server: any) => {
|
|
579
|
+
switch (output.type) {
|
|
580
|
+
// ── System Init ────────────────────────────────────────
|
|
581
|
+
case 'system_init': {
|
|
582
|
+
const initEvent = output as SystemInitEvent;
|
|
583
|
+
const failedServers = initEvent.mcpServers.filter(s => s.status !== 'connected');
|
|
584
|
+
failedServers.forEach(server => {
|
|
538
585
|
debug.warn('mcp', `MCP server connection failed: ${server.name} (${server.status})`);
|
|
539
|
-
|
|
540
586
|
this.emitStreamEvent(streamState, 'notification', {
|
|
541
587
|
notification: {
|
|
542
588
|
type: 'warning',
|
|
543
589
|
title: 'MCP Server Connection Failed',
|
|
544
590
|
message: `Failed to connect to custom MCP server "${server.name}". Status: ${server.status}`,
|
|
545
|
-
icon: 'lucide:alert-triangle'
|
|
546
591
|
},
|
|
547
592
|
timestamp: new Date().toISOString()
|
|
548
593
|
});
|
|
549
594
|
});
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
(server: any) => server.status === 'connected'
|
|
554
|
-
);
|
|
555
|
-
if (connectedServers.length > 0) {
|
|
556
|
-
debug.log('mcp', `✓ Connected MCP servers: ${connectedServers.map((s: any) => s.name).join(', ')}`);
|
|
595
|
+
const connected = initEvent.mcpServers.filter(s => s.status === 'connected');
|
|
596
|
+
if (connected.length > 0) {
|
|
597
|
+
debug.log('mcp', `✓ Connected MCP servers: ${connected.map(s => s.name).join(', ')}`);
|
|
557
598
|
}
|
|
599
|
+
continue; // Don't save to DB
|
|
558
600
|
}
|
|
559
601
|
|
|
560
|
-
//
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
if (message.type === 'system' && message.subtype === 'compact_boundary') {
|
|
566
|
-
const compactMessage = message as SDKCompactBoundaryMessage;
|
|
567
|
-
streamState.hasCompactBoundary = true;
|
|
568
|
-
const compactTimestamp = new Date().toISOString();
|
|
569
|
-
|
|
570
|
-
// Save to DB so compact boundary persists across refresh
|
|
571
|
-
let savedCompactId: string | undefined;
|
|
572
|
-
let savedCompactParentId: string | null = null;
|
|
573
|
-
if (chatSessionId) {
|
|
574
|
-
const saved = await this.saveMessage(
|
|
575
|
-
message,
|
|
576
|
-
chatSessionId,
|
|
577
|
-
compactTimestamp,
|
|
578
|
-
requestData.senderId,
|
|
579
|
-
requestData.senderName
|
|
580
|
-
);
|
|
581
|
-
savedCompactId = saved?.id;
|
|
582
|
-
savedCompactParentId = saved?.parent_message_id || null;
|
|
583
|
-
}
|
|
602
|
+
// ── Compact Boundary ───────────────────────────────────
|
|
603
|
+
case 'compact_boundary': {
|
|
604
|
+
const boundary = enrichMessageEngine(output, engineCtx) as CompactBoundaryMessage;
|
|
605
|
+
streamState.hasCompactBoundary = true;
|
|
606
|
+
const compactTimestamp = boundary.createdAt;
|
|
584
607
|
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
608
|
+
let savedCompactId: string | undefined;
|
|
609
|
+
let savedCompactParentId: string | null = null;
|
|
610
|
+
if (chatSessionId) {
|
|
611
|
+
const saved = await this.saveMessage(
|
|
612
|
+
boundary,
|
|
613
|
+
chatSessionId,
|
|
614
|
+
compactTimestamp
|
|
615
|
+
);
|
|
616
|
+
savedCompactId = saved?.id;
|
|
617
|
+
savedCompactParentId = saved?.parent_message_id || null;
|
|
594
618
|
}
|
|
595
|
-
});
|
|
596
|
-
|
|
597
|
-
// Emit as chat:message so it shows in the chat UI
|
|
598
|
-
this.emitStreamEvent(streamState, 'message', {
|
|
599
|
-
processId: streamState.processId,
|
|
600
|
-
message,
|
|
601
|
-
timestamp: compactTimestamp,
|
|
602
|
-
message_id: savedCompactId,
|
|
603
|
-
parent_message_id: savedCompactParentId,
|
|
604
|
-
sender_id: requestData.senderId,
|
|
605
|
-
sender_name: requestData.senderName
|
|
606
|
-
});
|
|
607
|
-
|
|
608
|
-
continue;
|
|
609
|
-
}
|
|
610
619
|
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
620
|
+
streamState.messages.push({
|
|
621
|
+
processId: streamState.processId,
|
|
622
|
+
message: boundary as any,
|
|
623
|
+
timestamp: compactTimestamp,
|
|
624
|
+
message_id: savedCompactId,
|
|
625
|
+
parent_message_id: savedCompactParentId,
|
|
626
|
+
compactBoundary: {
|
|
627
|
+
trigger: boundary.trigger,
|
|
628
|
+
preTokens: boundary.preTokens
|
|
629
|
+
}
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
this.emitStreamEvent(streamState, 'message', {
|
|
633
|
+
processId: streamState.processId,
|
|
634
|
+
message: boundary,
|
|
635
|
+
timestamp: compactTimestamp,
|
|
636
|
+
message_id: savedCompactId,
|
|
637
|
+
parent_message_id: savedCompactParentId,
|
|
638
|
+
sender_id: requestSender.id,
|
|
639
|
+
sender_name: requestSender.name
|
|
640
|
+
});
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// ── Rate Limit ─────────────────────────────────────────
|
|
645
|
+
case 'rate_limit': {
|
|
646
|
+
const rl = output as RateLimitEvent;
|
|
647
|
+
const isRejected = rl.status === 'rejected';
|
|
648
|
+
const resetTime = rl.resetsAt
|
|
649
|
+
? new Date(rl.resetsAt * 1000).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })
|
|
625
650
|
: 'unknown';
|
|
626
651
|
this.emitStreamEvent(streamState, 'notification', {
|
|
627
652
|
notification: {
|
|
@@ -629,317 +654,249 @@ class StreamManager extends EventEmitter {
|
|
|
629
654
|
title: isRejected ? 'Rate Limit Reached' : 'Rate Limit Warning',
|
|
630
655
|
message: isRejected
|
|
631
656
|
? `Rate limit exceeded. Resets at ${resetTime}.`
|
|
632
|
-
: `Approaching rate limit (${Math.round((
|
|
633
|
-
icon: isRejected ? 'lucide:ban' : 'lucide:alert-triangle'
|
|
657
|
+
: `Approaching rate limit (${Math.round((rl.utilization || 0) * 100)}% used). Resets at ${resetTime}.`,
|
|
634
658
|
},
|
|
635
659
|
timestamp: new Date().toISOString()
|
|
636
660
|
});
|
|
637
|
-
}
|
|
638
|
-
continue;
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
// Handle result messages — extract useful info, don't save to DB
|
|
642
|
-
if (message.type === 'result') {
|
|
643
|
-
const resultMsg = message as any;
|
|
644
|
-
if (resultMsg.subtype !== 'success' && resultMsg.errors?.length) {
|
|
645
|
-
debug.warn('chat', `SDK result error: ${resultMsg.subtype}`, resultMsg.errors);
|
|
646
|
-
}
|
|
647
|
-
continue;
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
// Skip all other system subtypes that aren't conversation content
|
|
651
|
-
// (init and compact_boundary are already handled above)
|
|
652
|
-
if (message.type === 'system') {
|
|
653
|
-
const subtype = (message as any).subtype;
|
|
654
|
-
// Compact boundary is handled above — this catches remaining subtypes:
|
|
655
|
-
// status, hook_started, hook_progress, hook_response,
|
|
656
|
-
// task_notification, task_started, task_progress,
|
|
657
|
-
// files_persisted, elicitation_complete, local_command_output
|
|
658
|
-
if (subtype !== 'compact_boundary') {
|
|
659
|
-
debug.log('chat', `[SM] Skipping system message subtype: ${subtype}`);
|
|
660
661
|
continue;
|
|
661
662
|
}
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// Skip transient metadata events (not conversation content)
|
|
665
|
-
if (
|
|
666
|
-
message.type === 'tool_progress' ||
|
|
667
|
-
message.type === 'auth_status' ||
|
|
668
|
-
message.type === 'tool_use_summary' ||
|
|
669
|
-
message.type === 'prompt_suggestion'
|
|
670
|
-
) {
|
|
671
|
-
debug.log('chat', `[SM] Skipping transient message type: ${message.type}`);
|
|
672
|
-
continue;
|
|
673
|
-
}
|
|
674
663
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
664
|
+
// ── Result ─────────────────────────────────────────────
|
|
665
|
+
case 'result': {
|
|
666
|
+
if (output.subtype === 'success') {
|
|
667
|
+
const successResult = output as SuccessResultEvent;
|
|
668
|
+
// Backfill stopReason to last assistant message if SDK left it null
|
|
669
|
+
if (successResult.stopReason && chatSessionId) {
|
|
670
|
+
const mapped = this.backfillStopReason(chatSessionId, successResult.stopReason);
|
|
671
|
+
// Re-emit patched assistant message so frontend updates live data
|
|
672
|
+
if (mapped && streamState.currentMessage?.type === 'assistant' && !streamState.currentMessage.stopReason) {
|
|
673
|
+
const patched = { ...streamState.currentMessage, stopReason: mapped } as AssistantMessage;
|
|
674
|
+
streamState.currentMessage = patched;
|
|
675
|
+
// Find the saved message ID from the last emitted assistant
|
|
676
|
+
const lastEntry = [...streamState.messages].reverse()
|
|
677
|
+
.find((m: any) => m.message?.type === 'assistant') as any;
|
|
678
|
+
this.emitStreamEvent(streamState, 'message', {
|
|
679
|
+
processId: streamState.processId,
|
|
680
|
+
message: patched,
|
|
681
|
+
timestamp: patched.createdAt,
|
|
682
|
+
message_id: lastEntry?.message_id ?? undefined,
|
|
683
|
+
parent_message_id: lastEntry?.parent_message_id ?? null,
|
|
684
|
+
sender_id: requestSender.id,
|
|
685
|
+
sender_name: requestSender.name
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
}
|
|
688
689
|
} else {
|
|
689
|
-
|
|
690
|
+
const errResult = output as ErrorResultEvent;
|
|
691
|
+
if (errResult.errors?.length) {
|
|
692
|
+
debug.warn('chat', `SDK result error: ${errResult.subtype}`, errResult.errors);
|
|
693
|
+
}
|
|
690
694
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
processId: streamState.processId,
|
|
706
|
-
eventType: 'start',
|
|
707
|
-
partialText: '',
|
|
708
|
-
deltaText: '',
|
|
709
|
-
reasoning: true,
|
|
710
|
-
timestamp: new Date().toISOString()
|
|
711
|
-
});
|
|
712
|
-
} else if ((event as any).content_block?.type === 'text') {
|
|
713
|
-
// Reset partial text for new text content block
|
|
714
|
-
streamState.currentPartialText = '';
|
|
715
|
-
// Emit a start event so frontend has a text stream_event
|
|
716
|
-
// before deltas arrive (matches thinking block behavior)
|
|
695
|
+
continue; // Don't save to DB
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// ── Stream Events (deltas, start/stop) ────────────────
|
|
699
|
+
case 'stream_event': {
|
|
700
|
+
const streamEvt = output as UnifiedStreamEvent;
|
|
701
|
+
|
|
702
|
+
if (streamEvt.event === 'start') {
|
|
703
|
+
const lifecycle = streamEvt as StreamLifecycleEvent;
|
|
704
|
+
if (lifecycle.reasoning) {
|
|
705
|
+
streamState.currentReasoningText = '';
|
|
706
|
+
} else {
|
|
707
|
+
streamState.currentPartialText = '';
|
|
708
|
+
}
|
|
717
709
|
this.emitStreamEvent(streamState, 'partial', {
|
|
718
710
|
processId: streamState.processId,
|
|
719
711
|
eventType: 'start',
|
|
720
712
|
partialText: '',
|
|
721
713
|
deltaText: '',
|
|
714
|
+
...(lifecycle.reasoning && { reasoning: true }),
|
|
722
715
|
timestamp: new Date().toISOString()
|
|
723
716
|
});
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
if (event.delta && 'thinking' in (event.delta as any)) {
|
|
729
|
-
const thinkingText = (event.delta as any).thinking;
|
|
730
|
-
streamState.currentReasoningText = (streamState.currentReasoningText || '') + thinkingText;
|
|
731
|
-
this.emitStreamEvent(streamState, 'partial', {
|
|
732
|
-
processId: streamState.processId,
|
|
733
|
-
eventType: 'update',
|
|
734
|
-
partialText: streamState.currentReasoningText,
|
|
735
|
-
deltaText: thinkingText,
|
|
736
|
-
reasoning: true,
|
|
737
|
-
timestamp: new Date().toISOString()
|
|
738
|
-
});
|
|
739
|
-
} else if (event.delta && 'text' in event.delta) {
|
|
740
|
-
if (isReasoning) {
|
|
741
|
-
// Open Code: reasoning delta (packaged as text_delta with metadata.reasoning flag)
|
|
742
|
-
const deltaText = event.delta.text;
|
|
743
|
-
streamState.currentReasoningText = (streamState.currentReasoningText || '') + deltaText;
|
|
717
|
+
} else if (streamEvt.event === 'delta') {
|
|
718
|
+
const delta = streamEvt as TextDeltaEvent;
|
|
719
|
+
if (delta.reasoning) {
|
|
720
|
+
streamState.currentReasoningText = (streamState.currentReasoningText || '') + delta.text;
|
|
744
721
|
this.emitStreamEvent(streamState, 'partial', {
|
|
745
722
|
processId: streamState.processId,
|
|
746
723
|
eventType: 'update',
|
|
747
724
|
partialText: streamState.currentReasoningText,
|
|
748
|
-
deltaText:
|
|
725
|
+
deltaText: delta.text,
|
|
749
726
|
reasoning: true,
|
|
750
727
|
timestamp: new Date().toISOString()
|
|
751
728
|
});
|
|
752
729
|
} else {
|
|
753
|
-
|
|
754
|
-
const deltaText = event.delta.text;
|
|
755
|
-
streamState.currentPartialText = (streamState.currentPartialText || '') + deltaText;
|
|
730
|
+
streamState.currentPartialText = (streamState.currentPartialText || '') + delta.text;
|
|
756
731
|
this.emitStreamEvent(streamState, 'partial', {
|
|
757
732
|
processId: streamState.processId,
|
|
758
733
|
eventType: 'update',
|
|
759
734
|
partialText: streamState.currentPartialText,
|
|
760
|
-
deltaText:
|
|
735
|
+
deltaText: delta.text,
|
|
736
|
+
timestamp: new Date().toISOString()
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
} else if (streamEvt.event === 'stop') {
|
|
740
|
+
const lifecycle = streamEvt as StreamLifecycleEvent;
|
|
741
|
+
if (lifecycle.reasoning && streamState.currentReasoningText) {
|
|
742
|
+
this.emitStreamEvent(streamState, 'partial', {
|
|
743
|
+
processId: streamState.processId,
|
|
744
|
+
eventType: 'end',
|
|
745
|
+
partialText: streamState.currentReasoningText,
|
|
746
|
+
deltaText: '',
|
|
747
|
+
reasoning: true,
|
|
748
|
+
timestamp: new Date().toISOString()
|
|
749
|
+
});
|
|
750
|
+
streamState.currentReasoningText = '';
|
|
751
|
+
} else {
|
|
752
|
+
this.emitStreamEvent(streamState, 'partial', {
|
|
753
|
+
processId: streamState.processId,
|
|
754
|
+
eventType: 'end',
|
|
755
|
+
partialText: streamState.currentPartialText || '',
|
|
756
|
+
deltaText: '',
|
|
761
757
|
timestamp: new Date().toISOString()
|
|
762
758
|
});
|
|
763
759
|
}
|
|
764
760
|
}
|
|
765
|
-
|
|
766
|
-
// Claude Code: end of a thinking block — emit reasoning end and clear state
|
|
767
|
-
if (streamState.currentReasoningText) {
|
|
768
|
-
this.emitStreamEvent(streamState, 'partial', {
|
|
769
|
-
processId: streamState.processId,
|
|
770
|
-
eventType: 'end',
|
|
771
|
-
partialText: streamState.currentReasoningText,
|
|
772
|
-
deltaText: '',
|
|
773
|
-
reasoning: true,
|
|
774
|
-
timestamp: new Date().toISOString()
|
|
775
|
-
});
|
|
776
|
-
// Clear so subsequent content_block_stop (text/tool) doesn't re-trigger
|
|
777
|
-
streamState.currentReasoningText = '';
|
|
778
|
-
}
|
|
779
|
-
} else if (event.type === 'message_stop') {
|
|
780
|
-
if (isReasoning) {
|
|
781
|
-
this.emitStreamEvent(streamState, 'partial', {
|
|
782
|
-
processId: streamState.processId,
|
|
783
|
-
eventType: 'end',
|
|
784
|
-
partialText: streamState.currentReasoningText || '',
|
|
785
|
-
deltaText: '',
|
|
786
|
-
reasoning: true,
|
|
787
|
-
timestamp: new Date().toISOString()
|
|
788
|
-
});
|
|
789
|
-
} else {
|
|
790
|
-
this.emitStreamEvent(streamState, 'partial', {
|
|
791
|
-
processId: streamState.processId,
|
|
792
|
-
eventType: 'end',
|
|
793
|
-
partialText: streamState.currentPartialText || '',
|
|
794
|
-
deltaText: '',
|
|
795
|
-
timestamp: new Date().toISOString()
|
|
796
|
-
});
|
|
797
|
-
}
|
|
761
|
+
continue;
|
|
798
762
|
}
|
|
799
|
-
continue;
|
|
800
|
-
}
|
|
801
763
|
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
const content = (message as any).message.content;
|
|
807
|
-
const contentTypes = content.map((b: any) => b.type);
|
|
808
|
-
debug.log('chat', `[SM] assistant message content types: ${JSON.stringify(contentTypes)}`);
|
|
809
|
-
const thinkingBlocks = content.filter((b: any) => b.type === 'thinking');
|
|
810
|
-
|
|
811
|
-
if (thinkingBlocks.length > 0) {
|
|
812
|
-
const reasoningText = thinkingBlocks
|
|
813
|
-
.map((b: any) => b.thinking || '')
|
|
814
|
-
.join('\n');
|
|
815
|
-
const otherBlocks = content.filter((b: any) => b.type !== 'thinking');
|
|
816
|
-
|
|
817
|
-
// 1. Emit reasoning message
|
|
818
|
-
// Synthetic reasoning message — extracted thinking blocks as text
|
|
819
|
-
const reasoningMsg = {
|
|
820
|
-
type: 'assistant' as const,
|
|
821
|
-
message: {
|
|
822
|
-
...message.message,
|
|
823
|
-
content: [{ type: 'text' as const, text: reasoningText }],
|
|
824
|
-
},
|
|
825
|
-
uuid: crypto.randomUUID(),
|
|
826
|
-
session_id: message.session_id,
|
|
827
|
-
parent_tool_use_id: null,
|
|
828
|
-
metadata: { reasoning: true },
|
|
829
|
-
} as unknown as EngineSDKMessage;
|
|
764
|
+
// ── Reasoning Message ──────────────────────────────────
|
|
765
|
+
case 'reasoning': {
|
|
766
|
+
const reasoning = enrichMessageEngine(output, engineCtx) as ReasoningMessage;
|
|
767
|
+
streamState.currentReasoningText = undefined;
|
|
830
768
|
|
|
831
|
-
const reasoningTimestamp =
|
|
769
|
+
const reasoningTimestamp = reasoning.createdAt;
|
|
832
770
|
let savedReasoningId: string | undefined;
|
|
833
771
|
let savedReasoningParentId: string | null = null;
|
|
834
772
|
if (chatSessionId) {
|
|
835
773
|
const saved = await this.saveMessage(
|
|
836
|
-
|
|
837
|
-
|
|
774
|
+
reasoning,
|
|
775
|
+
chatSessionId,
|
|
776
|
+
reasoningTimestamp
|
|
838
777
|
);
|
|
839
778
|
savedReasoningId = saved?.id;
|
|
840
779
|
savedReasoningParentId = saved?.parent_message_id || null;
|
|
841
780
|
}
|
|
842
781
|
|
|
843
|
-
// Clear reasoning text after save to prevent stale catchup injection
|
|
844
|
-
streamState.currentReasoningText = undefined;
|
|
845
|
-
|
|
846
782
|
this.emitStreamEvent(streamState, 'message', {
|
|
847
783
|
processId: streamState.processId,
|
|
848
|
-
message:
|
|
784
|
+
message: reasoning,
|
|
849
785
|
timestamp: reasoningTimestamp,
|
|
850
786
|
message_id: savedReasoningId,
|
|
851
787
|
parent_message_id: savedReasoningParentId,
|
|
852
|
-
sender_id:
|
|
853
|
-
sender_name:
|
|
788
|
+
sender_id: requestSender.id,
|
|
789
|
+
sender_name: requestSender.name
|
|
854
790
|
});
|
|
855
|
-
|
|
856
|
-
// 2. Strip thinking blocks from original message
|
|
857
|
-
(message as any).message.content = otherBlocks.length > 0
|
|
858
|
-
? otherBlocks
|
|
859
|
-
: [{ type: 'text', text: '' }];
|
|
791
|
+
continue;
|
|
860
792
|
}
|
|
861
|
-
}
|
|
862
793
|
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
.
|
|
871
|
-
.map((c: any) => c.text as string)
|
|
794
|
+
// ── Assistant Message ──────────────────────────────────
|
|
795
|
+
case 'assistant': {
|
|
796
|
+
const assistantMsg = enrichMessageEngine(output, engineCtx) as AssistantMessage;
|
|
797
|
+
|
|
798
|
+
// Deduplicate consecutive identical assistant messages
|
|
799
|
+
const currentText = assistantMsg.content
|
|
800
|
+
.filter(c => c.type === 'text')
|
|
801
|
+
.map(c => (c as any).text as string)
|
|
872
802
|
.join('');
|
|
873
803
|
if (currentText && currentText === lastAssistantTextContent) {
|
|
874
804
|
debug.warn('chat', 'Skipping duplicate consecutive assistant message');
|
|
875
805
|
continue;
|
|
876
806
|
}
|
|
877
807
|
if (currentText) lastAssistantTextContent = currentText;
|
|
878
|
-
}
|
|
879
|
-
} else if (message.type !== 'assistant') {
|
|
880
|
-
// Reset tracker on non-assistant messages (user/system/tool result)
|
|
881
|
-
lastAssistantTextContent = null;
|
|
882
|
-
}
|
|
883
808
|
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
? message.message.usage
|
|
887
|
-
: undefined;
|
|
809
|
+
const usage = assistantMsg.usage;
|
|
810
|
+
const messageTimestamp = assistantMsg.createdAt;
|
|
888
811
|
|
|
889
|
-
|
|
812
|
+
let savedMsgId: string | undefined;
|
|
813
|
+
let savedParentId: string | null = null;
|
|
814
|
+
if (chatSessionId) {
|
|
815
|
+
const saved = await this.saveMessage(
|
|
816
|
+
assistantMsg,
|
|
817
|
+
chatSessionId,
|
|
818
|
+
messageTimestamp
|
|
819
|
+
);
|
|
820
|
+
savedMsgId = saved?.id;
|
|
821
|
+
savedParentId = saved?.parent_message_id || null;
|
|
822
|
+
}
|
|
890
823
|
|
|
891
|
-
|
|
892
|
-
let savedMsgId: string | undefined;
|
|
893
|
-
let savedParentId: string | null = null;
|
|
894
|
-
if (chatSessionId) {
|
|
895
|
-
const saved = await this.saveMessage(
|
|
896
|
-
message,
|
|
897
|
-
chatSessionId,
|
|
898
|
-
messageTimestamp,
|
|
899
|
-
requestData.senderId,
|
|
900
|
-
requestData.senderName
|
|
901
|
-
);
|
|
902
|
-
savedMsgId = saved?.id;
|
|
903
|
-
savedParentId = saved?.parent_message_id || null;
|
|
904
|
-
}
|
|
824
|
+
streamState.currentPartialText = undefined;
|
|
905
825
|
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
826
|
+
streamState.messages.push({
|
|
827
|
+
processId: streamState.processId,
|
|
828
|
+
message: assistantMsg as any,
|
|
829
|
+
usage: usage as any,
|
|
830
|
+
timestamp: messageTimestamp,
|
|
831
|
+
message_id: savedMsgId,
|
|
832
|
+
parent_message_id: savedParentId,
|
|
833
|
+
sender_id: requestSender.id,
|
|
834
|
+
sender_name: requestSender.name
|
|
835
|
+
});
|
|
915
836
|
|
|
916
|
-
|
|
917
|
-
processId: streamState.processId,
|
|
918
|
-
message,
|
|
919
|
-
usage,
|
|
920
|
-
timestamp: messageTimestamp,
|
|
921
|
-
message_id: savedMsgId,
|
|
922
|
-
parent_message_id: savedParentId,
|
|
923
|
-
sender_id: requestData.senderId,
|
|
924
|
-
sender_name: requestData.senderName
|
|
925
|
-
});
|
|
837
|
+
streamState.currentMessage = assistantMsg;
|
|
926
838
|
|
|
927
|
-
|
|
839
|
+
this.emitStreamEvent(streamState, 'message', {
|
|
840
|
+
processId: streamState.processId,
|
|
841
|
+
message: assistantMsg,
|
|
842
|
+
usage,
|
|
843
|
+
timestamp: messageTimestamp,
|
|
844
|
+
message_id: savedMsgId,
|
|
845
|
+
parent_message_id: savedParentId,
|
|
846
|
+
sender_id: requestSender.id,
|
|
847
|
+
sender_name: requestSender.name
|
|
848
|
+
});
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
928
851
|
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
852
|
+
// ── User Message (tool results from SDK) ───────────────
|
|
853
|
+
case 'user': {
|
|
854
|
+
const userMsg = enrichMessageEngine(output, engineCtx) as UserMessage;
|
|
855
|
+
lastAssistantTextContent = null; // Reset dedup tracker
|
|
856
|
+
|
|
857
|
+
const messageTimestamp = userMsg.createdAt;
|
|
858
|
+
let savedMsgId: string | undefined;
|
|
859
|
+
let savedParentId: string | null = null;
|
|
860
|
+
if (chatSessionId) {
|
|
861
|
+
const saved = await this.saveMessage(
|
|
862
|
+
userMsg,
|
|
863
|
+
chatSessionId,
|
|
864
|
+
messageTimestamp
|
|
865
|
+
);
|
|
866
|
+
savedMsgId = saved?.id;
|
|
867
|
+
savedParentId = saved?.parent_message_id || null;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
streamState.messages.push({
|
|
871
|
+
processId: streamState.processId,
|
|
872
|
+
message: userMsg as any,
|
|
873
|
+
timestamp: messageTimestamp,
|
|
874
|
+
message_id: savedMsgId,
|
|
875
|
+
parent_message_id: savedParentId,
|
|
876
|
+
sender_id: requestSender.id,
|
|
877
|
+
sender_name: requestSender.name
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
streamState.currentMessage = userMsg;
|
|
881
|
+
|
|
882
|
+
this.emitStreamEvent(streamState, 'message', {
|
|
883
|
+
processId: streamState.processId,
|
|
884
|
+
message: userMsg,
|
|
885
|
+
timestamp: messageTimestamp,
|
|
886
|
+
message_id: savedMsgId,
|
|
887
|
+
parent_message_id: savedParentId,
|
|
888
|
+
sender_id: requestSender.id,
|
|
889
|
+
sender_name: requestSender.name
|
|
890
|
+
});
|
|
891
|
+
continue;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
default:
|
|
895
|
+
debug.log('chat', `[SM] Skipping unknown EngineOutput type: ${(output as any).type}`);
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
940
898
|
} }); // end runWithContextAsync + for await
|
|
941
899
|
|
|
942
|
-
// Only mark as completed if not already cancelled/errored
|
|
943
900
|
if (streamState.status === 'active') {
|
|
944
901
|
streamState.status = 'completed';
|
|
945
902
|
streamState.completedAt = new Date();
|
|
@@ -948,18 +905,15 @@ class StreamManager extends EventEmitter {
|
|
|
948
905
|
processId: streamState.processId,
|
|
949
906
|
timestamp: streamState.completedAt.toISOString()
|
|
950
907
|
});
|
|
951
|
-
|
|
952
908
|
this.emitStreamLifecycle(streamState, 'completed');
|
|
953
909
|
}
|
|
954
910
|
|
|
955
|
-
// Auto-release all MCP-controlled tabs for this chat session
|
|
956
911
|
if (chatSessionId) {
|
|
957
912
|
browserMcpControl.releaseSession(chatSessionId);
|
|
958
913
|
debug.log('mcp', `✅ Auto-released MCP tabs for session ${chatSessionId.slice(0, 8)} on stream completion`);
|
|
959
914
|
}
|
|
960
915
|
|
|
961
916
|
} catch (error) {
|
|
962
|
-
// Don't overwrite status if already cancelled by cancelStream()
|
|
963
917
|
if (streamState.status !== 'cancelled') {
|
|
964
918
|
streamState.status = 'error';
|
|
965
919
|
streamState.error = this.extractErrorDetail(error);
|
|
@@ -967,48 +921,41 @@ class StreamManager extends EventEmitter {
|
|
|
967
921
|
|
|
968
922
|
const errorTimestamp = streamState.completedAt.toISOString();
|
|
969
923
|
|
|
970
|
-
// Build a synthetic assistant message
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
// Save error message to DB (no snapshot needed for error messages)
|
|
924
|
+
// Build a synthetic error assistant message (unified type)
|
|
925
|
+
const errorAssistantMsg: AssistantMessage = {
|
|
926
|
+
type: 'assistant',
|
|
927
|
+
createdAt: errorTimestamp,
|
|
928
|
+
messageId: crypto.randomUUID(),
|
|
929
|
+
sessionId: streamState.sdkSessionId || null,
|
|
930
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
931
|
+
engine: { type: streamState.engine, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
|
|
932
|
+
content: [{ type: 'text', text: `**Error:** ${streamState.error}` }],
|
|
933
|
+
stopReason: null,
|
|
934
|
+
usage: null,
|
|
935
|
+
};
|
|
936
|
+
|
|
984
937
|
let savedErrorMsgId: string | undefined;
|
|
985
938
|
let savedErrorParentId: string | null = null;
|
|
986
939
|
if (requestData.chatSessionId) {
|
|
987
940
|
const saved = await this.saveMessage(
|
|
988
941
|
errorAssistantMsg,
|
|
989
942
|
requestData.chatSessionId,
|
|
990
|
-
errorTimestamp
|
|
991
|
-
requestData.senderId,
|
|
992
|
-
requestData.senderName
|
|
943
|
+
errorTimestamp
|
|
993
944
|
);
|
|
994
945
|
savedErrorMsgId = saved?.id;
|
|
995
946
|
savedErrorParentId = saved?.parent_message_id || null;
|
|
996
947
|
}
|
|
997
948
|
|
|
998
|
-
// Emit as chat:message so the error appears in the conversation list
|
|
999
|
-
// and is loaded from DB on browser refresh
|
|
1000
949
|
this.emitStreamEvent(streamState, 'message', {
|
|
1001
950
|
processId: streamState.processId,
|
|
1002
951
|
message: errorAssistantMsg,
|
|
1003
952
|
timestamp: errorTimestamp,
|
|
1004
953
|
message_id: savedErrorMsgId,
|
|
1005
954
|
parent_message_id: savedErrorParentId,
|
|
1006
|
-
sender_id: requestData.
|
|
1007
|
-
sender_name: requestData.
|
|
955
|
+
sender_id: requestData.sender.id,
|
|
956
|
+
sender_name: requestData.sender.name,
|
|
1008
957
|
});
|
|
1009
958
|
|
|
1010
|
-
// Emit chat:error to signal stream termination (triggers isLoading=false,
|
|
1011
|
-
// sound/push notification, and stream cleanup on the frontend)
|
|
1012
959
|
this.emitStreamEvent(streamState, 'error', {
|
|
1013
960
|
processId: streamState.processId,
|
|
1014
961
|
error: streamState.error,
|
|
@@ -1018,14 +965,11 @@ class StreamManager extends EventEmitter {
|
|
|
1018
965
|
this.emitStreamLifecycle(streamState, 'error');
|
|
1019
966
|
}
|
|
1020
967
|
|
|
1021
|
-
// Auto-release all MCP-controlled tabs for this chat session
|
|
1022
968
|
if (requestData.chatSessionId) {
|
|
1023
969
|
browserMcpControl.releaseSession(requestData.chatSessionId);
|
|
1024
970
|
debug.log('mcp', `✅ Auto-released MCP tabs for session ${requestData.chatSessionId.slice(0, 8)} on stream error`);
|
|
1025
971
|
}
|
|
1026
972
|
} finally {
|
|
1027
|
-
// Capture snapshot ONCE at stream end (regardless of completion/error/cancel).
|
|
1028
|
-
// Associates the snapshot with the user message (checkpoint) that triggered the stream.
|
|
1029
973
|
const { projectPath, projectId, chatSessionId } = requestData;
|
|
1030
974
|
if (projectPath && projectId && chatSessionId && userMessageId) {
|
|
1031
975
|
snapshotService.captureSnapshot(projectPath, projectId, chatSessionId, userMessageId)
|
|
@@ -1119,28 +1063,30 @@ class StreamManager extends EventEmitter {
|
|
|
1119
1063
|
// Save partial reasoning text to DB before cancelling (persists across refresh/project switch)
|
|
1120
1064
|
if (streamState.currentReasoningText && streamState.chatSessionId) {
|
|
1121
1065
|
try {
|
|
1122
|
-
const reasoningMessage = {
|
|
1123
|
-
type: 'assistant' as const,
|
|
1124
|
-
parent_tool_use_id: null,
|
|
1125
|
-
message: {
|
|
1126
|
-
role: 'assistant' as const,
|
|
1127
|
-
content: [{ type: 'text' as const, text: streamState.currentReasoningText }]
|
|
1128
|
-
},
|
|
1129
|
-
session_id: streamState.sdkSessionId || '',
|
|
1130
|
-
metadata: { reasoning: true }
|
|
1131
|
-
};
|
|
1132
|
-
|
|
1133
1066
|
const timestamp = new Date().toISOString();
|
|
1134
1067
|
const currentHead = sessionQueries.getHead(streamState.chatSessionId);
|
|
1135
1068
|
|
|
1069
|
+
const reasoningMessage: ReasoningMessage = {
|
|
1070
|
+
type: 'reasoning',
|
|
1071
|
+
createdAt: timestamp,
|
|
1072
|
+
messageId: crypto.randomUUID(),
|
|
1073
|
+
sessionId: null, // Partial cancel saves are not valid resume targets
|
|
1074
|
+
parent: { messageId: currentHead || null, sessionId: null, toolUseId: null },
|
|
1075
|
+
engine: { type: streamState.engine, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
|
|
1076
|
+
text: streamState.currentReasoningText,
|
|
1077
|
+
};
|
|
1078
|
+
|
|
1136
1079
|
const savedMessage = messageQueries.create({
|
|
1137
1080
|
session_id: streamState.chatSessionId,
|
|
1138
|
-
|
|
1081
|
+
message: reasoningMessage,
|
|
1139
1082
|
timestamp,
|
|
1140
1083
|
parent_message_id: currentHead || undefined
|
|
1141
1084
|
});
|
|
1142
1085
|
|
|
1143
1086
|
sessionQueries.updateHead(streamState.chatSessionId, savedMessage.id);
|
|
1087
|
+
sessionQueries.updateOnMessage(streamState.chatSessionId, {
|
|
1088
|
+
messageType: 'reasoning', timestamp,
|
|
1089
|
+
});
|
|
1144
1090
|
debug.log('chat', 'Saved partial reasoning on cancel:', savedMessage.id);
|
|
1145
1091
|
} catch (error) {
|
|
1146
1092
|
debug.error('chat', 'Failed to save partial reasoning on cancel:', error);
|
|
@@ -1150,48 +1096,54 @@ class StreamManager extends EventEmitter {
|
|
|
1150
1096
|
// Save partial text to DB before cancelling (persists across refresh/project switch)
|
|
1151
1097
|
if (streamState.currentPartialText && streamState.chatSessionId) {
|
|
1152
1098
|
try {
|
|
1153
|
-
const partialMessage = {
|
|
1154
|
-
type: 'assistant' as const,
|
|
1155
|
-
parent_tool_use_id: null,
|
|
1156
|
-
message: {
|
|
1157
|
-
role: 'assistant' as const,
|
|
1158
|
-
content: [{ type: 'text' as const, text: streamState.currentPartialText }]
|
|
1159
|
-
},
|
|
1160
|
-
session_id: streamState.sdkSessionId || '',
|
|
1161
|
-
partialText: streamState.currentPartialText
|
|
1162
|
-
};
|
|
1163
|
-
|
|
1164
1099
|
const timestamp = new Date().toISOString();
|
|
1165
1100
|
const currentHead = sessionQueries.getHead(streamState.chatSessionId);
|
|
1166
1101
|
|
|
1102
|
+
const partialMessage: AssistantMessage = {
|
|
1103
|
+
type: 'assistant',
|
|
1104
|
+
createdAt: timestamp,
|
|
1105
|
+
messageId: crypto.randomUUID(),
|
|
1106
|
+
sessionId: null, // Partial cancel saves are not valid resume targets
|
|
1107
|
+
parent: { messageId: currentHead || null, sessionId: null, toolUseId: null },
|
|
1108
|
+
engine: { type: streamState.engine, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
|
|
1109
|
+
content: [{ type: 'text', text: streamState.currentPartialText }],
|
|
1110
|
+
stopReason: 'interrupted',
|
|
1111
|
+
usage: null,
|
|
1112
|
+
};
|
|
1113
|
+
|
|
1167
1114
|
const savedMessage = messageQueries.create({
|
|
1168
1115
|
session_id: streamState.chatSessionId,
|
|
1169
|
-
|
|
1116
|
+
message: partialMessage,
|
|
1170
1117
|
timestamp,
|
|
1171
1118
|
parent_message_id: currentHead || undefined
|
|
1172
1119
|
});
|
|
1173
1120
|
|
|
1174
1121
|
sessionQueries.updateHead(streamState.chatSessionId, savedMessage.id);
|
|
1122
|
+
const clean = streamState.currentPartialText.replace(/```[\s\S]*?```/g, '').trim();
|
|
1123
|
+
sessionQueries.updateOnMessage(streamState.chatSessionId, {
|
|
1124
|
+
messageType: 'assistant', timestamp,
|
|
1125
|
+
headSummary: clean ? clean.slice(0, 200) + (clean.length > 200 ? '...' : '') : undefined,
|
|
1126
|
+
});
|
|
1175
1127
|
debug.log('chat', 'Saved partial text on cancel:', savedMessage.id);
|
|
1176
1128
|
} catch (error) {
|
|
1177
1129
|
debug.error('chat', 'Failed to save partial text on cancel:', error);
|
|
1178
1130
|
}
|
|
1179
1131
|
}
|
|
1180
1132
|
|
|
1181
|
-
// Claude Code only: restore
|
|
1133
|
+
// Claude Code only: restore head_session_id to pre-stream value.
|
|
1182
1134
|
// Claude Code SDK only returns session_id inside yielded messages, so a cancelled
|
|
1183
1135
|
// stream's fork session_id is not a valid resume target. OpenCode creates sessions
|
|
1184
|
-
// synchronously, so its
|
|
1185
|
-
if (streamState.engine === 'claude-code' && streamState.chatSessionId && streamState.
|
|
1136
|
+
// synchronously, so its head_session_id is always valid — no restoration needed.
|
|
1137
|
+
if (streamState.engine === 'claude-code' && streamState.chatSessionId && streamState.preStreamSessionId !== undefined) {
|
|
1186
1138
|
try {
|
|
1187
|
-
if (streamState.
|
|
1188
|
-
sessionQueries.
|
|
1139
|
+
if (streamState.preStreamSessionId) {
|
|
1140
|
+
sessionQueries.updateSessionId(streamState.chatSessionId, streamState.preStreamSessionId);
|
|
1189
1141
|
} else {
|
|
1190
|
-
sessionQueries.
|
|
1142
|
+
sessionQueries.clearSessionId(streamState.chatSessionId);
|
|
1191
1143
|
}
|
|
1192
|
-
debug.log('chat', `Restored
|
|
1144
|
+
debug.log('chat', `Restored head_session_id to: ${streamState.preStreamSessionId || 'null'}`);
|
|
1193
1145
|
} catch (error) {
|
|
1194
|
-
debug.error('chat', 'Failed to restore
|
|
1146
|
+
debug.error('chat', 'Failed to restore head_session_id:', error);
|
|
1195
1147
|
}
|
|
1196
1148
|
}
|
|
1197
1149
|
|
|
@@ -1274,29 +1226,54 @@ class StreamManager extends EventEmitter {
|
|
|
1274
1226
|
}
|
|
1275
1227
|
|
|
1276
1228
|
/**
|
|
1277
|
-
* Save message to database
|
|
1229
|
+
* Save message to database and update session metadata.
|
|
1278
1230
|
*/
|
|
1279
1231
|
private async saveMessage(
|
|
1280
|
-
message:
|
|
1232
|
+
message: UnifiedMessage,
|
|
1281
1233
|
sessionId: string,
|
|
1282
|
-
timestamp: string
|
|
1283
|
-
senderId?: string,
|
|
1284
|
-
senderName?: string
|
|
1234
|
+
timestamp: string
|
|
1285
1235
|
): Promise<DatabaseMessage | null> {
|
|
1286
1236
|
try {
|
|
1287
1237
|
const currentHead = sessionQueries.getHead(sessionId);
|
|
1288
1238
|
|
|
1289
1239
|
const savedMessage = messageQueries.create({
|
|
1290
1240
|
session_id: sessionId,
|
|
1291
|
-
|
|
1241
|
+
message: message,
|
|
1292
1242
|
timestamp,
|
|
1293
|
-
sender_id: senderId,
|
|
1294
|
-
sender_name: senderName,
|
|
1295
1243
|
parent_message_id: currentHead || undefined
|
|
1296
1244
|
});
|
|
1297
1245
|
|
|
1298
1246
|
sessionQueries.updateHead(sessionId, savedMessage.id);
|
|
1299
1247
|
|
|
1248
|
+
// ── Update session metadata ──
|
|
1249
|
+
try {
|
|
1250
|
+
const text = extractMessageText(message);
|
|
1251
|
+
const updateOpts: Parameters<typeof sessionQueries.updateOnMessage>[1] = {
|
|
1252
|
+
messageType: message.type,
|
|
1253
|
+
senderId: message.type === 'user' ? message.sender?.id : undefined,
|
|
1254
|
+
senderName: message.type === 'user' ? message.sender?.name : undefined,
|
|
1255
|
+
timestamp,
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
if (message.type === 'user' && text.trim()) {
|
|
1259
|
+
updateOpts.headTitle = text.slice(0, 80) + (text.length > 80 ? '...' : '');
|
|
1260
|
+
// Auto-set title if this is the first user message
|
|
1261
|
+
if (!currentHead) {
|
|
1262
|
+
updateOpts.isFirstUserMessage = true;
|
|
1263
|
+
updateOpts.title = updateOpts.headTitle;
|
|
1264
|
+
}
|
|
1265
|
+
} else if (message.type === 'assistant' && text.trim()) {
|
|
1266
|
+
const clean = text.replace(/```[\s\S]*?```/g, '').trim();
|
|
1267
|
+
if (clean) {
|
|
1268
|
+
updateOpts.headSummary = clean.slice(0, 200) + (clean.length > 200 ? '...' : '');
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
sessionQueries.updateOnMessage(sessionId, updateOpts);
|
|
1273
|
+
} catch (err) {
|
|
1274
|
+
debug.error('chat', 'Failed to update session metadata:', err);
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1300
1277
|
// Update checkpoint_tree_state when saving a new checkpoint (real user message)
|
|
1301
1278
|
if (message.type === 'user') {
|
|
1302
1279
|
try {
|
|
@@ -1328,6 +1305,38 @@ class StreamManager extends EventEmitter {
|
|
|
1328
1305
|
}
|
|
1329
1306
|
}
|
|
1330
1307
|
|
|
1308
|
+
/**
|
|
1309
|
+
* Backfill stopReason from a result event to the last assistant message in DB.
|
|
1310
|
+
* Claude Code SDK may yield assistant messages with stop_reason: null during streaming;
|
|
1311
|
+
* the actual stop_reason only arrives in the result event after the turn completes.
|
|
1312
|
+
* Returns the mapped StopReason if backfill succeeded, null otherwise.
|
|
1313
|
+
*/
|
|
1314
|
+
private backfillStopReason(chatSessionId: string, rawStopReason: string): StopReason | null {
|
|
1315
|
+
try {
|
|
1316
|
+
const mapped: StopReason = (['end_turn', 'tool_use', 'max_tokens', 'interrupted'] as StopReason[])
|
|
1317
|
+
.find(r => r === rawStopReason) || 'end_turn';
|
|
1318
|
+
|
|
1319
|
+
const currentHead = sessionQueries.getHead(chatSessionId);
|
|
1320
|
+
if (!currentHead) return null;
|
|
1321
|
+
|
|
1322
|
+
const headRow = messageQueries.getById(currentHead);
|
|
1323
|
+
if (!headRow) return null;
|
|
1324
|
+
|
|
1325
|
+
const headMsg = JSON.parse(headRow.data) as UnifiedMessage;
|
|
1326
|
+
if (headMsg.type !== 'assistant' || headMsg.stopReason) return null;
|
|
1327
|
+
|
|
1328
|
+
const updated = { ...headMsg, stopReason: mapped };
|
|
1329
|
+
const { getDatabase } = require('../database');
|
|
1330
|
+
getDatabase().prepare('UPDATE messages SET data = ? WHERE id = ?')
|
|
1331
|
+
.run(JSON.stringify(updated), headRow.id);
|
|
1332
|
+
|
|
1333
|
+
return mapped;
|
|
1334
|
+
} catch (err) {
|
|
1335
|
+
debug.error('chat', 'Failed to backfill stopReason:', err);
|
|
1336
|
+
return null;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1331
1340
|
/**
|
|
1332
1341
|
* Extract detailed error info from an error object.
|
|
1333
1342
|
* Handles engine-specific error shapes (Anthropic APIError, OpenCode SDK errors).
|