@widgetic/chat 0.1.6 → 0.1.8

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.
@@ -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[]) => Promise<void>;
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>(null);
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
- for (const conversation of conversations) {
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
- if (messageList.length > 0) {
186
- currentConversationId = conversationId;
187
- markWidgetHeadAtLatestCommit();
188
- chatLog('[Chat] Restored conversation with history:', conversationId, messageList.length, 'messages');
189
- return;
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;
191
212
  }
192
213
 
193
- const fallbackConversation = conversations[0];
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;
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;
238
+ }
239
+
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
- let loaded: any[] | null = null;
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(async () => {
252
- try {
253
- await initializeForContext(context.id);
254
- isInitialized = true;
255
- } catch (error) {
256
- console.error('[Chat] Failed to initialize:', error);
257
- chatStore.actions.updateUI({
258
- errorMessage: 'Failed to initialize chat. Please try again.',
259
- });
260
- isInitialized = true;
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 = [...prevMsgs].reverse().find(
272
- (m: any) => m.messageType === 'user' && Array.isArray(m.attachments) && m.attachments.length > 0,
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 nextMsgs = getCurrentMessages(currentConversationId) || [];
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
  });
@@ -313,13 +362,19 @@
313
362
  const conversation = onCreateConversation
314
363
  ? await onCreateConversation(context.id, defaultTitle)
315
364
  : await chatService.createConversation(context.id, { title: defaultTitle });
316
-
365
+
366
+ const conversationId =
367
+ conversation && typeof conversation.id === 'string' ? conversation.id.trim() : '';
368
+ if (!conversation || !conversationId) {
369
+ throw new Error('Failed to create conversation');
370
+ }
371
+
317
372
  chatStore.dispatch({
318
373
  type: 'ADD_CONVERSATION',
319
374
  payload: { contextId: context.id, conversation }
320
375
  });
321
-
322
- currentConversationId = conversation.id;
376
+
377
+ currentConversationId = conversationId;
323
378
  return conversation;
324
379
  } catch (error) {
325
380
  console.error('Failed to create conversation:', error);
@@ -347,15 +402,52 @@
347
402
  }
348
403
  }
349
404
 
350
- async function sendMessage(content: string, attachments?: AttachmentInput[]) {
405
+ async function sendMessage(content: string, attachments?: Array<File | AttachmentInput>) {
351
406
  if (!currentConversationId) {
407
+ if (initializePromise) {
408
+ try {
409
+ await initializePromise;
410
+ } catch {
411
+ /* ignore error, fallback to creating below */
412
+ }
413
+ }
414
+ if (!currentConversationId) {
415
+ try {
416
+ await createNewConversation();
417
+ } catch (convErr) {
418
+ console.error('No active conversation and failed to create one:', convErr);
419
+ return;
420
+ }
421
+ if (!currentConversationId) {
422
+ console.error('No active conversation after create');
423
+ return;
424
+ }
425
+ }
426
+ }
427
+
428
+ const activeConversationId = currentConversationId;
429
+ if (!activeConversationId) {
352
430
  console.error('No active conversation');
353
431
  return;
354
432
  }
355
433
 
356
- chatLog('[Chat] Sending message:', content.substring(0, 60));
434
+ const normalizedAttachments: AttachmentInput[] = (attachments || []).map((att) => {
435
+ if (att instanceof File) {
436
+ const isImage = att.type.startsWith('image/');
437
+ const isVideo = att.type.startsWith('video/');
438
+ return {
439
+ file: att,
440
+ type: isImage ? 'image' : isVideo ? 'video' : 'document',
441
+ preview: isImage || isVideo || att.type === 'application/pdf' ? URL.createObjectURL(att) : undefined,
442
+ uploadProgress: 0,
443
+ };
444
+ }
445
+ return att;
446
+ });
447
+
448
+ // chatLog('[Chat] Sending message:', content.substring(0, 60));
357
449
  const submittedContent = content;
358
- const submittedAttachments = attachments;
450
+ const submittedAttachments = normalizedAttachments;
359
451
 
360
452
  try {
361
453
  localIsSending = true;
@@ -367,22 +459,22 @@
367
459
  notifyDraftChange();
368
460
 
369
461
  // Clear head/checkpoint marks — new prompt starts a new turn
370
- const existingMsgs = getCurrentMessages(currentConversationId);
462
+ const existingMsgs = getCurrentMessages(activeConversationId);
371
463
  if (existingMsgs?.some((m: any) => m.rolledBackAt || m.isWidgetHead)) {
372
464
  const cleared = existingMsgs.map((m: any) => ({
373
465
  ...m,
374
466
  rolledBackAt: null,
375
467
  isWidgetHead: false,
376
468
  }));
377
- chatStore.actions.setMessages(currentConversationId, cleared);
469
+ chatStore.actions.setMessages(activeConversationId, cleared);
378
470
  }
379
471
 
380
472
  // Add user message to the UI immediately (local mock for instant feedback)
381
- const userMessage = await chatService.sendMessage(currentConversationId, {
473
+ const userMessage = await chatService.sendMessage(activeConversationId, {
382
474
  messageContent: submittedContent,
383
475
  attachments: submittedAttachments
384
476
  });
385
- chatStore.actions.addMessage(currentConversationId, userMessage);
477
+ chatStore.actions.addMessage(activeConversationId, userMessage);
386
478
 
387
479
  // Persist user message to backend and update local ID with DB UUID
388
480
  if (onSaveMessage) {
@@ -396,18 +488,18 @@
396
488
  display_order: i + 1,
397
489
  })).filter((att: { url?: string; file?: File }) => !!att.url || att.file instanceof File);
398
490
  const saved = await onSaveMessage(
399
- currentConversationId,
491
+ activeConversationId,
400
492
  submittedContent,
401
493
  'user',
402
494
  persistAttachments.length > 0 ? persistAttachments : userMessage.attachments,
403
495
  );
404
496
  if (saved?.id && saved.id !== userMessage.id) {
405
- chatStore.actions.updateMessageId(currentConversationId, userMessage.id, saved.id);
497
+ chatStore.actions.updateMessageId(activeConversationId, userMessage.id, saved.id);
406
498
  }
407
499
  const savedAttachments = saved?.attachments || saved?.data?.attachments;
408
500
  if (Array.isArray(savedAttachments) && savedAttachments.length > 0) {
409
501
  const targetId = saved?.id || userMessage.id;
410
- chatStore.actions.updateMessageAttachments(currentConversationId, targetId, savedAttachments);
502
+ chatStore.actions.updateMessageAttachments(activeConversationId, targetId, savedAttachments);
411
503
  }
412
504
  } catch (err) {
413
505
  chatWarn('[Chat] Failed to persist user message:', err);
@@ -419,14 +511,14 @@
419
511
  file: att.file,
420
512
  url: att.uploadedUrl || att.preview,
421
513
  uploadId: att.uploadId,
422
- fileType: att.file.type,
423
- fileName: att.file.name,
424
- fileSize: att.file.size,
514
+ fileType: att.file?.type || 'application/octet-stream',
515
+ fileName: att.file?.name || 'attachment',
516
+ fileSize: att.file?.size,
425
517
  }));
426
518
  await onSendMessage(submittedContent, outgoing.length > 0 ? outgoing : undefined);
427
519
  } else {
428
- const aiResponse = await chatService.processAIResponse(currentConversationId, userMessage);
429
- chatStore.actions.addMessage(currentConversationId, aiResponse);
520
+ const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
521
+ chatStore.actions.addMessage(activeConversationId, aiResponse);
430
522
  }
431
523
 
432
524
  } catch (error) {
@@ -462,10 +554,7 @@
462
554
 
463
555
  // Mark HEAD as soon as an assistant message carries a widget commit — this makes the
464
556
  // 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
- ) {
557
+ if (messageHasWidgetCommit(content)) {
469
558
  markWidgetHeadAtLatestCommit(assistantMsg.id);
470
559
  }
471
560
 
@@ -475,9 +564,12 @@
475
564
  if (saved?.id && saved.id !== assistantMsg.id) {
476
565
  chatStore.actions.updateMessageId(convId, assistantMsg.id, saved.id);
477
566
  }
567
+ rememberPersistedCommitSha(convId, content);
478
568
  }).catch(err =>
479
569
  chatWarn('[Chat] Failed to persist assistant message:', err)
480
570
  );
571
+ } else if (skipPersist && messageHasWidgetCommit(content)) {
572
+ persistAssistantCommitOnce(assistantMsg.id, content);
481
573
  }
482
574
  }
483
575
 
@@ -485,12 +577,18 @@
485
577
  * Also persists to DB via onSaveMessage so multi-turn history is complete. */
486
578
  function addUserMessage(content: string, attachments?: Array<{ id: string; url: string; file_type: string; file_name: string; file_size?: number }>) {
487
579
  if (!currentConversationId) return;
580
+ const mappedAttachments = (attachments || []).map((att, index) => ({
581
+ ...att,
582
+ file_size: att.file_size ?? null,
583
+ display_order: index + 1,
584
+ created_at: new Date().toISOString(),
585
+ }));
488
586
  const userMsg = {
489
587
  id: `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
490
588
  conversationId: currentConversationId,
491
589
  messageContent: content,
492
590
  messageType: 'user' as const,
493
- attachments: attachments || [],
591
+ attachments: mappedAttachments,
494
592
  isCommit: false,
495
593
  userId: 'current_user',
496
594
  createdAt: new Date(),
@@ -503,7 +601,7 @@
503
601
 
504
602
  if (onSaveMessage) {
505
603
  const convId = currentConversationId;
506
- onSaveMessage(convId, content, 'user', attachments).then(saved => {
604
+ onSaveMessage(convId, content, 'user', mappedAttachments).then(saved => {
507
605
  if (saved?.id && saved.id !== userMsg.id) {
508
606
  chatStore.actions.updateMessageId(convId, userMsg.id, saved.id);
509
607
  }
@@ -513,9 +611,9 @@
513
611
  }
514
612
  }
515
613
 
516
- // ActionBar event handlers
517
- async function handleScreenshot({ detail }: { detail: { contextId: string } }) {
518
- chatLog('[Chat] Screenshot requested for context:', detail.contextId);
614
+ // ActionBar callback handlers (Svelte 5 — no createEventDispatcher)
615
+ async function handleScreenshot() {
616
+ // chatLog('[Chat] Screenshot requested for context:', context.id);
519
617
 
520
618
  try {
521
619
  let screenshotDataUrl: string | null = null;
@@ -545,6 +643,9 @@
545
643
  localAttachments = [...localAttachments, attachmentInput];
546
644
  const attachmentIndex = localAttachments.length - 1;
547
645
  notifyDraftChange();
646
+ expandChatForAttachmentGrowth(attachmentIndex);
647
+ chatStore.actions.updateUI({ errorMessage: null });
648
+ console.log('[Chat] attachments now', localAttachments.length);
548
649
 
549
650
  if (onUploadChatFile) {
550
651
  await uploadAttachmentToCdn(screenshotFile, attachmentInput, attachmentIndex, {
@@ -552,7 +653,7 @@
552
653
  });
553
654
  }
554
655
 
555
- chatLog('Screenshot captured and added to attachments');
656
+ // chatLog('Screenshot captured and added to attachments');
556
657
  } catch (error) {
557
658
  console.error('Screenshot capture failed:', error);
558
659
  chatStore.actions.updateUI({
@@ -561,14 +662,14 @@
561
662
  }
562
663
  }
563
664
 
564
- async function handleRecordStart({ detail }: { detail: { contextId: string } }) {
565
- chatLog('Recording start requested for context:', detail.contextId);
665
+ async function handleRecordStart() {
666
+ // chatLog('Recording start requested for context:', context.id);
566
667
 
567
668
  try {
568
669
  localIsRecording = true;
569
670
 
570
671
  // This would integrate with the existing recording module
571
- chatLog('Recording started...');
672
+ // chatLog('Recording started...');
572
673
 
573
674
  } catch (error) {
574
675
  console.error('Failed to start recording:', error);
@@ -579,8 +680,8 @@
579
680
  }
580
681
  }
581
682
 
582
- async function handleRecordStop({ detail }: { detail: { contextId: string } }) {
583
- chatLog('Recording stop requested for context:', detail.contextId);
683
+ async function handleRecordStop() {
684
+ // chatLog('Recording stop requested for context:', context.id);
584
685
 
585
686
  try {
586
687
  localIsRecording = false;
@@ -599,8 +700,9 @@
599
700
 
600
701
  // Add to attachments
601
702
  localAttachments = [...localAttachments, attachmentInput];
703
+ console.log('[Chat] attachments now', localAttachments.length);
602
704
 
603
- chatLog('Recording stopped and added to attachments');
705
+ // chatLog('Recording stopped and added to attachments');
604
706
 
605
707
  } catch (error) {
606
708
  console.error('Failed to stop recording:', error);
@@ -642,13 +744,20 @@
642
744
  entry.uploadedUrl = uploaded.url;
643
745
  entry.uploadId = uploaded.id;
644
746
  if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
747
+ if (entry.preview && entry.preview.startsWith('blob:')) {
748
+ try {
749
+ URL.revokeObjectURL(entry.preview);
750
+ } catch {
751
+ /* ignore error */
752
+ }
753
+ }
645
754
  entry.preview = uploaded.url;
646
755
  }
647
756
  entry.uploadProgress = 100;
648
757
  bumpAttachmentProgress(attachmentIndex, 100);
649
758
  localAttachments = [...localAttachments];
650
759
  notifyDraftChange();
651
- chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
760
+ // chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
652
761
  } catch (uploadError) {
653
762
  console.error('[Chat] Upload failed, using local preview where possible:', uploadError);
654
763
  if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
@@ -663,8 +772,92 @@
663
772
  }
664
773
  }
665
774
 
775
+ function expandChatForAttachmentGrowth(previousCount: number) {
776
+ if (localAttachments.length <= previousCount) return;
777
+
778
+ // When the first attachment appears, free space in a fixed messages area so the footer tray stays visible.
779
+ if (previousCount === 0 && messagesAreaHeight !== null) {
780
+ messagesAreaHeight = Math.max(120, messagesAreaHeight - 120);
781
+ }
782
+
783
+ if (!resizeExpandsContainer) return;
784
+ // Grow the fixed-height host once per net attachment increase so the tray is not clipped.
785
+ onMessagesResize?.(120);
786
+ chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', localAttachments.length);
787
+ }
788
+
789
+ function isImageAttachment(attachment: AttachmentInput): boolean {
790
+ return (
791
+ attachment.type === 'image' ||
792
+ !!attachment.file?.type?.startsWith('image/')
793
+ );
794
+ }
795
+
796
+ function getFooterAttachmentPreviewUrl(attachment: AttachmentInput): string {
797
+ if (attachment.preview) return attachment.preview;
798
+ if (attachment.uploadedUrl) return attachment.uploadedUrl;
799
+ if (!attachment.file) return '';
800
+ try {
801
+ const objectUrl = URL.createObjectURL(attachment.file);
802
+ attachment.preview = objectUrl;
803
+ return objectUrl;
804
+ } catch {
805
+ return '';
806
+ }
807
+ }
808
+
809
+ function removeFooterAttachment(index: number) {
810
+ const removed = localAttachments[index];
811
+ if (removed?.preview && removed.preview.startsWith('blob:')) {
812
+ try {
813
+ URL.revokeObjectURL(removed.preview);
814
+ } catch {
815
+ /* ignore error */
816
+ }
817
+ }
818
+ localAttachments = localAttachments.filter((_, i) => i !== index);
819
+ notifyDraftChange();
820
+ chatLog('[Chat] Removed footer attachment at index:', index);
821
+ }
822
+
823
+ let footerLightboxSrc: string | null = $state(null);
824
+
825
+ async function addFilesAsAttachments(files: File[]) {
826
+ const usableFiles = (files || []).filter((file) => file && file.size > 0);
827
+ if (usableFiles.length === 0) return;
828
+
829
+ const previousCount = localAttachments.length;
830
+ const newAttachments: AttachmentInput[] = usableFiles.map((file) => ({
831
+ file,
832
+ type: file.type.startsWith('image/')
833
+ ? 'image'
834
+ : file.type.startsWith('video/')
835
+ ? 'video'
836
+ : 'document',
837
+ uploadProgress: 0,
838
+ }));
839
+
840
+ const startIndex = localAttachments.length;
841
+ localAttachments = [...localAttachments, ...newAttachments];
842
+ notifyDraftChange();
843
+ expandChatForAttachmentGrowth(previousCount);
844
+ chatStore.actions.updateUI({ errorMessage: null });
845
+ console.log('[Chat] attachments now', localAttachments.length);
846
+
847
+ try {
848
+ localIsUploading = true;
849
+ for (let i = 0; i < usableFiles.length; i++) {
850
+ await uploadAttachmentToCdn(usableFiles[i], newAttachments[i], startIndex + i);
851
+ }
852
+ } finally {
853
+ localIsUploading = false;
854
+ }
855
+
856
+ chatLog('[Chat] Files added as attachments:', usableFiles.length);
857
+ }
858
+
666
859
  async function handleUpload() {
667
- chatLog('File upload requested');
860
+ // chatLog('File upload requested');
668
861
 
669
862
  const fileInput = document.createElement('input');
670
863
  fileInput.type = 'file';
@@ -673,44 +866,17 @@
673
866
 
674
867
  fileInput.onchange = async (event) => {
675
868
  const files = Array.from((event.target as HTMLInputElement).files || []);
676
- if (files.length === 0) return;
677
-
678
- const newAttachments: AttachmentInput[] = files.map((file) => ({
679
- file,
680
- type: file.type.startsWith('image/')
681
- ? 'image'
682
- : file.type.startsWith('video/')
683
- ? 'video'
684
- : 'document',
685
- uploadProgress: 0,
686
- }));
687
-
688
- const startIndex = localAttachments.length;
689
- localAttachments = [...localAttachments, ...newAttachments];
690
- notifyDraftChange();
691
-
692
- try {
693
- localIsUploading = true;
694
- for (let i = 0; i < files.length; i++) {
695
- const file = files[i];
696
- const entry = newAttachments[i];
697
- await uploadAttachmentToCdn(file, entry, startIndex + i);
698
- }
699
- } finally {
700
- localIsUploading = false;
701
- }
702
-
703
- chatLog('Files selected via upload:', files.length);
869
+ await addFilesAsAttachments(files);
704
870
  };
705
871
 
706
872
  fileInput.click();
707
873
  }
708
874
 
709
- async function handleComplete({ detail }: { detail: { completed: boolean } }) {
710
- chatLog('Conversation completion toggle requested', {
711
- conversationId: currentConversationId,
712
- completed: detail?.completed,
713
- });
875
+ async function handleComplete(detail: { completed: boolean }) {
876
+ // chatLog('Conversation completion toggle requested', {
877
+ // conversationId: currentConversationId,
878
+ // completed: detail?.completed,
879
+ // });
714
880
 
715
881
  if (!currentConversationId) {
716
882
  console.error('No active conversation to mark as complete');
@@ -723,7 +889,7 @@
723
889
  conversationId: currentConversationId,
724
890
  completed: detail?.completed,
725
891
  });
726
- chatLog('Completion toggled via parent callback');
892
+ // chatLog('Completion toggled via parent callback');
727
893
  } else {
728
894
  chatWarn('No onCompletionToggle callback provided');
729
895
  }
@@ -735,7 +901,7 @@
735
901
  }
736
902
  }
737
903
 
738
- function handleActionError({ detail }: { detail: { type: string; error: any } }) {
904
+ function handleActionError(detail: { type: string; error: unknown }) {
739
905
  console.error(`ActionBar ${detail.type} error:`, detail.error);
740
906
  chatStore.actions.updateUI({
741
907
  errorMessage: `${detail.type} action failed. Please try again.`
@@ -743,7 +909,7 @@
743
909
  }
744
910
 
745
911
  async function handleSuggestionSelected(suggestion: string) {
746
- chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
912
+ // chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
747
913
  // Autocomplete into input instead of sending immediately — lets user review,
748
914
  // edit, and attach an image before sending (e.g. "Generate code from this design"
749
915
  // is useless without an attached screenshot).
@@ -753,7 +919,7 @@
753
919
  async function handleRetryMessage(content: string) {
754
920
  const retryContent = content.trim();
755
921
  if (!retryContent) return;
756
- chatLog('[Chat] Retrying failed message:', retryContent.slice(0, 80));
922
+ // chatLog('[Chat] Retrying failed message:', retryContent.slice(0, 80));
757
923
  if (onRetryMessage) {
758
924
  await onRetryMessage(retryContent);
759
925
  return;
@@ -762,7 +928,7 @@
762
928
  }
763
929
 
764
930
  async function handleRestoreCheckpoint(messageId: string, messageIndex: number) {
765
- chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
931
+ // chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
766
932
 
767
933
  if (!currentConversationId || !currentMessages) {
768
934
  console.error('No active conversation or messages to restore');
@@ -770,21 +936,32 @@
770
936
  }
771
937
 
772
938
  try {
773
- const clicked = currentMessages[messageIndex];
774
- let checkpointUserId = messageId;
939
+ const clicked = messageIndex >= 0
940
+ ? currentMessages[messageIndex]
941
+ : currentMessages.find((msg: any) => msg.id === messageId);
942
+ if (!clicked) {
943
+ console.warn('[Chat] Restore checkpoint: message not in local list', messageId);
944
+ if (onRestoreCheckpointBackend && !String(messageId).startsWith('fallback-head-')) {
945
+ await onRestoreCheckpointBackend(currentConversationId, messageId);
946
+ }
947
+ return;
948
+ }
949
+ const resolvedIndex = currentMessages.findIndex((msg: any) => msg.id === clicked.id);
950
+ let checkpointUserId = clicked.messageType === 'user' ? clicked.id : messageId;
775
951
  let headAssistantId = clicked?.id;
776
952
 
777
953
  // API rolls back to the commit produced by the user prompt before this assistant reply.
778
954
  if (clicked?.messageType === 'assistant') {
779
955
  headAssistantId = clicked.id;
780
- for (let i = messageIndex - 1; i >= 0; i--) {
956
+ for (let i = resolvedIndex - 1; i >= 0; i--) {
781
957
  if (currentMessages[i].messageType === 'user') {
782
958
  checkpointUserId = currentMessages[i].id;
783
959
  break;
784
960
  }
785
961
  }
786
962
  } else {
787
- for (let i = messageIndex + 1; i < currentMessages.length; i++) {
963
+ checkpointUserId = clicked.id;
964
+ for (let i = resolvedIndex + 1; i < currentMessages.length; i++) {
788
965
  if (currentMessages[i].messageType === 'assistant' && messageHasWidgetCommit(currentMessages[i].messageContent)) {
789
966
  headAssistantId = currentMessages[i].id;
790
967
  break;
@@ -798,13 +975,13 @@
798
975
  rolledBackAt: null,
799
976
  }));
800
977
 
801
- chatLog(`Restoring to checkpoint user message ${checkpointUserId}, head assistant ${headAssistantId}`);
978
+ // chatLog(`Restoring to checkpoint user message ${checkpointUserId}, head assistant ${headAssistantId}`);
802
979
  chatStore.actions.setMessages(currentConversationId, updatedMessages);
803
980
 
804
981
  if (onRestoreCheckpointBackend) {
805
982
  try {
806
983
  const result = await onRestoreCheckpointBackend(currentConversationId, checkpointUserId);
807
- chatLog('[Chat] Checkpoint restored on backend:', result);
984
+ // chatLog('[Chat] Checkpoint restored on backend:', result);
808
985
  if (headAssistantId) {
809
986
  markWidgetHeadAtLatestCommit(headAssistantId);
810
987
  }
@@ -814,7 +991,7 @@
814
991
  }
815
992
 
816
993
  chatStore.actions.updateUI({ errorMessage: null });
817
- chatLog('Checkpoint restored successfully');
994
+ // chatLog('Checkpoint restored successfully');
818
995
 
819
996
  } catch (error) {
820
997
  console.error('Failed to restore checkpoint:', error);
@@ -842,13 +1019,11 @@
842
1019
  return;
843
1020
  }
844
1021
  try {
845
- const byteString = atob(dataUrl.split(',')[1]);
1022
+ const response = await fetch(dataUrl);
1023
+ const blob = await response.blob();
846
1024
  const mimeMatch = dataUrl.match(/data:(image\/[^;]+);/);
847
- const mimeType = mimeMatch?.[1] || 'image/png';
848
- const ab = new ArrayBuffer(byteString.length);
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 });
1025
+ const mimeType = mimeMatch?.[1] || blob.type || 'image/png';
1026
+ const file = new File([blob], fileName, { type: mimeType });
852
1027
  const attachmentInput: AttachmentInput = {
853
1028
  file,
854
1029
  type: 'image',
@@ -858,10 +1033,11 @@
858
1033
  const attachmentIndex = localAttachments.length;
859
1034
  localAttachments = [...localAttachments, attachmentInput];
860
1035
  notifyDraftChange();
1036
+ expandChatForAttachmentGrowth(attachmentIndex);
861
1037
  if (onUploadChatFile) {
862
1038
  await uploadAttachmentToCdn(file, attachmentInput, attachmentIndex);
863
1039
  }
864
- chatLog('Image attachment added from external paste');
1040
+ // chatLog('Image attachment added from external paste');
865
1041
  } catch (err) {
866
1042
  console.error('[Chat] Failed to add image attachment:', err);
867
1043
  }
@@ -889,6 +1065,15 @@
889
1065
  }
890
1066
 
891
1067
  function restoreAttachmentsFromDataUrls(dataUrls: string[]) {
1068
+ for (const att of localAttachments) {
1069
+ if (att.preview && att.preview.startsWith('blob:')) {
1070
+ try {
1071
+ URL.revokeObjectURL(att.preview);
1072
+ } catch {
1073
+ /* ignore error */
1074
+ }
1075
+ }
1076
+ }
892
1077
  localAttachments = [];
893
1078
  const validUrls = dataUrls.filter(isValidImageDataUrl);
894
1079
  for (let i = 0; i < validUrls.length; i++) {
@@ -900,12 +1085,21 @@
900
1085
  }
901
1086
 
902
1087
  function clearDraft() {
1088
+ for (const att of localAttachments) {
1089
+ if (att.preview && att.preview.startsWith('blob:')) {
1090
+ try {
1091
+ URL.revokeObjectURL(att.preview);
1092
+ } catch {
1093
+ /* ignore error */
1094
+ }
1095
+ }
1096
+ }
903
1097
  localInputText = '';
904
1098
  localAttachments = [];
905
1099
  notifyDraftChange();
906
1100
  }
907
1101
 
908
- const CODEGEN_COMMIT_REGEX = /Commit:?\s+([a-f0-9]{7,40})/i;
1102
+ const CODEGEN_COMMIT_REGEX = /(?:Commit:?\s+|Code saved\s*\()([a-f0-9]{7,40})/i;
909
1103
 
910
1104
  function isPreviewRecompiledMessage(content?: string | null): boolean {
911
1105
  return /^Preview recompiled/i.test((content || '').trim());
@@ -917,13 +1111,14 @@
917
1111
  return /^Updated \d+ files?/i.test(trimmed) && /\n\nCommit\s+[a-f0-9]{7,40}/i.test(trimmed);
918
1112
  }
919
1113
 
920
- /** Widget HEAD: codegen completion, saved-code summaries, or visible preview-recompiled bubbles. */
1114
+ /** Widget HEAD: real codegen commits only — not rebuild-only "Preview recompiled" bubbles. */
921
1115
  function messageHasWidgetCommit(content?: string | null): boolean {
922
1116
  const trimmed = (content || '').trim();
923
1117
  if (!trimmed || isCodegenFailureMessage(trimmed)) return false;
924
- if (isPreviewRecompiledMessage(trimmed) && CODEGEN_COMMIT_REGEX.test(trimmed)) return true;
1118
+ if (isPreviewRecompiledMessage(trimmed)) return false;
925
1119
  if (CODEGEN_COMMIT_REGEX.test(trimmed) && (
926
1120
  /^Code generation completed/i.test(trimmed) ||
1121
+ /^Compile fix applied/i.test(trimmed) ||
927
1122
  /^Code saved/i.test(trimmed) ||
928
1123
  isBackendCodegenSummary(trimmed)
929
1124
  )) {
@@ -962,7 +1157,8 @@
962
1157
  isCodegenStatusMessage(content) ||
963
1158
  isBackendCodegenSummary(content) ||
964
1159
  messageHasWidgetCommit(content) ||
965
- isCodegenProgressMessage(content)
1160
+ isCodegenProgressMessage(content) ||
1161
+ isCodegenFailureMessage(content)
966
1162
  );
967
1163
  }
968
1164
 
@@ -972,7 +1168,8 @@
972
1168
  /^Code generation failed/i.test(t) ||
973
1169
  /^⚠️/.test(t) ||
974
1170
  /Too many generation requests/i.test(t) ||
975
- /temporarily unavailable/i.test(t)
1171
+ /temporarily unavailable/i.test(t) ||
1172
+ /Generation stopped/i.test(t)
976
1173
  );
977
1174
  }
978
1175
 
@@ -998,7 +1195,7 @@
998
1195
  rolledBackAt: null,
999
1196
  }));
1000
1197
  chatStore.actions.setMessages(currentConversationId, updated);
1001
- chatLog('[Chat] Widget HEAD marked on message:', headId);
1198
+ // chatLog('[Chat] Widget HEAD marked on message:', headId);
1002
1199
  }
1003
1200
 
1004
1201
  const CODEGEN_STATUS_MESSAGE_REGEX = /^Code generation completed/i;
@@ -1007,6 +1204,42 @@
1007
1204
  return CODEGEN_STATUS_MESSAGE_REGEX.test((content || '').trim());
1008
1205
  }
1009
1206
 
1207
+ const persistedCommitKeys: Record<string, true> = {};
1208
+
1209
+ function extractCommitShaFromContent(content: string): string | null {
1210
+ const match = (content || '').match(CODEGEN_COMMIT_REGEX);
1211
+ return match?.[1]?.toLowerCase() ?? null;
1212
+ }
1213
+
1214
+ function persistKey(conversationId: string, content: string): string | null {
1215
+ const sha = extractCommitShaFromContent(content);
1216
+ if (!sha) return null;
1217
+ return `${conversationId}:${sha}`;
1218
+ }
1219
+
1220
+ function rememberPersistedCommitSha(conversationId: string | null, content: string) {
1221
+ if (!conversationId) return;
1222
+ const key = persistKey(conversationId, content);
1223
+ if (key) persistedCommitKeys[key] = true;
1224
+ }
1225
+
1226
+ function persistAssistantCommitOnce(localMessageId: string, content: string) {
1227
+ if (!onSaveMessage || !currentConversationId) return;
1228
+ if (!messageHasWidgetCommit(content)) return;
1229
+ const key = persistKey(currentConversationId, content);
1230
+ if (!key || persistedCommitKeys[key]) return;
1231
+ persistedCommitKeys[key] = true;
1232
+ const convId = currentConversationId;
1233
+ onSaveMessage(convId, content, 'assistant').then(saved => {
1234
+ if (saved?.id && saved.id !== localMessageId) {
1235
+ chatStore.actions.updateMessageId(convId, localMessageId, saved.id);
1236
+ }
1237
+ }).catch(err => {
1238
+ delete persistedCommitKeys[key];
1239
+ chatWarn('[Chat] Failed to persist codegen commit message:', err);
1240
+ });
1241
+ }
1242
+
1010
1243
  /** One assistant bubble per user turn: loading → ready (in-place update within current turn only). */
1011
1244
  function updateLatestCodegenStatusMessage(content: string) {
1012
1245
  if (!currentConversationId) return;
@@ -1037,6 +1270,7 @@
1037
1270
  // Restore Checkpoint buttons require some message to be HEAD, so we mark eagerly on any commit.
1038
1271
  if (messageHasWidgetCommit(content)) {
1039
1272
  markWidgetHeadAtLatestCommit(targetId);
1273
+ persistAssistantCommitOnce(targetId, content);
1040
1274
  }
1041
1275
  return;
1042
1276
  }
@@ -1048,6 +1282,7 @@
1048
1282
  chatStore.actions.updateMessageContent(currentConversationId, m.id, content);
1049
1283
  if (messageHasWidgetCommit(content)) {
1050
1284
  markWidgetHeadAtLatestCommit(m.id);
1285
+ persistAssistantCommitOnce(m.id, content);
1051
1286
  }
1052
1287
  return;
1053
1288
  }
@@ -1065,6 +1300,12 @@
1065
1300
  const msgs = getCurrentMessages(currentConversationId);
1066
1301
  const idx = getLastUserMessageIndex(msgs);
1067
1302
  if (idx < 0) return;
1303
+ const last = msgs[idx];
1304
+ const hasRemote = (last.attachments || []).some(
1305
+ (a: { url?: string }) => typeof a.url === 'string' && /^https?:\/\//i.test(a.url),
1306
+ );
1307
+ const incomingHasRemote = attachments.some((a) => /^https?:\/\//i.test(a.url || ''));
1308
+ if (hasRemote && !incomingHasRemote) return;
1068
1309
  const mapped = attachments.map((a, i) => ({
1069
1310
  id: a.id || `att_${Date.now()}_${i}`,
1070
1311
  url: a.url,
@@ -1075,7 +1316,7 @@
1075
1316
  created_at: new Date().toISOString(),
1076
1317
  }));
1077
1318
  chatStore.actions.updateMessageAttachments(currentConversationId, msgs[idx].id, mapped);
1078
- chatLog('[Chat] Patched last user message attachments:', mapped.length);
1319
+ // chatLog('[Chat] Patched last user message attachments:', mapped.length);
1079
1320
  }
1080
1321
 
1081
1322
  /** Reload messages from backend and re-mark widget HEAD (picks up server-persisted summaries). */
@@ -1088,13 +1329,13 @@
1088
1329
  const loadedHasHead = (loaded || []).some((m) => messageHasWidgetCommit(m.messageContent));
1089
1330
  if (loaded?.length) {
1090
1331
  if (localHasHead && !loadedHasHead) {
1091
- chatLog('[Chat] Keep local HEAD commit message — DB reload has no commit yet');
1332
+ // chatLog('[Chat] Keep local HEAD commit message — DB reload has no commit yet');
1092
1333
  } else {
1093
1334
  chatStore.actions.setMessages(currentConversationId, loaded);
1094
1335
  }
1095
1336
  }
1096
1337
  markWidgetHeadAtLatestCommit();
1097
- chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
1338
+ // chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
1098
1339
  } catch (err) {
1099
1340
  chatWarn('[Chat] Failed to reload conversation messages:', err);
1100
1341
  }
@@ -1111,7 +1352,7 @@
1111
1352
  if (!/preview build failed/i.test(content)) continue;
1112
1353
  const cleaned = content.replace(previewFailedSuffix, '').trim();
1113
1354
  chatStore.actions.updateMessageContent(currentConversationId, msg.id, cleaned);
1114
- chatLog('[Chat] Cleared stale preview build failure from assistant message:', msg.id);
1355
+ // chatLog('[Chat] Cleared stale preview build failure from assistant message:', msg.id);
1115
1356
  break;
1116
1357
  }
1117
1358
  }
@@ -1177,12 +1418,12 @@
1177
1418
 
1178
1419
  // Debug reactive values
1179
1420
  $effect(() => {
1180
- chatLog('Chat render state for', context.id, ':', {
1181
- isInitialized,
1182
- chatState: !!chatState,
1183
- currentConversationId,
1184
- messagesLength: currentMessages?.length || 0
1185
- });
1421
+ // chatLog('Chat render state for', context.id, ':', {
1422
+ // isInitialized,
1423
+ // chatState: !!chatState,
1424
+ // currentConversationId,
1425
+ // messagesLength: currentMessages?.length || 0
1426
+ // });
1186
1427
  });
1187
1428
 
1188
1429
  // ── Messages area vertical resize ────────────────────────────────────
@@ -1236,7 +1477,7 @@
1236
1477
 
1237
1478
  <div
1238
1479
  bind:this={chatContainer}
1239
- class="{className ? className : 'prompt-chat-ct'} relative flex flex-col overflow-hidden bg-white border border-gray-300 rounded-medium {resizeExpandsContainer ? 'shrink-0' : 'h-full'}"
1480
+ class="{className ? className : 'prompt-chat-ct'} relative flex flex-col overflow-hidden bg-white border border-gray-300 {className ? '' : 'rounded-medium'} h-full min-h-0"
1240
1481
  style={style}
1241
1482
  >
1242
1483
  {#if showHeader}
@@ -1270,85 +1511,156 @@
1270
1511
  {/if}
1271
1512
 
1272
1513
  <!-- Chat Interface -->
1273
- {#if isInitialized}
1274
- <div
1275
- class="prompt-chat-messages-area flex min-h-0 flex-col overflow-hidden"
1276
- style="{messagesAreaHeight !== null
1277
- ? `flex: 0 0 ${messagesAreaHeight}px; height: ${messagesAreaHeight}px;`
1278
- : 'flex: 1 1 auto; min-height: 0;'}"
1279
- >
1280
- <ChatMessages
1281
- class="prompt-chat-messages h-full"
1282
- messages={currentMessages || []}
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
-
1514
+ <div
1515
+ class="prompt-chat-messages-area flex min-h-0 flex-col overflow-hidden"
1516
+ style="{messagesAreaHeight !== null
1517
+ ? `flex: 0 0 ${messagesAreaHeight}px; height: ${messagesAreaHeight}px;`
1518
+ : 'flex: 1 1 auto; min-height: 0;'}"
1519
+ >
1520
+ <ChatMessages
1521
+ class="prompt-chat-messages h-full"
1522
+ messages={currentMessages || []}
1523
+ isLoading={isLoading}
1524
+ {context}
1525
+ isCompleted={isCompleted}
1526
+ enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
1527
+ showGenerationSummaries={config?.features?.showGenerationSummaries === true}
1528
+ widgetHeadCommitSha={widgetHeadCommitSha}
1529
+ showCommitMeta={showLogs}
1530
+ isGenerating={isGenerating || isLoading}
1531
+ onSuggestionSelected={handleSuggestionSelected}
1532
+ onRestoreCheckpoint={handleRestoreCheckpoint}
1533
+ onRetryMessage={handleRetryMessage}
1534
+ />
1535
+ </div>
1536
+
1537
+ <div
1538
+ 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"
1539
+ class:bg-blue-100={isResizingMessages}
1540
+ class:border-blue-300={isResizingMessages}
1541
+ style="height: 16px; touch-action: none; padding: 4px 0;"
1542
+ onpointerdown={handleMessagesResizeStart}
1543
+ role="separator"
1544
+ aria-orientation="horizontal"
1545
+ aria-label="Resize messages area"
1546
+ title="Drag to resize messages area"
1547
+ >
1548
+ <div class="drag-grip w-14 h-1 rounded-full bg-gray-500 {isResizingMessages ? 'bg-blue-400' : ''}"></div>
1549
+ </div>
1550
+
1551
+ <div class="prompt-chat-footer-ct shrink-0 flex flex-col">
1308
1552
  <ActionBar
1309
1553
  {context}
1310
1554
  conversationId={currentConversationId}
1311
1555
  isRecording={localIsRecording}
1312
1556
  isCompleted={isCompleted}
1313
- disabled={!isInitialized || isLoading}
1557
+ disabled={isLoading}
1314
1558
  showScreenshot={config?.features?.screenshot !== false}
1315
1559
  showRecord={config?.features?.screenRecording !== false}
1316
1560
  showUpload={config?.features?.fileUpload !== false}
1317
1561
  showComplete={config?.features?.markComplete !== false}
1318
- on:screenshot={handleScreenshot}
1319
- on:recordStart={handleRecordStart}
1320
- on:recordStop={handleRecordStop}
1321
- on:upload={handleUpload}
1322
- on:complete={handleComplete}
1323
- on:error={handleActionError}
1562
+ onScreenshot={() => void handleScreenshot()}
1563
+ onUpload={() => void handleUpload()}
1564
+ onRecordStart={() => void handleRecordStart()}
1565
+ onRecordStop={() => void handleRecordStop()}
1566
+ onComplete={(detail) => void handleComplete(detail)}
1567
+ onError={handleActionError}
1324
1568
  />
1325
-
1569
+
1570
+ {#if localAttachments.length > 0}
1571
+ <div class="prompt-chat-attachments-tray-ct flex flex-wrap gap-2 p-3 border-t border-gray-100 bg-white shrink-0">
1572
+ {#each localAttachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
1573
+ <div class="prompt-chat-attachment-item-ct relative bg-gray-50 rounded-lg overflow-hidden">
1574
+ <span class="prompt-chat-attachment-index-badge absolute top-0.5 left-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{index + 1}</span>
1575
+ {#if isImageAttachment(attachment)}
1576
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
1577
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
1578
+ <img
1579
+ src={getFooterAttachmentPreviewUrl(attachment)}
1580
+ alt={attachment.file?.name || 'attachment'}
1581
+ class="prompt-chat-attachment-image-preview w-16 h-16 object-cover cursor-pointer"
1582
+ onclick={() => {
1583
+ const previewUrl = getFooterAttachmentPreviewUrl(attachment);
1584
+ if (previewUrl) footerLightboxSrc = previewUrl;
1585
+ }}
1586
+ />
1587
+ {:else}
1588
+ <div class="prompt-chat-attachment-file-preview flex items-center gap-2 p-3 w-32">
1589
+ <span class="text-lg">📄</span>
1590
+ <span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || 'attachment'}</span>
1591
+ </div>
1592
+ {/if}
1593
+
1594
+ <button
1595
+ type="button"
1596
+ class="prompt-chat-remove-attachment-btn absolute top-1 right-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600 cursor-pointer"
1597
+ onclick={() => removeFooterAttachment(index)}
1598
+ aria-label="Remove attachment"
1599
+ >
1600
+ ✕
1601
+ </button>
1602
+
1603
+ {#if attachment.uploadProgress && attachment.uploadProgress > 0 && attachment.uploadProgress < 100}
1604
+ <div class="prompt-chat-attachment-upload-bar absolute bottom-0 left-0 right-0 h-1 bg-gray-200">
1605
+ <div class="h-full bg-blue-500 transition-all duration-300" style="width: {attachment.uploadProgress}%"></div>
1606
+ </div>
1607
+ {/if}
1608
+ </div>
1609
+ {/each}
1610
+ </div>
1611
+ {/if}
1612
+
1326
1613
  <ChatInput
1327
1614
  value={localInputText}
1328
1615
  attachments={localAttachments}
1616
+ showAttachmentsTray={false}
1329
1617
  isRecording={localIsRecording}
1330
1618
  isSending={localIsSending}
1331
1619
  isUploading={localIsUploading}
1620
+ isGenerating={isGenerating || isLoading}
1621
+ onStop={() => onStopGeneration?.()}
1332
1622
  onSend={(content, attachmentInputs) => {
1333
1623
  sendMessage(content, attachmentInputs);
1334
1624
  }}
1335
1625
  onInputChange={(text) => {
1336
- chatLog('Input change for chat', context.id, ':', text);
1626
+ // chatLog('Input change for chat', context.id, ':', text);
1337
1627
  localInputText = text;
1338
1628
  notifyDraftChange();
1339
1629
  }}
1340
1630
  onAttachmentsChange={(attachments) => {
1341
- chatLog('Attachments change for chat', context.id, ':', attachments.length);
1631
+ // chatLog('Attachments change for chat', context.id, ':', attachments.length);
1342
1632
  localAttachments = attachments;
1343
1633
  notifyDraftChange();
1344
1634
  }}
1635
+ onFilesDropped={(files) => {
1636
+ void addFilesAsAttachments(files);
1637
+ }}
1345
1638
  />
1346
- {:else}
1347
- <!-- Loading State -->
1348
- <div class="loading-indicator-ct flex-1 flex items-center justify-center">
1349
- <div class="text-center">
1350
- <div class="w-8 h-8 border-2 border-gray-300 border-t-blue-600 rounded-full animate-spin mx-auto mb-4"></div>
1351
- <p class="text-gray-600 text-sm">Initializing chat...</p>
1639
+ </div>
1640
+
1641
+ {#if footerLightboxSrc}
1642
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
1643
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1644
+ <div
1645
+ class="prompt-chat-footer-lightbox-overlay fixed inset-0 z-[9999] flex items-center justify-center bg-black/85"
1646
+ onclick={() => (footerLightboxSrc = null)}
1647
+ >
1648
+ <button
1649
+ type="button"
1650
+ class="prompt-chat-footer-lightbox-close-btn absolute top-4 right-4 w-9 h-9 rounded-full bg-white/15 text-white text-lg flex items-center justify-center cursor-pointer hover:bg-white/30"
1651
+ onclick={() => (footerLightboxSrc = null)}
1652
+ title="Close"
1653
+ >
1654
+ ✕
1655
+ </button>
1656
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
1657
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1658
+ <div class="prompt-chat-footer-lightbox-content max-w-[90vw] max-h-[90vh]" onclick={(e) => e.stopPropagation()}>
1659
+ <img
1660
+ src={footerLightboxSrc}
1661
+ alt="Attachment preview"
1662
+ class="prompt-chat-footer-lightbox-image max-w-[90vw] max-h-[85vh] object-contain rounded-lg"
1663
+ />
1352
1664
  </div>
1353
1665
  </div>
1354
1666
  {/if}