@widgetic/chat 0.1.5 → 0.1.7
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/dist/adapters/widgeticAdapter.js +2 -5
- package/dist/components/ActionBar.svelte +6 -6
- package/dist/components/AttachmentDisplay.svelte +16 -5
- package/dist/components/Chat.svelte +375 -209
- package/dist/components/Chat.svelte.d.ts +14 -2
- package/dist/components/ChatInput.svelte +71 -17
- package/dist/components/ChatInput.svelte.d.ts +2 -0
- package/dist/components/ChatMessages.svelte +267 -113
- package/dist/components/ChatMessages.svelte.d.ts +3 -1
- package/dist/components/CodeBlock.svelte +146 -19
- package/dist/components/SuggestionButtons.svelte +1 -1
- package/dist/services/chatService.js +11 -11
- package/dist/stores/chatStore.js +4 -6
- package/dist/types/config.d.ts +2 -2
- package/dist/types/config.js +1 -1
- package/dist/utils/logger.js +2 -3
- package/package.json +7 -6
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { onMount, onDestroy, untrack } from 'svelte';
|
|
3
|
-
import { chatStore, getCurrentMessages } from '../stores/chatStore.js';
|
|
3
|
+
import { chatStore, getCurrentState, getCurrentMessages } from '../stores/chatStore.js';
|
|
4
4
|
import { createChatService } from '../services/chatService.js';
|
|
5
5
|
import { setLogsEnabled, chatLog, chatWarn } from '../utils/logger.js';
|
|
6
6
|
import type { ChatConfig, ChatContext } from '../types/index.js';
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
isCompleted?: boolean;
|
|
21
21
|
onStatsUpdate?: (messageCount: number, firstMessage: string | null) => void;
|
|
22
22
|
onChatReady?: (chatMethods: ChatMethods) => void;
|
|
23
|
-
onCompletionToggle?: () => void;
|
|
23
|
+
onCompletionToggle?: (detail?: { conversationId: string | null; completed: boolean }) => void;
|
|
24
24
|
/** When provided, called instead of the built-in mock service for sending messages.
|
|
25
25
|
* The parent handles the actual API call and can push assistant messages via addAssistantMessage. */
|
|
26
26
|
onSendMessage?: (
|
|
@@ -79,11 +79,19 @@
|
|
|
79
79
|
resizeExpandsContainer?: boolean;
|
|
80
80
|
/** Delta in pixels, plus the resulting chat container height (for parent-owned resize). */
|
|
81
81
|
onMessagesResize?: (deltaPx: number, nextContainerHeightPx?: number) => void;
|
|
82
|
+
/**
|
|
83
|
+
* Widget Git HEAD from the host (panel lastCommitId). Used so Head / Restore chrome
|
|
84
|
+
* still appears when assistant commit bubbles were never persisted.
|
|
85
|
+
*/
|
|
86
|
+
widgetHeadCommitSha?: string | null;
|
|
87
|
+
/** Host is running widget codegen — send button becomes stop. */
|
|
88
|
+
isGenerating?: boolean;
|
|
89
|
+
onStopGeneration?: () => void;
|
|
82
90
|
}
|
|
83
91
|
|
|
84
92
|
// Expose methods to parent component
|
|
85
93
|
interface ChatMethods {
|
|
86
|
-
sendMessage: (content: string, attachments?: File
|
|
94
|
+
sendMessage: (content: string, attachments?: Array<File | AttachmentInput>) => Promise<void>;
|
|
87
95
|
addAssistantMessage: (content: string, skipPersist?: boolean) => void;
|
|
88
96
|
addUserMessage: (content: string, attachments?: Array<{ id: string; url: string; file_type: string; file_name: string; file_size?: number }>) => void;
|
|
89
97
|
/** Returns the current conversation ID (null if no conversation is active). */
|
|
@@ -116,7 +124,7 @@
|
|
|
116
124
|
updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
|
|
117
125
|
}
|
|
118
126
|
|
|
119
|
-
let { context, config = {}, class: className = '', style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize }: Props = $props();
|
|
127
|
+
let { context, config = {}, class: className = '', style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, isGenerating = false, onStopGeneration }: Props = $props();
|
|
120
128
|
|
|
121
129
|
function notifyDraftChange() {
|
|
122
130
|
onDraftChange?.();
|
|
@@ -140,9 +148,10 @@
|
|
|
140
148
|
let localIsSending = $state(false);
|
|
141
149
|
let localIsUploading = $state(false);
|
|
142
150
|
|
|
143
|
-
// Reactive state from store - using proper store subscription
|
|
144
|
-
let chatState = $state<any>(
|
|
151
|
+
// Reactive state from store - using proper store subscription initialized synchronously
|
|
152
|
+
let chatState = $state<any>(getCurrentState());
|
|
145
153
|
let storeUnsubscribe: (() => void) | null = null;
|
|
154
|
+
let initializePromise: Promise<void> | null = null;
|
|
146
155
|
|
|
147
156
|
// Initialize store subscription
|
|
148
157
|
onMount(() => {
|
|
@@ -153,6 +162,15 @@
|
|
|
153
162
|
|
|
154
163
|
onDestroy(() => {
|
|
155
164
|
storeUnsubscribe?.();
|
|
165
|
+
for (const att of localAttachments) {
|
|
166
|
+
if (att.preview && att.preview.startsWith('blob:')) {
|
|
167
|
+
try {
|
|
168
|
+
URL.revokeObjectURL(att.preview);
|
|
169
|
+
} catch {
|
|
170
|
+
/* ignore error */
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
156
174
|
});
|
|
157
175
|
|
|
158
176
|
// Derived values from chat state
|
|
@@ -173,30 +191,53 @@
|
|
|
173
191
|
|
|
174
192
|
/** Prefer a conversation that already has messages (avoids empty auto-created convos). */
|
|
175
193
|
async function activateBestConversation(conversations: any[]): Promise<void> {
|
|
176
|
-
|
|
177
|
-
const conversationId = conversation.id || conversation.conversation_id || conversation.conversationId;
|
|
178
|
-
if (!conversationId) continue;
|
|
179
|
-
const loadedMessages = onLoadMessages
|
|
180
|
-
? await onLoadMessages(conversationId)
|
|
181
|
-
: await chatService.getMessages(conversationId);
|
|
182
|
-
const messageList = loadedMessages || [];
|
|
183
|
-
chatStore.actions.setMessages(conversationId, messageList);
|
|
194
|
+
if (!conversations || conversations.length === 0) return;
|
|
184
195
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
196
|
+
// Check latest conversation first (usually the intended active conversation)
|
|
197
|
+
const primaryConversation = conversations[0];
|
|
198
|
+
const primaryId = primaryConversation?.id || primaryConversation?.conversation_id || primaryConversation?.conversationId;
|
|
199
|
+
if (!primaryId) return;
|
|
200
|
+
|
|
201
|
+
currentConversationId = primaryId;
|
|
202
|
+
const initialLoadedMessages = onLoadMessages
|
|
203
|
+
? await onLoadMessages(primaryId)
|
|
204
|
+
: await chatService.getMessages(primaryId);
|
|
205
|
+
const initialMessageList = initialLoadedMessages || [];
|
|
206
|
+
chatStore.actions.setMessages(primaryId, initialMessageList);
|
|
207
|
+
|
|
208
|
+
if (initialMessageList.length > 0 || conversations.length === 1) {
|
|
209
|
+
markWidgetHeadAtLatestCommit();
|
|
210
|
+
// chatLog('[Chat] Restored conversation with history:', primaryId, initialMessageList.length, 'messages');
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// If latest conversation is empty, probe remaining conversations in parallel
|
|
215
|
+
const otherConversations = conversations.slice(1);
|
|
216
|
+
const probeResults = await Promise.all(
|
|
217
|
+
otherConversations.map(async (conv) => {
|
|
218
|
+
const id = conv?.id || conv?.conversation_id || conv?.conversationId;
|
|
219
|
+
if (!id) return null;
|
|
220
|
+
try {
|
|
221
|
+
const msgs = onLoadMessages
|
|
222
|
+
? await onLoadMessages(id)
|
|
223
|
+
: await chatService.getMessages(id);
|
|
224
|
+
return { id, messages: msgs || [] };
|
|
225
|
+
} catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
})
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
const foundWithHistory = probeResults.find((res) => res && res.messages.length > 0);
|
|
232
|
+
if (foundWithHistory) {
|
|
233
|
+
chatStore.actions.setMessages(foundWithHistory.id, foundWithHistory.messages);
|
|
234
|
+
currentConversationId = foundWithHistory.id;
|
|
235
|
+
markWidgetHeadAtLatestCommit();
|
|
236
|
+
// chatLog('[Chat] Restored conversation with history:', foundWithHistory.id, foundWithHistory.messages.length, 'messages');
|
|
237
|
+
return;
|
|
191
238
|
}
|
|
192
239
|
|
|
193
|
-
|
|
194
|
-
const fallbackId =
|
|
195
|
-
fallbackConversation?.id ||
|
|
196
|
-
fallbackConversation?.conversation_id ||
|
|
197
|
-
fallbackConversation?.conversationId;
|
|
198
|
-
chatLog('[Chat] All conversations empty — using latest:', fallbackId);
|
|
199
|
-
currentConversationId = fallbackId || null;
|
|
240
|
+
// chatLog('[Chat] All conversations empty — using latest:', primaryId);
|
|
200
241
|
}
|
|
201
242
|
|
|
202
243
|
let lastLoadedContextId = $state('');
|
|
@@ -204,18 +245,10 @@
|
|
|
204
245
|
async function initializeForContext(contextId: string) {
|
|
205
246
|
if (!contextId) return;
|
|
206
247
|
lastLoadedContextId = contextId;
|
|
207
|
-
chatLog('[Chat] Initializing with context:', contextId);
|
|
248
|
+
// chatLog('[Chat] Initializing with context:', contextId);
|
|
208
249
|
chatStore.actions.setActiveContext(contextId, true);
|
|
209
250
|
|
|
210
|
-
|
|
211
|
-
for (let attempt = 0; attempt < 4; attempt++) {
|
|
212
|
-
loaded = await loadConversations();
|
|
213
|
-
if (loaded !== null) break;
|
|
214
|
-
if (attempt < 3) {
|
|
215
|
-
await new Promise((resolve) => setTimeout(resolve, 400 * (attempt + 1)));
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
251
|
+
const loaded = await loadConversations();
|
|
219
252
|
if (loaded === null) {
|
|
220
253
|
chatStore.actions.updateUI({
|
|
221
254
|
errorMessage: 'Could not load chat history.',
|
|
@@ -224,17 +257,17 @@
|
|
|
224
257
|
}
|
|
225
258
|
|
|
226
259
|
if (loaded.length === 0) {
|
|
227
|
-
chatLog('[Chat] No existing conversations, creating new one');
|
|
260
|
+
// chatLog('[Chat] No existing conversations, creating new one');
|
|
228
261
|
await createNewConversation();
|
|
229
262
|
} else {
|
|
230
|
-
chatLog('[Chat] Selecting from', loaded.length, 'conversation(s)');
|
|
263
|
+
// chatLog('[Chat] Selecting from', loaded.length, 'conversation(s)');
|
|
231
264
|
await activateBestConversation(loaded);
|
|
232
265
|
}
|
|
233
|
-
chatLog('[Chat] Initialized successfully');
|
|
266
|
+
// chatLog('[Chat] Initialized successfully');
|
|
234
267
|
}
|
|
235
268
|
|
|
236
269
|
async function retryLoadHistory() {
|
|
237
|
-
chatLog('[Chat] Retry load history for', context?.id);
|
|
270
|
+
// chatLog('[Chat] Retry load history for', context?.id);
|
|
238
271
|
chatStore.actions.updateUI({ errorMessage: null });
|
|
239
272
|
lastLoadedContextId = '';
|
|
240
273
|
try {
|
|
@@ -248,17 +281,19 @@
|
|
|
248
281
|
}
|
|
249
282
|
|
|
250
283
|
// Lifecycle
|
|
251
|
-
onMount(
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
284
|
+
onMount(() => {
|
|
285
|
+
initializePromise = (async () => {
|
|
286
|
+
try {
|
|
287
|
+
await initializeForContext(context.id);
|
|
288
|
+
} catch (error) {
|
|
289
|
+
console.error('[Chat] Failed to initialize:', error);
|
|
290
|
+
chatStore.actions.updateUI({
|
|
291
|
+
errorMessage: 'Failed to initialize chat. Please try again.',
|
|
292
|
+
});
|
|
293
|
+
} finally {
|
|
294
|
+
isInitialized = true;
|
|
295
|
+
}
|
|
296
|
+
})();
|
|
262
297
|
});
|
|
263
298
|
|
|
264
299
|
$effect(() => {
|
|
@@ -266,19 +301,33 @@
|
|
|
266
301
|
if (!isInitialized || !nextId) return;
|
|
267
302
|
if (nextId === lastLoadedContextId) return;
|
|
268
303
|
untrack(() => {
|
|
304
|
+
const isDraftMigration =
|
|
305
|
+
Boolean(lastLoadedContextId) &&
|
|
306
|
+
(lastLoadedContextId.includes('temp') ||
|
|
307
|
+
lastLoadedContextId.includes('draft') ||
|
|
308
|
+
lastLoadedContextId.startsWith('new') ||
|
|
309
|
+
(lastLoadedContextId.includes(':') && nextId.includes(':') &&
|
|
310
|
+
lastLoadedContextId.split(':')[0] === nextId.split(':')[0] &&
|
|
311
|
+
lastLoadedContextId.split(':')[1]?.startsWith('draft')));
|
|
312
|
+
|
|
269
313
|
const prevConv = currentConversationId;
|
|
270
314
|
const prevMsgs = prevConv ? [...(getCurrentMessages(prevConv) || [])] : [];
|
|
271
|
-
const prevUserWithImage =
|
|
272
|
-
|
|
273
|
-
|
|
315
|
+
const prevUserWithImage = isDraftMigration
|
|
316
|
+
? [...prevMsgs].reverse().find(
|
|
317
|
+
(m: any) => m.messageType === 'user' && Array.isArray(m.attachments) && m.attachments.length > 0,
|
|
318
|
+
)
|
|
319
|
+
: null;
|
|
320
|
+
|
|
274
321
|
void initializeForContext(nextId).then(() => {
|
|
275
|
-
if (!prevUserWithImage?.attachments?.length) return;
|
|
276
|
-
const
|
|
322
|
+
if (!isDraftMigration || !prevUserWithImage?.attachments?.length) return;
|
|
323
|
+
const convId = currentConversationId;
|
|
324
|
+
if (!convId) return;
|
|
325
|
+
const nextMsgs = getCurrentMessages(convId) || [];
|
|
277
326
|
const nextUser = [...nextMsgs].reverse().find((m: any) => m.messageType === 'user');
|
|
278
327
|
if (!nextUser) return;
|
|
279
328
|
if (nextUser.attachments && nextUser.attachments.length > 0) return;
|
|
280
329
|
updateLastUserMessageAttachments(prevUserWithImage.attachments);
|
|
281
|
-
chatLog('[Chat] Restored image attachments after widget id migrate:', prevUserWithImage.attachments.length);
|
|
330
|
+
// chatLog('[Chat] Restored image attachments after widget id migrate:', prevUserWithImage.attachments.length);
|
|
282
331
|
});
|
|
283
332
|
});
|
|
284
333
|
});
|
|
@@ -347,15 +396,48 @@
|
|
|
347
396
|
}
|
|
348
397
|
}
|
|
349
398
|
|
|
350
|
-
async function sendMessage(content: string, attachments?: AttachmentInput
|
|
399
|
+
async function sendMessage(content: string, attachments?: Array<File | AttachmentInput>) {
|
|
351
400
|
if (!currentConversationId) {
|
|
401
|
+
if (initializePromise) {
|
|
402
|
+
try {
|
|
403
|
+
await initializePromise;
|
|
404
|
+
} catch {
|
|
405
|
+
/* ignore error, fallback to creating below */
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (!currentConversationId) {
|
|
409
|
+
try {
|
|
410
|
+
await createNewConversation();
|
|
411
|
+
} catch (convErr) {
|
|
412
|
+
console.error('No active conversation and failed to create one:', convErr);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const activeConversationId = currentConversationId;
|
|
419
|
+
if (!activeConversationId) {
|
|
352
420
|
console.error('No active conversation');
|
|
353
421
|
return;
|
|
354
422
|
}
|
|
355
423
|
|
|
356
|
-
|
|
424
|
+
const normalizedAttachments: AttachmentInput[] = (attachments || []).map((att) => {
|
|
425
|
+
if (att instanceof File) {
|
|
426
|
+
const isImage = att.type.startsWith('image/');
|
|
427
|
+
const isVideo = att.type.startsWith('video/');
|
|
428
|
+
return {
|
|
429
|
+
file: att,
|
|
430
|
+
type: isImage ? 'image' : isVideo ? 'video' : 'document',
|
|
431
|
+
preview: isImage || isVideo || att.type === 'application/pdf' ? URL.createObjectURL(att) : undefined,
|
|
432
|
+
uploadProgress: 0,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
return att;
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
// chatLog('[Chat] Sending message:', content.substring(0, 60));
|
|
357
439
|
const submittedContent = content;
|
|
358
|
-
const submittedAttachments =
|
|
440
|
+
const submittedAttachments = normalizedAttachments;
|
|
359
441
|
|
|
360
442
|
try {
|
|
361
443
|
localIsSending = true;
|
|
@@ -367,22 +449,22 @@
|
|
|
367
449
|
notifyDraftChange();
|
|
368
450
|
|
|
369
451
|
// Clear head/checkpoint marks — new prompt starts a new turn
|
|
370
|
-
const existingMsgs = getCurrentMessages(
|
|
452
|
+
const existingMsgs = getCurrentMessages(activeConversationId);
|
|
371
453
|
if (existingMsgs?.some((m: any) => m.rolledBackAt || m.isWidgetHead)) {
|
|
372
454
|
const cleared = existingMsgs.map((m: any) => ({
|
|
373
455
|
...m,
|
|
374
456
|
rolledBackAt: null,
|
|
375
457
|
isWidgetHead: false,
|
|
376
458
|
}));
|
|
377
|
-
chatStore.actions.setMessages(
|
|
459
|
+
chatStore.actions.setMessages(activeConversationId, cleared);
|
|
378
460
|
}
|
|
379
461
|
|
|
380
462
|
// Add user message to the UI immediately (local mock for instant feedback)
|
|
381
|
-
const userMessage = await chatService.sendMessage(
|
|
463
|
+
const userMessage = await chatService.sendMessage(activeConversationId, {
|
|
382
464
|
messageContent: submittedContent,
|
|
383
465
|
attachments: submittedAttachments
|
|
384
466
|
});
|
|
385
|
-
chatStore.actions.addMessage(
|
|
467
|
+
chatStore.actions.addMessage(activeConversationId, userMessage);
|
|
386
468
|
|
|
387
469
|
// Persist user message to backend and update local ID with DB UUID
|
|
388
470
|
if (onSaveMessage) {
|
|
@@ -396,18 +478,18 @@
|
|
|
396
478
|
display_order: i + 1,
|
|
397
479
|
})).filter((att: { url?: string; file?: File }) => !!att.url || att.file instanceof File);
|
|
398
480
|
const saved = await onSaveMessage(
|
|
399
|
-
|
|
481
|
+
activeConversationId,
|
|
400
482
|
submittedContent,
|
|
401
483
|
'user',
|
|
402
484
|
persistAttachments.length > 0 ? persistAttachments : userMessage.attachments,
|
|
403
485
|
);
|
|
404
486
|
if (saved?.id && saved.id !== userMessage.id) {
|
|
405
|
-
chatStore.actions.updateMessageId(
|
|
487
|
+
chatStore.actions.updateMessageId(activeConversationId, userMessage.id, saved.id);
|
|
406
488
|
}
|
|
407
489
|
const savedAttachments = saved?.attachments || saved?.data?.attachments;
|
|
408
490
|
if (Array.isArray(savedAttachments) && savedAttachments.length > 0) {
|
|
409
491
|
const targetId = saved?.id || userMessage.id;
|
|
410
|
-
chatStore.actions.updateMessageAttachments(
|
|
492
|
+
chatStore.actions.updateMessageAttachments(activeConversationId, targetId, savedAttachments);
|
|
411
493
|
}
|
|
412
494
|
} catch (err) {
|
|
413
495
|
chatWarn('[Chat] Failed to persist user message:', err);
|
|
@@ -419,14 +501,14 @@
|
|
|
419
501
|
file: att.file,
|
|
420
502
|
url: att.uploadedUrl || att.preview,
|
|
421
503
|
uploadId: att.uploadId,
|
|
422
|
-
fileType: att.file
|
|
423
|
-
fileName: att.file
|
|
424
|
-
fileSize: att.file
|
|
504
|
+
fileType: att.file?.type || 'application/octet-stream',
|
|
505
|
+
fileName: att.file?.name || 'attachment',
|
|
506
|
+
fileSize: att.file?.size,
|
|
425
507
|
}));
|
|
426
508
|
await onSendMessage(submittedContent, outgoing.length > 0 ? outgoing : undefined);
|
|
427
509
|
} else {
|
|
428
|
-
const aiResponse = await chatService.processAIResponse(
|
|
429
|
-
chatStore.actions.addMessage(
|
|
510
|
+
const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
|
|
511
|
+
chatStore.actions.addMessage(activeConversationId, aiResponse);
|
|
430
512
|
}
|
|
431
513
|
|
|
432
514
|
} catch (error) {
|
|
@@ -462,10 +544,7 @@
|
|
|
462
544
|
|
|
463
545
|
// Mark HEAD as soon as an assistant message carries a widget commit — this makes the
|
|
464
546
|
// Restore Checkpoint button available on previous commits even before "Preview ready".
|
|
465
|
-
if (
|
|
466
|
-
/Commit:?\s+[a-f0-9]{7,40}/i.test(content) &&
|
|
467
|
-
!/^Code generation failed/i.test(content.trim())
|
|
468
|
-
) {
|
|
547
|
+
if (messageHasWidgetCommit(content)) {
|
|
469
548
|
markWidgetHeadAtLatestCommit(assistantMsg.id);
|
|
470
549
|
}
|
|
471
550
|
|
|
@@ -475,9 +554,12 @@
|
|
|
475
554
|
if (saved?.id && saved.id !== assistantMsg.id) {
|
|
476
555
|
chatStore.actions.updateMessageId(convId, assistantMsg.id, saved.id);
|
|
477
556
|
}
|
|
557
|
+
rememberPersistedCommitSha(convId, content);
|
|
478
558
|
}).catch(err =>
|
|
479
559
|
chatWarn('[Chat] Failed to persist assistant message:', err)
|
|
480
560
|
);
|
|
561
|
+
} else if (skipPersist && messageHasWidgetCommit(content)) {
|
|
562
|
+
persistAssistantCommitOnce(assistantMsg.id, content);
|
|
481
563
|
}
|
|
482
564
|
}
|
|
483
565
|
|
|
@@ -485,12 +567,18 @@
|
|
|
485
567
|
* Also persists to DB via onSaveMessage so multi-turn history is complete. */
|
|
486
568
|
function addUserMessage(content: string, attachments?: Array<{ id: string; url: string; file_type: string; file_name: string; file_size?: number }>) {
|
|
487
569
|
if (!currentConversationId) return;
|
|
570
|
+
const mappedAttachments = (attachments || []).map((att, index) => ({
|
|
571
|
+
...att,
|
|
572
|
+
file_size: att.file_size ?? null,
|
|
573
|
+
display_order: index + 1,
|
|
574
|
+
created_at: new Date().toISOString(),
|
|
575
|
+
}));
|
|
488
576
|
const userMsg = {
|
|
489
577
|
id: `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
|
490
578
|
conversationId: currentConversationId,
|
|
491
579
|
messageContent: content,
|
|
492
580
|
messageType: 'user' as const,
|
|
493
|
-
attachments:
|
|
581
|
+
attachments: mappedAttachments,
|
|
494
582
|
isCommit: false,
|
|
495
583
|
userId: 'current_user',
|
|
496
584
|
createdAt: new Date(),
|
|
@@ -503,7 +591,7 @@
|
|
|
503
591
|
|
|
504
592
|
if (onSaveMessage) {
|
|
505
593
|
const convId = currentConversationId;
|
|
506
|
-
onSaveMessage(convId, content, 'user',
|
|
594
|
+
onSaveMessage(convId, content, 'user', mappedAttachments).then(saved => {
|
|
507
595
|
if (saved?.id && saved.id !== userMsg.id) {
|
|
508
596
|
chatStore.actions.updateMessageId(convId, userMsg.id, saved.id);
|
|
509
597
|
}
|
|
@@ -515,7 +603,7 @@
|
|
|
515
603
|
|
|
516
604
|
// ActionBar event handlers
|
|
517
605
|
async function handleScreenshot({ detail }: { detail: { contextId: string } }) {
|
|
518
|
-
chatLog('[Chat] Screenshot requested for context:', detail.contextId);
|
|
606
|
+
// chatLog('[Chat] Screenshot requested for context:', detail.contextId);
|
|
519
607
|
|
|
520
608
|
try {
|
|
521
609
|
let screenshotDataUrl: string | null = null;
|
|
@@ -552,7 +640,7 @@
|
|
|
552
640
|
});
|
|
553
641
|
}
|
|
554
642
|
|
|
555
|
-
chatLog('Screenshot captured and added to attachments');
|
|
643
|
+
// chatLog('Screenshot captured and added to attachments');
|
|
556
644
|
} catch (error) {
|
|
557
645
|
console.error('Screenshot capture failed:', error);
|
|
558
646
|
chatStore.actions.updateUI({
|
|
@@ -562,13 +650,13 @@
|
|
|
562
650
|
}
|
|
563
651
|
|
|
564
652
|
async function handleRecordStart({ detail }: { detail: { contextId: string } }) {
|
|
565
|
-
chatLog('Recording start requested for context:', detail.contextId);
|
|
653
|
+
// chatLog('Recording start requested for context:', detail.contextId);
|
|
566
654
|
|
|
567
655
|
try {
|
|
568
656
|
localIsRecording = true;
|
|
569
657
|
|
|
570
658
|
// This would integrate with the existing recording module
|
|
571
|
-
chatLog('Recording started...');
|
|
659
|
+
// chatLog('Recording started...');
|
|
572
660
|
|
|
573
661
|
} catch (error) {
|
|
574
662
|
console.error('Failed to start recording:', error);
|
|
@@ -580,7 +668,7 @@
|
|
|
580
668
|
}
|
|
581
669
|
|
|
582
670
|
async function handleRecordStop({ detail }: { detail: { contextId: string } }) {
|
|
583
|
-
chatLog('Recording stop requested for context:', detail.contextId);
|
|
671
|
+
// chatLog('Recording stop requested for context:', detail.contextId);
|
|
584
672
|
|
|
585
673
|
try {
|
|
586
674
|
localIsRecording = false;
|
|
@@ -600,7 +688,7 @@
|
|
|
600
688
|
// Add to attachments
|
|
601
689
|
localAttachments = [...localAttachments, attachmentInput];
|
|
602
690
|
|
|
603
|
-
chatLog('Recording stopped and added to attachments');
|
|
691
|
+
// chatLog('Recording stopped and added to attachments');
|
|
604
692
|
|
|
605
693
|
} catch (error) {
|
|
606
694
|
console.error('Failed to stop recording:', error);
|
|
@@ -642,13 +730,20 @@
|
|
|
642
730
|
entry.uploadedUrl = uploaded.url;
|
|
643
731
|
entry.uploadId = uploaded.id;
|
|
644
732
|
if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
|
|
733
|
+
if (entry.preview && entry.preview.startsWith('blob:')) {
|
|
734
|
+
try {
|
|
735
|
+
URL.revokeObjectURL(entry.preview);
|
|
736
|
+
} catch {
|
|
737
|
+
/* ignore error */
|
|
738
|
+
}
|
|
739
|
+
}
|
|
645
740
|
entry.preview = uploaded.url;
|
|
646
741
|
}
|
|
647
742
|
entry.uploadProgress = 100;
|
|
648
743
|
bumpAttachmentProgress(attachmentIndex, 100);
|
|
649
744
|
localAttachments = [...localAttachments];
|
|
650
745
|
notifyDraftChange();
|
|
651
|
-
chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
|
|
746
|
+
// chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
|
|
652
747
|
} catch (uploadError) {
|
|
653
748
|
console.error('[Chat] Upload failed, using local preview where possible:', uploadError);
|
|
654
749
|
if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
|
|
@@ -664,7 +759,7 @@
|
|
|
664
759
|
}
|
|
665
760
|
|
|
666
761
|
async function handleUpload() {
|
|
667
|
-
chatLog('File upload requested');
|
|
762
|
+
// chatLog('File upload requested');
|
|
668
763
|
|
|
669
764
|
const fileInput = document.createElement('input');
|
|
670
765
|
fileInput.type = 'file';
|
|
@@ -700,33 +795,37 @@
|
|
|
700
795
|
localIsUploading = false;
|
|
701
796
|
}
|
|
702
797
|
|
|
703
|
-
chatLog('Files selected via upload:', files.length);
|
|
798
|
+
// chatLog('Files selected via upload:', files.length);
|
|
704
799
|
};
|
|
705
800
|
|
|
706
801
|
fileInput.click();
|
|
707
802
|
}
|
|
708
803
|
|
|
709
804
|
async function handleComplete({ detail }: { detail: { completed: boolean } }) {
|
|
710
|
-
chatLog('Conversation completion toggle requested'
|
|
711
|
-
|
|
805
|
+
// chatLog('Conversation completion toggle requested', {
|
|
806
|
+
// conversationId: currentConversationId,
|
|
807
|
+
// completed: detail?.completed,
|
|
808
|
+
// });
|
|
809
|
+
|
|
712
810
|
if (!currentConversationId) {
|
|
713
811
|
console.error('No active conversation to mark as complete');
|
|
714
812
|
return;
|
|
715
813
|
}
|
|
716
|
-
|
|
814
|
+
|
|
717
815
|
try {
|
|
718
|
-
// Call parent's completion toggle function
|
|
719
816
|
if (onCompletionToggle) {
|
|
720
|
-
onCompletionToggle(
|
|
721
|
-
|
|
817
|
+
onCompletionToggle({
|
|
818
|
+
conversationId: currentConversationId,
|
|
819
|
+
completed: detail?.completed,
|
|
820
|
+
});
|
|
821
|
+
// chatLog('Completion toggled via parent callback');
|
|
722
822
|
} else {
|
|
723
823
|
chatWarn('No onCompletionToggle callback provided');
|
|
724
824
|
}
|
|
725
|
-
|
|
726
825
|
} catch (error) {
|
|
727
826
|
console.error('Failed to update conversation status:', error);
|
|
728
|
-
chatStore.actions.updateUI({
|
|
729
|
-
errorMessage: 'Failed to update conversation status'
|
|
827
|
+
chatStore.actions.updateUI({
|
|
828
|
+
errorMessage: 'Failed to update conversation status'
|
|
730
829
|
});
|
|
731
830
|
}
|
|
732
831
|
}
|
|
@@ -739,7 +838,7 @@
|
|
|
739
838
|
}
|
|
740
839
|
|
|
741
840
|
async function handleSuggestionSelected(suggestion: string) {
|
|
742
|
-
chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
|
|
841
|
+
// chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
|
|
743
842
|
// Autocomplete into input instead of sending immediately — lets user review,
|
|
744
843
|
// edit, and attach an image before sending (e.g. "Generate code from this design"
|
|
745
844
|
// is useless without an attached screenshot).
|
|
@@ -749,7 +848,7 @@
|
|
|
749
848
|
async function handleRetryMessage(content: string) {
|
|
750
849
|
const retryContent = content.trim();
|
|
751
850
|
if (!retryContent) return;
|
|
752
|
-
chatLog('[Chat] Retrying failed message:', retryContent.slice(0, 80));
|
|
851
|
+
// chatLog('[Chat] Retrying failed message:', retryContent.slice(0, 80));
|
|
753
852
|
if (onRetryMessage) {
|
|
754
853
|
await onRetryMessage(retryContent);
|
|
755
854
|
return;
|
|
@@ -758,7 +857,7 @@
|
|
|
758
857
|
}
|
|
759
858
|
|
|
760
859
|
async function handleRestoreCheckpoint(messageId: string, messageIndex: number) {
|
|
761
|
-
chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
|
|
860
|
+
// chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
|
|
762
861
|
|
|
763
862
|
if (!currentConversationId || !currentMessages) {
|
|
764
863
|
console.error('No active conversation or messages to restore');
|
|
@@ -766,21 +865,32 @@
|
|
|
766
865
|
}
|
|
767
866
|
|
|
768
867
|
try {
|
|
769
|
-
const clicked =
|
|
770
|
-
|
|
868
|
+
const clicked = messageIndex >= 0
|
|
869
|
+
? currentMessages[messageIndex]
|
|
870
|
+
: currentMessages.find((msg: any) => msg.id === messageId);
|
|
871
|
+
if (!clicked) {
|
|
872
|
+
console.warn('[Chat] Restore checkpoint: message not in local list', messageId);
|
|
873
|
+
if (onRestoreCheckpointBackend && !String(messageId).startsWith('fallback-head-')) {
|
|
874
|
+
await onRestoreCheckpointBackend(currentConversationId, messageId);
|
|
875
|
+
}
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
const resolvedIndex = currentMessages.findIndex((msg: any) => msg.id === clicked.id);
|
|
879
|
+
let checkpointUserId = clicked.messageType === 'user' ? clicked.id : messageId;
|
|
771
880
|
let headAssistantId = clicked?.id;
|
|
772
881
|
|
|
773
882
|
// API rolls back to the commit produced by the user prompt before this assistant reply.
|
|
774
883
|
if (clicked?.messageType === 'assistant') {
|
|
775
884
|
headAssistantId = clicked.id;
|
|
776
|
-
for (let i =
|
|
885
|
+
for (let i = resolvedIndex - 1; i >= 0; i--) {
|
|
777
886
|
if (currentMessages[i].messageType === 'user') {
|
|
778
887
|
checkpointUserId = currentMessages[i].id;
|
|
779
888
|
break;
|
|
780
889
|
}
|
|
781
890
|
}
|
|
782
891
|
} else {
|
|
783
|
-
|
|
892
|
+
checkpointUserId = clicked.id;
|
|
893
|
+
for (let i = resolvedIndex + 1; i < currentMessages.length; i++) {
|
|
784
894
|
if (currentMessages[i].messageType === 'assistant' && messageHasWidgetCommit(currentMessages[i].messageContent)) {
|
|
785
895
|
headAssistantId = currentMessages[i].id;
|
|
786
896
|
break;
|
|
@@ -794,13 +904,13 @@
|
|
|
794
904
|
rolledBackAt: null,
|
|
795
905
|
}));
|
|
796
906
|
|
|
797
|
-
chatLog(`Restoring to checkpoint user message ${checkpointUserId}, head assistant ${headAssistantId}`);
|
|
907
|
+
// chatLog(`Restoring to checkpoint user message ${checkpointUserId}, head assistant ${headAssistantId}`);
|
|
798
908
|
chatStore.actions.setMessages(currentConversationId, updatedMessages);
|
|
799
909
|
|
|
800
910
|
if (onRestoreCheckpointBackend) {
|
|
801
911
|
try {
|
|
802
912
|
const result = await onRestoreCheckpointBackend(currentConversationId, checkpointUserId);
|
|
803
|
-
chatLog('[Chat] Checkpoint restored on backend:', result);
|
|
913
|
+
// chatLog('[Chat] Checkpoint restored on backend:', result);
|
|
804
914
|
if (headAssistantId) {
|
|
805
915
|
markWidgetHeadAtLatestCommit(headAssistantId);
|
|
806
916
|
}
|
|
@@ -810,7 +920,7 @@
|
|
|
810
920
|
}
|
|
811
921
|
|
|
812
922
|
chatStore.actions.updateUI({ errorMessage: null });
|
|
813
|
-
chatLog('Checkpoint restored successfully');
|
|
923
|
+
// chatLog('Checkpoint restored successfully');
|
|
814
924
|
|
|
815
925
|
} catch (error) {
|
|
816
926
|
console.error('Failed to restore checkpoint:', error);
|
|
@@ -838,13 +948,11 @@
|
|
|
838
948
|
return;
|
|
839
949
|
}
|
|
840
950
|
try {
|
|
841
|
-
const
|
|
951
|
+
const response = await fetch(dataUrl);
|
|
952
|
+
const blob = await response.blob();
|
|
842
953
|
const mimeMatch = dataUrl.match(/data:(image\/[^;]+);/);
|
|
843
|
-
const mimeType = mimeMatch?.[1] || 'image/png';
|
|
844
|
-
const
|
|
845
|
-
const ia = new Uint8Array(ab);
|
|
846
|
-
for (let i = 0; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);
|
|
847
|
-
const file = new File([ab], fileName, { type: mimeType });
|
|
954
|
+
const mimeType = mimeMatch?.[1] || blob.type || 'image/png';
|
|
955
|
+
const file = new File([blob], fileName, { type: mimeType });
|
|
848
956
|
const attachmentInput: AttachmentInput = {
|
|
849
957
|
file,
|
|
850
958
|
type: 'image',
|
|
@@ -857,7 +965,7 @@
|
|
|
857
965
|
if (onUploadChatFile) {
|
|
858
966
|
await uploadAttachmentToCdn(file, attachmentInput, attachmentIndex);
|
|
859
967
|
}
|
|
860
|
-
chatLog('Image attachment added from external paste');
|
|
968
|
+
// chatLog('Image attachment added from external paste');
|
|
861
969
|
} catch (err) {
|
|
862
970
|
console.error('[Chat] Failed to add image attachment:', err);
|
|
863
971
|
}
|
|
@@ -885,6 +993,15 @@
|
|
|
885
993
|
}
|
|
886
994
|
|
|
887
995
|
function restoreAttachmentsFromDataUrls(dataUrls: string[]) {
|
|
996
|
+
for (const att of localAttachments) {
|
|
997
|
+
if (att.preview && att.preview.startsWith('blob:')) {
|
|
998
|
+
try {
|
|
999
|
+
URL.revokeObjectURL(att.preview);
|
|
1000
|
+
} catch {
|
|
1001
|
+
/* ignore error */
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
888
1005
|
localAttachments = [];
|
|
889
1006
|
const validUrls = dataUrls.filter(isValidImageDataUrl);
|
|
890
1007
|
for (let i = 0; i < validUrls.length; i++) {
|
|
@@ -896,12 +1013,21 @@
|
|
|
896
1013
|
}
|
|
897
1014
|
|
|
898
1015
|
function clearDraft() {
|
|
1016
|
+
for (const att of localAttachments) {
|
|
1017
|
+
if (att.preview && att.preview.startsWith('blob:')) {
|
|
1018
|
+
try {
|
|
1019
|
+
URL.revokeObjectURL(att.preview);
|
|
1020
|
+
} catch {
|
|
1021
|
+
/* ignore error */
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
899
1025
|
localInputText = '';
|
|
900
1026
|
localAttachments = [];
|
|
901
1027
|
notifyDraftChange();
|
|
902
1028
|
}
|
|
903
1029
|
|
|
904
|
-
const CODEGEN_COMMIT_REGEX = /Commit:?\s
|
|
1030
|
+
const CODEGEN_COMMIT_REGEX = /(?:Commit:?\s+|Code saved\s*\()([a-f0-9]{7,40})/i;
|
|
905
1031
|
|
|
906
1032
|
function isPreviewRecompiledMessage(content?: string | null): boolean {
|
|
907
1033
|
return /^Preview recompiled/i.test((content || '').trim());
|
|
@@ -913,13 +1039,14 @@
|
|
|
913
1039
|
return /^Updated \d+ files?/i.test(trimmed) && /\n\nCommit\s+[a-f0-9]{7,40}/i.test(trimmed);
|
|
914
1040
|
}
|
|
915
1041
|
|
|
916
|
-
/** Widget HEAD: codegen
|
|
1042
|
+
/** Widget HEAD: real codegen commits only — not rebuild-only "Preview recompiled" bubbles. */
|
|
917
1043
|
function messageHasWidgetCommit(content?: string | null): boolean {
|
|
918
1044
|
const trimmed = (content || '').trim();
|
|
919
1045
|
if (!trimmed || isCodegenFailureMessage(trimmed)) return false;
|
|
920
|
-
if (isPreviewRecompiledMessage(trimmed)
|
|
1046
|
+
if (isPreviewRecompiledMessage(trimmed)) return false;
|
|
921
1047
|
if (CODEGEN_COMMIT_REGEX.test(trimmed) && (
|
|
922
1048
|
/^Code generation completed/i.test(trimmed) ||
|
|
1049
|
+
/^Compile fix applied/i.test(trimmed) ||
|
|
923
1050
|
/^Code saved/i.test(trimmed) ||
|
|
924
1051
|
isBackendCodegenSummary(trimmed)
|
|
925
1052
|
)) {
|
|
@@ -958,7 +1085,8 @@
|
|
|
958
1085
|
isCodegenStatusMessage(content) ||
|
|
959
1086
|
isBackendCodegenSummary(content) ||
|
|
960
1087
|
messageHasWidgetCommit(content) ||
|
|
961
|
-
isCodegenProgressMessage(content)
|
|
1088
|
+
isCodegenProgressMessage(content) ||
|
|
1089
|
+
isCodegenFailureMessage(content)
|
|
962
1090
|
);
|
|
963
1091
|
}
|
|
964
1092
|
|
|
@@ -968,7 +1096,8 @@
|
|
|
968
1096
|
/^Code generation failed/i.test(t) ||
|
|
969
1097
|
/^⚠️/.test(t) ||
|
|
970
1098
|
/Too many generation requests/i.test(t) ||
|
|
971
|
-
/temporarily unavailable/i.test(t)
|
|
1099
|
+
/temporarily unavailable/i.test(t) ||
|
|
1100
|
+
/Generation stopped/i.test(t)
|
|
972
1101
|
);
|
|
973
1102
|
}
|
|
974
1103
|
|
|
@@ -994,7 +1123,7 @@
|
|
|
994
1123
|
rolledBackAt: null,
|
|
995
1124
|
}));
|
|
996
1125
|
chatStore.actions.setMessages(currentConversationId, updated);
|
|
997
|
-
chatLog('[Chat] Widget HEAD marked on message:', headId);
|
|
1126
|
+
// chatLog('[Chat] Widget HEAD marked on message:', headId);
|
|
998
1127
|
}
|
|
999
1128
|
|
|
1000
1129
|
const CODEGEN_STATUS_MESSAGE_REGEX = /^Code generation completed/i;
|
|
@@ -1003,6 +1132,42 @@
|
|
|
1003
1132
|
return CODEGEN_STATUS_MESSAGE_REGEX.test((content || '').trim());
|
|
1004
1133
|
}
|
|
1005
1134
|
|
|
1135
|
+
const persistedCommitKeys: Record<string, true> = {};
|
|
1136
|
+
|
|
1137
|
+
function extractCommitShaFromContent(content: string): string | null {
|
|
1138
|
+
const match = (content || '').match(CODEGEN_COMMIT_REGEX);
|
|
1139
|
+
return match?.[1]?.toLowerCase() ?? null;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
function persistKey(conversationId: string, content: string): string | null {
|
|
1143
|
+
const sha = extractCommitShaFromContent(content);
|
|
1144
|
+
if (!sha) return null;
|
|
1145
|
+
return `${conversationId}:${sha}`;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
function rememberPersistedCommitSha(conversationId: string | null, content: string) {
|
|
1149
|
+
if (!conversationId) return;
|
|
1150
|
+
const key = persistKey(conversationId, content);
|
|
1151
|
+
if (key) persistedCommitKeys[key] = true;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
function persistAssistantCommitOnce(localMessageId: string, content: string) {
|
|
1155
|
+
if (!onSaveMessage || !currentConversationId) return;
|
|
1156
|
+
if (!messageHasWidgetCommit(content)) return;
|
|
1157
|
+
const key = persistKey(currentConversationId, content);
|
|
1158
|
+
if (!key || persistedCommitKeys[key]) return;
|
|
1159
|
+
persistedCommitKeys[key] = true;
|
|
1160
|
+
const convId = currentConversationId;
|
|
1161
|
+
onSaveMessage(convId, content, 'assistant').then(saved => {
|
|
1162
|
+
if (saved?.id && saved.id !== localMessageId) {
|
|
1163
|
+
chatStore.actions.updateMessageId(convId, localMessageId, saved.id);
|
|
1164
|
+
}
|
|
1165
|
+
}).catch(err => {
|
|
1166
|
+
delete persistedCommitKeys[key];
|
|
1167
|
+
chatWarn('[Chat] Failed to persist codegen commit message:', err);
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1006
1171
|
/** One assistant bubble per user turn: loading → ready (in-place update within current turn only). */
|
|
1007
1172
|
function updateLatestCodegenStatusMessage(content: string) {
|
|
1008
1173
|
if (!currentConversationId) return;
|
|
@@ -1033,6 +1198,7 @@
|
|
|
1033
1198
|
// Restore Checkpoint buttons require some message to be HEAD, so we mark eagerly on any commit.
|
|
1034
1199
|
if (messageHasWidgetCommit(content)) {
|
|
1035
1200
|
markWidgetHeadAtLatestCommit(targetId);
|
|
1201
|
+
persistAssistantCommitOnce(targetId, content);
|
|
1036
1202
|
}
|
|
1037
1203
|
return;
|
|
1038
1204
|
}
|
|
@@ -1044,6 +1210,7 @@
|
|
|
1044
1210
|
chatStore.actions.updateMessageContent(currentConversationId, m.id, content);
|
|
1045
1211
|
if (messageHasWidgetCommit(content)) {
|
|
1046
1212
|
markWidgetHeadAtLatestCommit(m.id);
|
|
1213
|
+
persistAssistantCommitOnce(m.id, content);
|
|
1047
1214
|
}
|
|
1048
1215
|
return;
|
|
1049
1216
|
}
|
|
@@ -1061,6 +1228,12 @@
|
|
|
1061
1228
|
const msgs = getCurrentMessages(currentConversationId);
|
|
1062
1229
|
const idx = getLastUserMessageIndex(msgs);
|
|
1063
1230
|
if (idx < 0) return;
|
|
1231
|
+
const last = msgs[idx];
|
|
1232
|
+
const hasRemote = (last.attachments || []).some(
|
|
1233
|
+
(a: { url?: string }) => typeof a.url === 'string' && /^https?:\/\//i.test(a.url),
|
|
1234
|
+
);
|
|
1235
|
+
const incomingHasRemote = attachments.some((a) => /^https?:\/\//i.test(a.url || ''));
|
|
1236
|
+
if (hasRemote && !incomingHasRemote) return;
|
|
1064
1237
|
const mapped = attachments.map((a, i) => ({
|
|
1065
1238
|
id: a.id || `att_${Date.now()}_${i}`,
|
|
1066
1239
|
url: a.url,
|
|
@@ -1071,7 +1244,7 @@
|
|
|
1071
1244
|
created_at: new Date().toISOString(),
|
|
1072
1245
|
}));
|
|
1073
1246
|
chatStore.actions.updateMessageAttachments(currentConversationId, msgs[idx].id, mapped);
|
|
1074
|
-
chatLog('[Chat] Patched last user message attachments:', mapped.length);
|
|
1247
|
+
// chatLog('[Chat] Patched last user message attachments:', mapped.length);
|
|
1075
1248
|
}
|
|
1076
1249
|
|
|
1077
1250
|
/** Reload messages from backend and re-mark widget HEAD (picks up server-persisted summaries). */
|
|
@@ -1084,13 +1257,13 @@
|
|
|
1084
1257
|
const loadedHasHead = (loaded || []).some((m) => messageHasWidgetCommit(m.messageContent));
|
|
1085
1258
|
if (loaded?.length) {
|
|
1086
1259
|
if (localHasHead && !loadedHasHead) {
|
|
1087
|
-
chatLog('[Chat] Keep local HEAD commit message — DB reload has no commit yet');
|
|
1260
|
+
// chatLog('[Chat] Keep local HEAD commit message — DB reload has no commit yet');
|
|
1088
1261
|
} else {
|
|
1089
1262
|
chatStore.actions.setMessages(currentConversationId, loaded);
|
|
1090
1263
|
}
|
|
1091
1264
|
}
|
|
1092
1265
|
markWidgetHeadAtLatestCommit();
|
|
1093
|
-
chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
|
|
1266
|
+
// chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
|
|
1094
1267
|
} catch (err) {
|
|
1095
1268
|
chatWarn('[Chat] Failed to reload conversation messages:', err);
|
|
1096
1269
|
}
|
|
@@ -1107,7 +1280,7 @@
|
|
|
1107
1280
|
if (!/preview build failed/i.test(content)) continue;
|
|
1108
1281
|
const cleaned = content.replace(previewFailedSuffix, '').trim();
|
|
1109
1282
|
chatStore.actions.updateMessageContent(currentConversationId, msg.id, cleaned);
|
|
1110
|
-
chatLog('[Chat] Cleared stale preview build failure from assistant message:', msg.id);
|
|
1283
|
+
// chatLog('[Chat] Cleared stale preview build failure from assistant message:', msg.id);
|
|
1111
1284
|
break;
|
|
1112
1285
|
}
|
|
1113
1286
|
}
|
|
@@ -1173,12 +1346,12 @@
|
|
|
1173
1346
|
|
|
1174
1347
|
// Debug reactive values
|
|
1175
1348
|
$effect(() => {
|
|
1176
|
-
chatLog('Chat render state for', context.id, ':', {
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
});
|
|
1349
|
+
// chatLog('Chat render state for', context.id, ':', {
|
|
1350
|
+
// isInitialized,
|
|
1351
|
+
// chatState: !!chatState,
|
|
1352
|
+
// currentConversationId,
|
|
1353
|
+
// messagesLength: currentMessages?.length || 0
|
|
1354
|
+
// });
|
|
1182
1355
|
});
|
|
1183
1356
|
|
|
1184
1357
|
// ── Messages area vertical resize ────────────────────────────────────
|
|
@@ -1266,88 +1439,81 @@
|
|
|
1266
1439
|
{/if}
|
|
1267
1440
|
|
|
1268
1441
|
<!-- Chat Interface -->
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
isLoading={isLoading}
|
|
1280
|
-
{context}
|
|
1281
|
-
isCompleted={isCompleted}
|
|
1282
|
-
enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
|
|
1283
|
-
showGenerationSummaries={config?.features?.showGenerationSummaries === true}
|
|
1284
|
-
onSuggestionSelected={handleSuggestionSelected}
|
|
1285
|
-
onRestoreCheckpoint={handleRestoreCheckpoint}
|
|
1286
|
-
onRetryMessage={handleRetryMessage}
|
|
1287
|
-
/>
|
|
1288
|
-
</div>
|
|
1289
|
-
|
|
1290
|
-
<div
|
|
1291
|
-
class="prompt-chat-messages-resize-handle flex items-center justify-center cursor-ns-resize select-none group border-t border-b border-transparent hover:border-gray-300 hover:bg-gray-100/80 transition-colors"
|
|
1292
|
-
class:bg-blue-100={isResizingMessages}
|
|
1293
|
-
class:border-blue-300={isResizingMessages}
|
|
1294
|
-
style="height: 16px; touch-action: none; padding: 4px 0;"
|
|
1295
|
-
onpointerdown={handleMessagesResizeStart}
|
|
1296
|
-
role="separator"
|
|
1297
|
-
aria-orientation="horizontal"
|
|
1298
|
-
aria-label="Resize messages area"
|
|
1299
|
-
title="Drag to resize messages area"
|
|
1300
|
-
>
|
|
1301
|
-
<div class="drag-grip w-10 h-1 rounded-full bg-gray-300 group-hover:bg-gray-500 group-hover:w-14 transition-all {isResizingMessages ? 'bg-blue-400 w-14' : ''}"></div>
|
|
1302
|
-
</div>
|
|
1303
|
-
|
|
1304
|
-
<ActionBar
|
|
1442
|
+
<div
|
|
1443
|
+
class="prompt-chat-messages-area flex min-h-0 flex-col overflow-hidden"
|
|
1444
|
+
style="{messagesAreaHeight !== null
|
|
1445
|
+
? `flex: 0 0 ${messagesAreaHeight}px; height: ${messagesAreaHeight}px;`
|
|
1446
|
+
: 'flex: 1 1 auto; min-height: 0;'}"
|
|
1447
|
+
>
|
|
1448
|
+
<ChatMessages
|
|
1449
|
+
class="prompt-chat-messages h-full"
|
|
1450
|
+
messages={currentMessages || []}
|
|
1451
|
+
isLoading={isLoading}
|
|
1305
1452
|
{context}
|
|
1306
|
-
conversationId={currentConversationId}
|
|
1307
|
-
isRecording={localIsRecording}
|
|
1308
1453
|
isCompleted={isCompleted}
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
on:recordStart={handleRecordStart}
|
|
1316
|
-
on:recordStop={handleRecordStop}
|
|
1317
|
-
on:upload={handleUpload}
|
|
1318
|
-
on:complete={handleComplete}
|
|
1319
|
-
on:error={handleActionError}
|
|
1320
|
-
/>
|
|
1321
|
-
|
|
1322
|
-
<ChatInput
|
|
1323
|
-
value={localInputText}
|
|
1324
|
-
attachments={localAttachments}
|
|
1325
|
-
isRecording={localIsRecording}
|
|
1326
|
-
isSending={localIsSending}
|
|
1327
|
-
isUploading={localIsUploading}
|
|
1328
|
-
onSend={(content, attachmentInputs) => {
|
|
1329
|
-
sendMessage(content, attachmentInputs);
|
|
1330
|
-
}}
|
|
1331
|
-
onInputChange={(text) => {
|
|
1332
|
-
chatLog('Input change for chat', context.id, ':', text);
|
|
1333
|
-
localInputText = text;
|
|
1334
|
-
notifyDraftChange();
|
|
1335
|
-
}}
|
|
1336
|
-
onAttachmentsChange={(attachments) => {
|
|
1337
|
-
chatLog('Attachments change for chat', context.id, ':', attachments.length);
|
|
1338
|
-
localAttachments = attachments;
|
|
1339
|
-
notifyDraftChange();
|
|
1340
|
-
}}
|
|
1454
|
+
enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
|
|
1455
|
+
showGenerationSummaries={config?.features?.showGenerationSummaries === true}
|
|
1456
|
+
widgetHeadCommitSha={widgetHeadCommitSha}
|
|
1457
|
+
onSuggestionSelected={handleSuggestionSelected}
|
|
1458
|
+
onRestoreCheckpoint={handleRestoreCheckpoint}
|
|
1459
|
+
onRetryMessage={handleRetryMessage}
|
|
1341
1460
|
/>
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1461
|
+
</div>
|
|
1462
|
+
|
|
1463
|
+
<div
|
|
1464
|
+
class="prompt-chat-messages-resize-handle flex items-center justify-center cursor-ns-resize select-none border-t border-b border-gray-300 bg-gray-100"
|
|
1465
|
+
class:bg-blue-100={isResizingMessages}
|
|
1466
|
+
class:border-blue-300={isResizingMessages}
|
|
1467
|
+
style="height: 16px; touch-action: none; padding: 4px 0;"
|
|
1468
|
+
onpointerdown={handleMessagesResizeStart}
|
|
1469
|
+
role="separator"
|
|
1470
|
+
aria-orientation="horizontal"
|
|
1471
|
+
aria-label="Resize messages area"
|
|
1472
|
+
title="Drag to resize messages area"
|
|
1473
|
+
>
|
|
1474
|
+
<div class="drag-grip w-14 h-1 rounded-full bg-gray-500 {isResizingMessages ? 'bg-blue-400' : ''}"></div>
|
|
1475
|
+
</div>
|
|
1476
|
+
|
|
1477
|
+
<ActionBar
|
|
1478
|
+
{context}
|
|
1479
|
+
conversationId={currentConversationId}
|
|
1480
|
+
isRecording={localIsRecording}
|
|
1481
|
+
isCompleted={isCompleted}
|
|
1482
|
+
disabled={isLoading}
|
|
1483
|
+
showScreenshot={config?.features?.screenshot !== false}
|
|
1484
|
+
showRecord={config?.features?.screenRecording !== false}
|
|
1485
|
+
showUpload={config?.features?.fileUpload !== false}
|
|
1486
|
+
showComplete={config?.features?.markComplete !== false}
|
|
1487
|
+
on:screenshot={handleScreenshot}
|
|
1488
|
+
on:recordStart={handleRecordStart}
|
|
1489
|
+
on:recordStop={handleRecordStop}
|
|
1490
|
+
on:upload={handleUpload}
|
|
1491
|
+
on:complete={handleComplete}
|
|
1492
|
+
on:error={handleActionError}
|
|
1493
|
+
/>
|
|
1494
|
+
|
|
1495
|
+
<ChatInput
|
|
1496
|
+
value={localInputText}
|
|
1497
|
+
attachments={localAttachments}
|
|
1498
|
+
isRecording={localIsRecording}
|
|
1499
|
+
isSending={localIsSending}
|
|
1500
|
+
isUploading={localIsUploading}
|
|
1501
|
+
isGenerating={isGenerating || isLoading}
|
|
1502
|
+
onStop={() => onStopGeneration?.()}
|
|
1503
|
+
onSend={(content, attachmentInputs) => {
|
|
1504
|
+
sendMessage(content, attachmentInputs);
|
|
1505
|
+
}}
|
|
1506
|
+
onInputChange={(text) => {
|
|
1507
|
+
// chatLog('Input change for chat', context.id, ':', text);
|
|
1508
|
+
localInputText = text;
|
|
1509
|
+
notifyDraftChange();
|
|
1510
|
+
}}
|
|
1511
|
+
onAttachmentsChange={(attachments) => {
|
|
1512
|
+
// chatLog('Attachments change for chat', context.id, ':', attachments.length);
|
|
1513
|
+
localAttachments = attachments;
|
|
1514
|
+
notifyDraftChange();
|
|
1515
|
+
}}
|
|
1516
|
+
/>
|
|
1351
1517
|
|
|
1352
1518
|
<!-- Error Display -->
|
|
1353
1519
|
{#if ui?.errorMessage}
|