-
Notifications
You must be signed in to change notification settings - Fork 692
Expand file tree
/
Copy pathconversation-manager.js
More file actions
646 lines (547 loc) · 22.4 KB
/
conversation-manager.js
File metadata and controls
646 lines (547 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
import { Message } from './schemas.js';
import indexedStorage from './indexed-storage.js';
class ConversationManager {
/**
* Field Name Standardization for Timestamps:
*
* We use 'created_at' as the standard field name on the client side for consistency.
* However, the server may send either:
* - 'created_at' (from Conversation model)
* - 'time_of_creation' (from ConversationEntry model)
*
* We handle both field names for backwards compatibility and to support different
* server data models. When processing server data, we always check for both names
* and normalize to 'created_at' in our client-side conversation objects.
*/
constructor() {
this.conversations = [];
this.storage = indexedStorage; // Use IndexedDB storage
}
async loadConversations(selectedSite, elements) {
// Load conversations from IndexedDB
// Server is only contacted when joining via share link
await this.loadLocalConversations(selectedSite);
}
async loadLocalConversations(selectedSite = null) {
this.conversations = [];
try {
// Load all messages from IndexedDB
const allMessages = await this.storage.getAllMessages();
// Group messages by conversation_id to reconstruct conversations
const conversationMap = {};
allMessages.forEach(msg => {
const convId = msg.conversation_id;
if (!convId) return;
if (!conversationMap[convId]) {
conversationMap[convId] = {
id: convId,
messages: [],
timestamp: msg.timestamp,
site: msg.content?.site || 'all',
mode: msg.content?.mode || 'list',
title: 'New chat'
};
}
// Convert Message object to plain object for backward compatibility with rest of the code
const msgData = msg instanceof Message ? msg.toDict() : msg;
msgData.db_saved = true; // Mark as saved since it came from the database
conversationMap[convId].messages.push(msgData);
// Update conversation metadata only from user messages
// Assistant messages should not change the conversation's site or mode
if (msg.sender_type === 'user' || msg.message_type == 'user') {
const msgSite = msg.content?.site;
const msgMode = msg.content?.mode;
const msgQuery = msg.content?.query;
if (msgSite) conversationMap[convId].site = msgSite;
if (msgMode) conversationMap[convId].mode = msgMode;
// Use the query as title if available
if (msgQuery && msgQuery !== '') {
conversationMap[convId].title = msgQuery.substring(0, 50);
}
}
// Update timestamp to be the latest message
if (msg.timestamp > conversationMap[convId].timestamp) {
conversationMap[convId].timestamp = msg.timestamp;
}
// console.log(conversationMap[convId]);
});
// Convert map to array
let conversations = Object.values(conversationMap);
// Don't filter by site - show all conversations regardless of selected site
// The selected site only affects new queries, not which conversations are shown
// Sort messages within each conversation by timestamp
conversations.forEach(conv => {
conv.messages.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
});
// Sort conversations by timestamp (most recent first)
conversations.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
// Filter by site if specified
this.conversations = selectedSite ? conversations.filter(c => c.site === selectedSite) : conversations;
} catch (e) {
console.error('Error loading conversations from IndexedDB:', e);
this.conversations = [];
}
}
async saveConversations() {
try {
// Save messages from each conversation to IndexedDB
for (const conv of this.conversations) {
// Skip conversation history searches
if (conv.site === 'conv_history') {
continue;
}
// Save messages - only save new messages that haven't been persisted yet
if (conv.messages && conv.messages.length > 0) {
const messagesToSave = [];
for (const msg of conv.messages) {
// Skip messages that are already saved (they have a db_saved flag)
if (msg.db_saved) {
continue;
}
// Ensure each message has required fields
if (!msg.conversation_id) {
msg.conversation_id = conv.id;
}
// Only save messages that have IDs
if (!msg.message_id) {
// Skip messages without IDs (like 'complete' messages)
continue;
}
// Convert to Message object before saving
const messageObj = Message.fromDict(msg);
messagesToSave.push(messageObj);
// Mark the original message as saved
msg.db_saved = true;
}
// Only save if there are new messages
if (messagesToSave.length > 0) {
await this.storage.saveMessages(messagesToSave);
}
}
}
} catch (e) {
console.error('Error saving conversations to IndexedDB:', e);
}
}
async getConversationWithMessages(id) {
// Guard against undefined or invalid IDs
if (!id) {
return null;
}
const conversation = this.conversations.find(c => c.id === id);
if (!conversation) {
return null;
}
// Load messages from IndexedDB if not already loaded
if (!conversation.messages || conversation.messages.length === 0) {
try {
conversation.messages = await this.storage.getMessages(id);
} catch (e) {
console.error('Error loading messages from IndexedDB:', e);
conversation.messages = [];
}
}
return conversation;
}
async loadConversation(id, chatInterface) {
const conversation = await this.getConversationWithMessages(id);
if (!conversation) {
return;
}
// Delegate to chat interface's own loadConversation if it has one
if (chatInterface.loadConversation) {
await chatInterface.loadConversation(id);
return;
}
// Otherwise handle basic loading
chatInterface.currentConversationId = id;
// Check if this is a server conversation (starts with conv_) or local
if (id.startsWith('conv_')) {
// This is a server conversation, we can reconnect to it
chatInterface.wsConversationId = id;
} else {
// This is a local conversation, we'll need to create it on server when sending first message
chatInterface.wsConversationId = null;
}
// Restore the site selection for this conversation
if (conversation.site) {
// Check if using state object (UnifiedChatInterface) or direct property
if (chatInterface.state) {
chatInterface.state.selectedSite = conversation.site;
} else {
chatInterface.selectedSite = conversation.site;
}
// Update the UI to reflect the site
const siteInfo = document.getElementById('chat-site-info');
if (siteInfo) {
siteInfo.textContent = `Asking ${conversation.site}`;
}
// Update site selector icon if it exists
if (chatInterface.siteSelectorIcon) {
chatInterface.siteSelectorIcon.title = `Site: ${conversation.site}`;
}
}
// Restore the mode selection for this conversation
if (conversation.mode) {
// Check if using state object (UnifiedChatInterface) or direct property
if (chatInterface.state) {
chatInterface.state.selectedMode = conversation.mode;
} else {
chatInterface.selectedMode = conversation.mode;
}
// Update mode selector UI if it exists
const modeSelectorIcon = document.getElementById('mode-selector-icon');
if (modeSelectorIcon) {
modeSelectorIcon.title = `Mode: ${conversation.mode.charAt(0).toUpperCase() + conversation.mode.slice(1)}`;
}
// Update selected state in dropdown
const modeDropdown = document.getElementById('mode-dropdown');
if (modeDropdown) {
const modeItems = modeDropdown.querySelectorAll('.mode-dropdown-item');
modeItems.forEach(item => {
if (item.getAttribute('data-mode') === conversation.mode) {
item.classList.add('selected');
} else {
item.classList.remove('selected');
}
});
}
}
// Clear messages
chatInterface.elements.messagesContainer.innerHTML = '';
// Rebuild context arrays from conversation history
chatInterface.prevQueries = conversation.messages
.filter(m => (m.sender_type === 'user') || (m.message_type === 'user' && !m.sender_type))
.slice(-10)
.map(m => m.content);
chatInterface.lastAnswers = [];
const assistantMessages = conversation.messages.filter(m => (m.sender_type === 'assistant') || (m.message_type === 'assistant' && !m.sender_type));
if (assistantMessages.length > 0) {
// Extract answers from assistant messages
assistantMessages.slice(-20).forEach(msg => {
if (msg.parsedAnswers && msg.parsedAnswers.length > 0) {
chatInterface.lastAnswers.push(...msg.parsedAnswers);
}
});
// Keep only last 20 answers
chatInterface.lastAnswers = chatInterface.lastAnswers.slice(-20);
}
// Clear messages container first
chatInterface.elements.messagesContainer.innerHTML = '';
// Sort messages by timestamp
const sortedMessages = [...conversation.messages].sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
// Replay all messages in timestamp order
sortedMessages.forEach((msg) => {
if (!msg.content) {
return;
}
// Check if content is an object (new format) or string (legacy)
if (typeof msg.content === 'object') {
// This is a server-format message, replay through handler
chatInterface.handleStreamData(msg.content);
} else {
// Legacy format - try to handle
try {
// Try to construct a message object from legacy format
const messageObj = {
message_type: msg.message_type,
content: msg.content,
timestamp: msg.timestamp
};
chatInterface.handleStreamData(messageObj);
} catch {
// Failed to handle legacy message
}
}
});
// Update title
chatInterface.elements.chatTitle.textContent = conversation.title || 'Chat';
// Update conversations list to show current selection
chatInterface.updateConversationsList();
// Hide centered input and show regular chat input
chatInterface.hideCenteredInput();
// Connect to WebSocket for server conversations
if (id.startsWith('conv_') && chatInterface.connectWebSocket) {
// This is a server conversation, connect to it
chatInterface.connectWebSocket(id).then(() => {
}).catch(() => {
// Reset wsConversationId if connection fails
chatInterface.wsConversationId = null;
});
}
// Scroll to bottom
setTimeout(() => {
chatInterface.scrollToBottom();
}, 100);
}
async deleteConversation(conversationId, chatInterface) {
try {
// Delete from IndexedDB
await this.storage.deleteConversation(conversationId);
// Remove from conversations array
this.conversations = this.conversations.filter(conv => conv.id !== conversationId);
} catch (e) {
console.error('Error deleting conversation from IndexedDB:', e);
}
// If this is a server conversation (starts with conv_), also delete from server
if (conversationId && conversationId.startsWith('conv_')) {
try {
// Get user ID if available
const userInfo = localStorage.getItem('userInfo');
let userId = null;
if (userInfo) {
try {
const parsed = JSON.parse(userInfo);
userId = parsed.id || parsed.user_id;
} catch (e) {
console.error('Error parsing userInfo:', e);
}
}
// Call server API to delete conversation
const params = new URLSearchParams({
conversation_id: conversationId
});
if (userId) {
params.append('user_id', userId);
}
const response = await fetch(`/api/conversation/delete?${params}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorData = await response.json();
console.error('Failed to delete conversation from server:', errorData);
// Continue with local deletion even if server fails
} else {
console.log(`Conversation ${conversationId} deleted from server`);
}
} catch (error) {
console.error('Error deleting conversation from server:', error);
// Continue with local deletion even if server fails
}
}
// Update UI
chatInterface.updateConversationsList();
// If we deleted the current conversation, create a new one
if (conversationId === chatInterface.currentConversationId) {
chatInterface.createNewChat();
}
}
updateConversationsList(chatInterface, container = null) {
// Use provided container or try to find the conversations list element
const targetContainer = container || document.getElementById('conversations-list');
if (!targetContainer) {
return;
}
targetContainer.innerHTML = '';
// Filter conversations
const conversationsWithContent = this.conversations.filter(conv => {
// Must have an ID
if (!conv.id) {
return false;
}
// For server conversations (conv_*), show them even without messages
if (conv.id.startsWith('conv_')) {
return true;
}
// For local conversations, must have messages
const hasMessages = conv.messages && conv.messages.length > 0;
if (!hasMessages) {
}
return hasMessages;
});
// Group conversations by site
const conversationsBySite = {};
conversationsWithContent.forEach(conv => {
const site = conv.site || 'all';
if (!conversationsBySite[site]) {
conversationsBySite[site] = [];
}
conversationsBySite[site].push(conv);
});
// Sort sites alphabetically, but keep 'all' at the top
const sites = Object.keys(conversationsBySite).sort((a, b) => {
if (a === 'all') return -1;
if (b === 'all') return 1;
return a.toLowerCase().localeCompare(b.toLowerCase());
});
// Create UI for each site group
sites.forEach(site => {
const conversations = conversationsBySite[site];
// Check if this is a dropdown container (which only shows one site)
const isDropdown = container && container.classList.contains('nlweb-dropdown-conversations-list');
// Create site group wrapper
const siteGroup = document.createElement('div');
siteGroup.className = 'site-group';
// Create conversations container for this site
const conversationsContainer = document.createElement('div');
conversationsContainer.className = 'site-conversations';
// Only show site header if not in dropdown
if (!isDropdown) {
// Create site header
const siteHeader = document.createElement('div');
siteHeader.className = 'site-group-header';
// Add site name (cleaned up for display)
const siteName = document.createElement('span');
siteName.textContent = this.cleanSiteName(site);
siteHeader.appendChild(siteName);
// Add chevron icon
const chevron = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
chevron.setAttribute('class', 'chevron');
chevron.setAttribute('viewBox', '0 0 24 24');
chevron.setAttribute('fill', 'none');
chevron.setAttribute('stroke', 'currentColor');
chevron.setAttribute('stroke-width', '2');
chevron.innerHTML = '<polyline points="6 9 12 15 18 9"></polyline>';
siteHeader.appendChild(chevron);
siteGroup.appendChild(siteHeader);
// Add click handler to toggle conversations visibility
siteHeader.addEventListener('click', () => {
conversationsContainer.classList.toggle('collapsed');
siteHeader.classList.toggle('collapsed');
});
}
// Sort conversations by timestamp (most recent first)
conversations.sort((a, b) => b.timestamp - a.timestamp);
conversations.forEach(conv => {
const convItem = document.createElement('div');
convItem.className = 'conversation-item';
convItem.dataset.conversationId = conv.id; // Add the data attribute for the click handler
if (conv.id === chatInterface.currentConversationId) {
convItem.classList.add('active');
}
// Delete button (now on the left)
const deleteBtn = document.createElement('button');
deleteBtn.className = 'conversation-delete';
deleteBtn.innerHTML = '×';
deleteBtn.title = 'Delete conversation';
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.deleteConversation(conv.id, chatInterface);
});
convItem.appendChild(deleteBtn);
// Create conversation content container
const convContent = document.createElement('div');
convContent.className = 'conversation-content';
// Title span
const titleSpan = document.createElement('span');
titleSpan.className = 'conversation-title';
titleSpan.textContent = conv.title || 'Untitled';
titleSpan.addEventListener('click', async () => {
await this.loadConversation(conv.id, chatInterface);
});
convContent.appendChild(titleSpan);
convItem.appendChild(convContent);
conversationsContainer.appendChild(convItem);
});
siteGroup.appendChild(conversationsContainer);
targetContainer.appendChild(siteGroup);
});
}
// Helper method to clean up site names for display
cleanSiteName(site) {
if (!site) return site;
// Remove common domain suffixes
return site
.replace(/\.myshopify\.com$/, '')
.replace(/\.com$/, '')
.replace(/\.org$/, '')
.replace(/\.net$/, '')
.replace(/\.io$/, '')
.replace(/\.co$/, '');
}
// Helper method to get conversations
getConversations() {
return this.conversations;
}
// Helper method to find a conversation by ID
findConversation(id) {
return this.conversations.find(c => c.id === id);
}
// Helper method to add a conversation
addConversation(conversation) {
this.conversations.unshift(conversation);
}
// Helper method to update a conversation
updateConversation(id, updates) {
const conversation = this.findConversation(id);
if (conversation) {
Object.assign(conversation, updates);
}
}
// Add a message to storage
async addMessage(conversationId, message) {
try {
// Ensure message has required fields
if (!message.conversation_id) {
message.conversation_id = conversationId;
}
// Use the message_id from the server - no generation needed
if (!message.message_id) {
console.warn('Message missing message_id from server in addMessage:', message);
}
// Note: We don't save the message here - it's saved in batch by saveConversations()
// The message object will be converted to Message class when saved
// Don't save here - messages are saved in batch by saveConversations()
// The message is added to the conversation's messages array by the caller
// Update conversation metadata only (don't push to messages array - caller handles that)
const conversation = this.findConversation(conversationId);
if (conversation) {
// Update conversation timestamp
if (message.timestamp > conversation.timestamp) {
conversation.timestamp = message.timestamp;
}
// Update title from first user message
if (((message.sender_type === 'user') || (message.message_type === 'user' && !message.sender_type)) && conversation.title === 'New chat') {
const content = typeof message.content === 'string' ? message.content : (message.content?.query || message.content?.content || 'New chat');
conversation.title = content.substring(0, 50);
// Title update is now handled in memory only - will be reconstructed from messages on next load
}
}
} catch (e) {
console.error('Error adding message to IndexedDB:', e);
}
}
// Update a message in storage
async updateMessage(messageId, updates) {
try {
// Get the message from IndexedDB
const allMessages = await this.storage.getAllMessages();
const message = allMessages.find(m => m.message_id === messageId);
if (message) {
// Update the message
Object.assign(message, updates);
await this.storage.updateMessage(message);
// Update in-memory if conversation is loaded
const conversation = this.findConversation(message.conversation_id);
if (conversation && conversation.messages) {
const memoryMsg = conversation.messages.find(m => m.message_id === messageId);
if (memoryMsg) {
Object.assign(memoryMsg, updates);
}
}
}
} catch (e) {
console.error('Error updating message in IndexedDB:', e);
}
}
// Delete a message from storage
async deleteMessage(messageId, conversationId) {
try {
// Delete from IndexedDB
await this.storage.deleteMessage(messageId);
// Update in-memory conversation
const conversation = this.findConversation(conversationId);
if (conversation && conversation.messages) {
conversation.messages = conversation.messages.filter(m => m.message_id !== messageId);
}
} catch (e) {
console.error('Error deleting message from IndexedDB:', e);
}
}
}
// Export the class
export { ConversationManager };
export default ConversationManager;