@widgetic/chat 0.1.6 → 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 +5 -5
- package/dist/components/AttachmentDisplay.svelte +16 -5
- package/dist/components/Chat.svelte +366 -204
- package/dist/components/Chat.svelte.d.ts +10 -1
- 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/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';
|
|
@@ -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,17 +795,17 @@
|
|
|
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
|
-
|
|
712
|
-
|
|
713
|
-
});
|
|
805
|
+
// chatLog('Conversation completion toggle requested', {
|
|
806
|
+
// conversationId: currentConversationId,
|
|
807
|
+
// completed: detail?.completed,
|
|
808
|
+
// });
|
|
714
809
|
|
|
715
810
|
if (!currentConversationId) {
|
|
716
811
|
console.error('No active conversation to mark as complete');
|
|
@@ -723,7 +818,7 @@
|
|
|
723
818
|
conversationId: currentConversationId,
|
|
724
819
|
completed: detail?.completed,
|
|
725
820
|
});
|
|
726
|
-
chatLog('Completion toggled via parent callback');
|
|
821
|
+
// chatLog('Completion toggled via parent callback');
|
|
727
822
|
} else {
|
|
728
823
|
chatWarn('No onCompletionToggle callback provided');
|
|
729
824
|
}
|
|
@@ -743,7 +838,7 @@
|
|
|
743
838
|
}
|
|
744
839
|
|
|
745
840
|
async function handleSuggestionSelected(suggestion: string) {
|
|
746
|
-
chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
|
|
841
|
+
// chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
|
|
747
842
|
// Autocomplete into input instead of sending immediately — lets user review,
|
|
748
843
|
// edit, and attach an image before sending (e.g. "Generate code from this design"
|
|
749
844
|
// is useless without an attached screenshot).
|
|
@@ -753,7 +848,7 @@
|
|
|
753
848
|
async function handleRetryMessage(content: string) {
|
|
754
849
|
const retryContent = content.trim();
|
|
755
850
|
if (!retryContent) return;
|
|
756
|
-
chatLog('[Chat] Retrying failed message:', retryContent.slice(0, 80));
|
|
851
|
+
// chatLog('[Chat] Retrying failed message:', retryContent.slice(0, 80));
|
|
757
852
|
if (onRetryMessage) {
|
|
758
853
|
await onRetryMessage(retryContent);
|
|
759
854
|
return;
|
|
@@ -762,7 +857,7 @@
|
|
|
762
857
|
}
|
|
763
858
|
|
|
764
859
|
async function handleRestoreCheckpoint(messageId: string, messageIndex: number) {
|
|
765
|
-
chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
|
|
860
|
+
// chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
|
|
766
861
|
|
|
767
862
|
if (!currentConversationId || !currentMessages) {
|
|
768
863
|
console.error('No active conversation or messages to restore');
|
|
@@ -770,21 +865,32 @@
|
|
|
770
865
|
}
|
|
771
866
|
|
|
772
867
|
try {
|
|
773
|
-
const clicked =
|
|
774
|
-
|
|
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;
|
|
775
880
|
let headAssistantId = clicked?.id;
|
|
776
881
|
|
|
777
882
|
// API rolls back to the commit produced by the user prompt before this assistant reply.
|
|
778
883
|
if (clicked?.messageType === 'assistant') {
|
|
779
884
|
headAssistantId = clicked.id;
|
|
780
|
-
for (let i =
|
|
885
|
+
for (let i = resolvedIndex - 1; i >= 0; i--) {
|
|
781
886
|
if (currentMessages[i].messageType === 'user') {
|
|
782
887
|
checkpointUserId = currentMessages[i].id;
|
|
783
888
|
break;
|
|
784
889
|
}
|
|
785
890
|
}
|
|
786
891
|
} else {
|
|
787
|
-
|
|
892
|
+
checkpointUserId = clicked.id;
|
|
893
|
+
for (let i = resolvedIndex + 1; i < currentMessages.length; i++) {
|
|
788
894
|
if (currentMessages[i].messageType === 'assistant' && messageHasWidgetCommit(currentMessages[i].messageContent)) {
|
|
789
895
|
headAssistantId = currentMessages[i].id;
|
|
790
896
|
break;
|
|
@@ -798,13 +904,13 @@
|
|
|
798
904
|
rolledBackAt: null,
|
|
799
905
|
}));
|
|
800
906
|
|
|
801
|
-
chatLog(`Restoring to checkpoint user message ${checkpointUserId}, head assistant ${headAssistantId}`);
|
|
907
|
+
// chatLog(`Restoring to checkpoint user message ${checkpointUserId}, head assistant ${headAssistantId}`);
|
|
802
908
|
chatStore.actions.setMessages(currentConversationId, updatedMessages);
|
|
803
909
|
|
|
804
910
|
if (onRestoreCheckpointBackend) {
|
|
805
911
|
try {
|
|
806
912
|
const result = await onRestoreCheckpointBackend(currentConversationId, checkpointUserId);
|
|
807
|
-
chatLog('[Chat] Checkpoint restored on backend:', result);
|
|
913
|
+
// chatLog('[Chat] Checkpoint restored on backend:', result);
|
|
808
914
|
if (headAssistantId) {
|
|
809
915
|
markWidgetHeadAtLatestCommit(headAssistantId);
|
|
810
916
|
}
|
|
@@ -814,7 +920,7 @@
|
|
|
814
920
|
}
|
|
815
921
|
|
|
816
922
|
chatStore.actions.updateUI({ errorMessage: null });
|
|
817
|
-
chatLog('Checkpoint restored successfully');
|
|
923
|
+
// chatLog('Checkpoint restored successfully');
|
|
818
924
|
|
|
819
925
|
} catch (error) {
|
|
820
926
|
console.error('Failed to restore checkpoint:', error);
|
|
@@ -842,13 +948,11 @@
|
|
|
842
948
|
return;
|
|
843
949
|
}
|
|
844
950
|
try {
|
|
845
|
-
const
|
|
951
|
+
const response = await fetch(dataUrl);
|
|
952
|
+
const blob = await response.blob();
|
|
846
953
|
const mimeMatch = dataUrl.match(/data:(image\/[^;]+);/);
|
|
847
|
-
const mimeType = mimeMatch?.[1] || 'image/png';
|
|
848
|
-
const
|
|
849
|
-
const ia = new Uint8Array(ab);
|
|
850
|
-
for (let i = 0; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);
|
|
851
|
-
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 });
|
|
852
956
|
const attachmentInput: AttachmentInput = {
|
|
853
957
|
file,
|
|
854
958
|
type: 'image',
|
|
@@ -861,7 +965,7 @@
|
|
|
861
965
|
if (onUploadChatFile) {
|
|
862
966
|
await uploadAttachmentToCdn(file, attachmentInput, attachmentIndex);
|
|
863
967
|
}
|
|
864
|
-
chatLog('Image attachment added from external paste');
|
|
968
|
+
// chatLog('Image attachment added from external paste');
|
|
865
969
|
} catch (err) {
|
|
866
970
|
console.error('[Chat] Failed to add image attachment:', err);
|
|
867
971
|
}
|
|
@@ -889,6 +993,15 @@
|
|
|
889
993
|
}
|
|
890
994
|
|
|
891
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
|
+
}
|
|
892
1005
|
localAttachments = [];
|
|
893
1006
|
const validUrls = dataUrls.filter(isValidImageDataUrl);
|
|
894
1007
|
for (let i = 0; i < validUrls.length; i++) {
|
|
@@ -900,12 +1013,21 @@
|
|
|
900
1013
|
}
|
|
901
1014
|
|
|
902
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
|
+
}
|
|
903
1025
|
localInputText = '';
|
|
904
1026
|
localAttachments = [];
|
|
905
1027
|
notifyDraftChange();
|
|
906
1028
|
}
|
|
907
1029
|
|
|
908
|
-
const CODEGEN_COMMIT_REGEX = /Commit:?\s
|
|
1030
|
+
const CODEGEN_COMMIT_REGEX = /(?:Commit:?\s+|Code saved\s*\()([a-f0-9]{7,40})/i;
|
|
909
1031
|
|
|
910
1032
|
function isPreviewRecompiledMessage(content?: string | null): boolean {
|
|
911
1033
|
return /^Preview recompiled/i.test((content || '').trim());
|
|
@@ -917,13 +1039,14 @@
|
|
|
917
1039
|
return /^Updated \d+ files?/i.test(trimmed) && /\n\nCommit\s+[a-f0-9]{7,40}/i.test(trimmed);
|
|
918
1040
|
}
|
|
919
1041
|
|
|
920
|
-
/** Widget HEAD: codegen
|
|
1042
|
+
/** Widget HEAD: real codegen commits only — not rebuild-only "Preview recompiled" bubbles. */
|
|
921
1043
|
function messageHasWidgetCommit(content?: string | null): boolean {
|
|
922
1044
|
const trimmed = (content || '').trim();
|
|
923
1045
|
if (!trimmed || isCodegenFailureMessage(trimmed)) return false;
|
|
924
|
-
if (isPreviewRecompiledMessage(trimmed)
|
|
1046
|
+
if (isPreviewRecompiledMessage(trimmed)) return false;
|
|
925
1047
|
if (CODEGEN_COMMIT_REGEX.test(trimmed) && (
|
|
926
1048
|
/^Code generation completed/i.test(trimmed) ||
|
|
1049
|
+
/^Compile fix applied/i.test(trimmed) ||
|
|
927
1050
|
/^Code saved/i.test(trimmed) ||
|
|
928
1051
|
isBackendCodegenSummary(trimmed)
|
|
929
1052
|
)) {
|
|
@@ -962,7 +1085,8 @@
|
|
|
962
1085
|
isCodegenStatusMessage(content) ||
|
|
963
1086
|
isBackendCodegenSummary(content) ||
|
|
964
1087
|
messageHasWidgetCommit(content) ||
|
|
965
|
-
isCodegenProgressMessage(content)
|
|
1088
|
+
isCodegenProgressMessage(content) ||
|
|
1089
|
+
isCodegenFailureMessage(content)
|
|
966
1090
|
);
|
|
967
1091
|
}
|
|
968
1092
|
|
|
@@ -972,7 +1096,8 @@
|
|
|
972
1096
|
/^Code generation failed/i.test(t) ||
|
|
973
1097
|
/^⚠️/.test(t) ||
|
|
974
1098
|
/Too many generation requests/i.test(t) ||
|
|
975
|
-
/temporarily unavailable/i.test(t)
|
|
1099
|
+
/temporarily unavailable/i.test(t) ||
|
|
1100
|
+
/Generation stopped/i.test(t)
|
|
976
1101
|
);
|
|
977
1102
|
}
|
|
978
1103
|
|
|
@@ -998,7 +1123,7 @@
|
|
|
998
1123
|
rolledBackAt: null,
|
|
999
1124
|
}));
|
|
1000
1125
|
chatStore.actions.setMessages(currentConversationId, updated);
|
|
1001
|
-
chatLog('[Chat] Widget HEAD marked on message:', headId);
|
|
1126
|
+
// chatLog('[Chat] Widget HEAD marked on message:', headId);
|
|
1002
1127
|
}
|
|
1003
1128
|
|
|
1004
1129
|
const CODEGEN_STATUS_MESSAGE_REGEX = /^Code generation completed/i;
|
|
@@ -1007,6 +1132,42 @@
|
|
|
1007
1132
|
return CODEGEN_STATUS_MESSAGE_REGEX.test((content || '').trim());
|
|
1008
1133
|
}
|
|
1009
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
|
+
|
|
1010
1171
|
/** One assistant bubble per user turn: loading → ready (in-place update within current turn only). */
|
|
1011
1172
|
function updateLatestCodegenStatusMessage(content: string) {
|
|
1012
1173
|
if (!currentConversationId) return;
|
|
@@ -1037,6 +1198,7 @@
|
|
|
1037
1198
|
// Restore Checkpoint buttons require some message to be HEAD, so we mark eagerly on any commit.
|
|
1038
1199
|
if (messageHasWidgetCommit(content)) {
|
|
1039
1200
|
markWidgetHeadAtLatestCommit(targetId);
|
|
1201
|
+
persistAssistantCommitOnce(targetId, content);
|
|
1040
1202
|
}
|
|
1041
1203
|
return;
|
|
1042
1204
|
}
|
|
@@ -1048,6 +1210,7 @@
|
|
|
1048
1210
|
chatStore.actions.updateMessageContent(currentConversationId, m.id, content);
|
|
1049
1211
|
if (messageHasWidgetCommit(content)) {
|
|
1050
1212
|
markWidgetHeadAtLatestCommit(m.id);
|
|
1213
|
+
persistAssistantCommitOnce(m.id, content);
|
|
1051
1214
|
}
|
|
1052
1215
|
return;
|
|
1053
1216
|
}
|
|
@@ -1065,6 +1228,12 @@
|
|
|
1065
1228
|
const msgs = getCurrentMessages(currentConversationId);
|
|
1066
1229
|
const idx = getLastUserMessageIndex(msgs);
|
|
1067
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;
|
|
1068
1237
|
const mapped = attachments.map((a, i) => ({
|
|
1069
1238
|
id: a.id || `att_${Date.now()}_${i}`,
|
|
1070
1239
|
url: a.url,
|
|
@@ -1075,7 +1244,7 @@
|
|
|
1075
1244
|
created_at: new Date().toISOString(),
|
|
1076
1245
|
}));
|
|
1077
1246
|
chatStore.actions.updateMessageAttachments(currentConversationId, msgs[idx].id, mapped);
|
|
1078
|
-
chatLog('[Chat] Patched last user message attachments:', mapped.length);
|
|
1247
|
+
// chatLog('[Chat] Patched last user message attachments:', mapped.length);
|
|
1079
1248
|
}
|
|
1080
1249
|
|
|
1081
1250
|
/** Reload messages from backend and re-mark widget HEAD (picks up server-persisted summaries). */
|
|
@@ -1088,13 +1257,13 @@
|
|
|
1088
1257
|
const loadedHasHead = (loaded || []).some((m) => messageHasWidgetCommit(m.messageContent));
|
|
1089
1258
|
if (loaded?.length) {
|
|
1090
1259
|
if (localHasHead && !loadedHasHead) {
|
|
1091
|
-
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');
|
|
1092
1261
|
} else {
|
|
1093
1262
|
chatStore.actions.setMessages(currentConversationId, loaded);
|
|
1094
1263
|
}
|
|
1095
1264
|
}
|
|
1096
1265
|
markWidgetHeadAtLatestCommit();
|
|
1097
|
-
chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
|
|
1266
|
+
// chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
|
|
1098
1267
|
} catch (err) {
|
|
1099
1268
|
chatWarn('[Chat] Failed to reload conversation messages:', err);
|
|
1100
1269
|
}
|
|
@@ -1111,7 +1280,7 @@
|
|
|
1111
1280
|
if (!/preview build failed/i.test(content)) continue;
|
|
1112
1281
|
const cleaned = content.replace(previewFailedSuffix, '').trim();
|
|
1113
1282
|
chatStore.actions.updateMessageContent(currentConversationId, msg.id, cleaned);
|
|
1114
|
-
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);
|
|
1115
1284
|
break;
|
|
1116
1285
|
}
|
|
1117
1286
|
}
|
|
@@ -1177,12 +1346,12 @@
|
|
|
1177
1346
|
|
|
1178
1347
|
// Debug reactive values
|
|
1179
1348
|
$effect(() => {
|
|
1180
|
-
chatLog('Chat render state for', context.id, ':', {
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
});
|
|
1349
|
+
// chatLog('Chat render state for', context.id, ':', {
|
|
1350
|
+
// isInitialized,
|
|
1351
|
+
// chatState: !!chatState,
|
|
1352
|
+
// currentConversationId,
|
|
1353
|
+
// messagesLength: currentMessages?.length || 0
|
|
1354
|
+
// });
|
|
1186
1355
|
});
|
|
1187
1356
|
|
|
1188
1357
|
// ── Messages area vertical resize ────────────────────────────────────
|
|
@@ -1270,88 +1439,81 @@
|
|
|
1270
1439
|
{/if}
|
|
1271
1440
|
|
|
1272
1441
|
<!-- Chat Interface -->
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
isLoading={isLoading}
|
|
1284
|
-
{context}
|
|
1285
|
-
isCompleted={isCompleted}
|
|
1286
|
-
enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
|
|
1287
|
-
showGenerationSummaries={config?.features?.showGenerationSummaries === true}
|
|
1288
|
-
onSuggestionSelected={handleSuggestionSelected}
|
|
1289
|
-
onRestoreCheckpoint={handleRestoreCheckpoint}
|
|
1290
|
-
onRetryMessage={handleRetryMessage}
|
|
1291
|
-
/>
|
|
1292
|
-
</div>
|
|
1293
|
-
|
|
1294
|
-
<div
|
|
1295
|
-
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"
|
|
1296
|
-
class:bg-blue-100={isResizingMessages}
|
|
1297
|
-
class:border-blue-300={isResizingMessages}
|
|
1298
|
-
style="height: 16px; touch-action: none; padding: 4px 0;"
|
|
1299
|
-
onpointerdown={handleMessagesResizeStart}
|
|
1300
|
-
role="separator"
|
|
1301
|
-
aria-orientation="horizontal"
|
|
1302
|
-
aria-label="Resize messages area"
|
|
1303
|
-
title="Drag to resize messages area"
|
|
1304
|
-
>
|
|
1305
|
-
<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>
|
|
1306
|
-
</div>
|
|
1307
|
-
|
|
1308
|
-
<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}
|
|
1309
1452
|
{context}
|
|
1310
|
-
conversationId={currentConversationId}
|
|
1311
|
-
isRecording={localIsRecording}
|
|
1312
1453
|
isCompleted={isCompleted}
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
on:recordStart={handleRecordStart}
|
|
1320
|
-
on:recordStop={handleRecordStop}
|
|
1321
|
-
on:upload={handleUpload}
|
|
1322
|
-
on:complete={handleComplete}
|
|
1323
|
-
on:error={handleActionError}
|
|
1324
|
-
/>
|
|
1325
|
-
|
|
1326
|
-
<ChatInput
|
|
1327
|
-
value={localInputText}
|
|
1328
|
-
attachments={localAttachments}
|
|
1329
|
-
isRecording={localIsRecording}
|
|
1330
|
-
isSending={localIsSending}
|
|
1331
|
-
isUploading={localIsUploading}
|
|
1332
|
-
onSend={(content, attachmentInputs) => {
|
|
1333
|
-
sendMessage(content, attachmentInputs);
|
|
1334
|
-
}}
|
|
1335
|
-
onInputChange={(text) => {
|
|
1336
|
-
chatLog('Input change for chat', context.id, ':', text);
|
|
1337
|
-
localInputText = text;
|
|
1338
|
-
notifyDraftChange();
|
|
1339
|
-
}}
|
|
1340
|
-
onAttachmentsChange={(attachments) => {
|
|
1341
|
-
chatLog('Attachments change for chat', context.id, ':', attachments.length);
|
|
1342
|
-
localAttachments = attachments;
|
|
1343
|
-
notifyDraftChange();
|
|
1344
|
-
}}
|
|
1454
|
+
enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
|
|
1455
|
+
showGenerationSummaries={config?.features?.showGenerationSummaries === true}
|
|
1456
|
+
widgetHeadCommitSha={widgetHeadCommitSha}
|
|
1457
|
+
onSuggestionSelected={handleSuggestionSelected}
|
|
1458
|
+
onRestoreCheckpoint={handleRestoreCheckpoint}
|
|
1459
|
+
onRetryMessage={handleRetryMessage}
|
|
1345
1460
|
/>
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
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
|
+
/>
|
|
1355
1517
|
|
|
1356
1518
|
<!-- Error Display -->
|
|
1357
1519
|
{#if ui?.errorMessage}
|