mini-chat-bot-widget 0.6.0 → 0.9.0

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,16 +1,115 @@
1
- // chat-widget.js - Modern vanilla JS chat bot widget
1
+ // chat-widget.js - Basic vanilla JS chat widget skeleton
2
+
3
+ // Import screen components
4
+ import TextChatScreen from "./text-chat-screen.js";
5
+ import AudioChatScreen from "./audio-chat-screen.js";
2
6
 
3
7
  class ChatWidget {
4
8
  constructor(options = {}) {
5
9
  this.title = options.title || "Chat Assistant";
6
10
  this.placeholder = options.placeholder || "Type your message...";
7
- this.primaryColor = options.primaryColor || "#6366f1";
11
+ this.primaryColor = options.primaryColor || "#1a5c4b";
8
12
  this.container = null;
9
13
  this.messages = [];
10
14
  this.isMinimized = false;
15
+ this.currentScreen = "welcome"; // welcome, text, audio
16
+ this.textChatScreen = null;
17
+ this.audioChatScreen = null;
18
+
19
+ // Configuration options for message sending
20
+ this.langgraphUrl = options.langgraphUrl || "http://localhost:8080";
21
+ this.authToken = options.authToken || null;
22
+ this.threadId = options.threadId || null;
23
+ this.assistantId = options.assistantId || null;
24
+ this.selectedLanguage = options.selectedLanguage || "en";
25
+ this.accessToken = options.accessToken || "";
26
+ this.supabaseToken = options.supabaseToken || "";
27
+ this.userInfo = options.userInfo || {};
28
+ this.mcpServerUrl = options.mcpServerUrl || "http://localhost:8010/mcp";
29
+ // Store the custom getHeaders function or use default
30
+ this._customGetHeaders = options.getHeaders;
31
+
32
+ // Default getHeaders implementation
33
+ this.getHeaders = () => {
34
+ if (this._customGetHeaders) {
35
+ return this._customGetHeaders();
36
+ }
37
+ const authToken = this.authToken || this.accessToken;
38
+ const supabaseToken = this.supabaseToken || authToken;
39
+ return {
40
+ "Content-Type": "application/json",
41
+ ...(authToken && { Authorization: `Bearer ${authToken}` }),
42
+ ...(supabaseToken && { "x-supabase-access-token": supabaseToken }),
43
+ Origin: (typeof window !== 'undefined' ? window.location.origin : "*") || "*",
44
+ };
45
+ };
46
+ this.getLatestCheckpoint = options.getLatestCheckpoint || (async () => null);
47
+ this.updateThread = options.updateThread || (async () => { });
48
+ this.getUserThreads = options.getUserThreads || (async ({ userId, userUuid }) => {
49
+ try {
50
+ const params = new URLSearchParams();
51
+ if (userUuid) params.append("user_uuid", userUuid);
52
+ const url = `${this.langgraphUrl}/history?${params.toString()}`;
53
+ const response = await fetch(url, {
54
+ method: "GET",
55
+ headers: this.getHeaders(),
56
+ });
57
+ if (!response.ok) return { threads: [] };
58
+ return await response.json();
59
+ } catch (e) {
60
+ console.error("Error fetching threads", e);
61
+ return { threads: [] };
62
+ }
63
+ });
64
+ this.setUserInfoFromDirectChatLogin = options.setUserInfoFromDirectChatLogin || (() => { });
65
+ this.setUserThreads = options.setUserThreads || (() => { });
66
+ this.setUserThreadsMetaData = options.setUserThreadsMetaData || (() => { });
67
+
68
+ this.languageOptions = [
69
+ { label: "Assamese", value: "as" },
70
+ { label: "Bengali", value: "bn" },
71
+ { label: "Dogri", value: "doi" },
72
+ { label: "English", value: "en" },
73
+ { label: "Gujarati", value: "gu" },
74
+ { label: "Hindi", value: "hi" },
75
+ { label: "Kannada", value: "kn" },
76
+ { label: "Konkani", value: "gom" },
77
+ { label: "Maithili", value: "mai" },
78
+ { label: "Malayalam", value: "ml" },
79
+ { label: "Marathi", value: "mr" },
80
+ { label: "Oriya", value: "or" },
81
+ { label: "Punjabi", value: "pa" },
82
+ { label: "Sanskrit", value: "sa" },
83
+ { label: "Sindhi", value: "sd" },
84
+ { label: "Tamil", value: "ta" },
85
+ { label: "Telugu", value: "te" },
86
+ { label: "Urdu", value: "ur" },
87
+ ];
88
+
89
+ // State management
90
+ this.isLoading = false;
91
+ this.isConnected = false;
92
+ this.initialized = false;
93
+ this.contentBlocks = [];
94
+ this.playedAudioIds = new Set();
95
+ this.currentInputAudio = null;
96
+ this.submissionInProgress = false;
97
+ this.processingAudioId = null;
98
+
11
99
  this._init();
100
+
101
+ // Initialize chat after DOM is ready
102
+ if (typeof window !== 'undefined') {
103
+ // Use setTimeout to ensure DOM is ready
104
+ setTimeout(() => {
105
+ this.initializeChat();
106
+ }, 100);
107
+ }
12
108
  }
13
109
 
110
+
111
+
112
+
14
113
  _init() {
15
114
  // Create container
16
115
  this.container = document.createElement("div");
@@ -22,46 +121,47 @@ class ChatWidget {
22
121
  </svg>
23
122
  </div>
24
123
  <div class="chat-widget-expanded" id="chat-expanded">
25
- <div class="chat-header">
26
- <div class="chat-header-content">
27
- <div class="chat-avatar">
28
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
29
- <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"></path>
30
- <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
31
- </svg>
124
+ <div class="chat-screen-container" id="chat-screen-container">
125
+ <!-- Screens will be rendered here -->
126
+ </div>
127
+ <div class="chat-drawer-overlay" id="chat-drawer-overlay">
128
+ <div class="chat-drawer">
129
+ <div class="drawer-header">
130
+ <div class="drawer-title">Menu</div>
32
131
  </div>
33
- <div class="chat-header-text">
34
- <div class="chat-title">${this.title}</div>
35
- <div class="chat-status">● Online</div>
132
+ <div class="drawer-content">
133
+ <button class="drawer-item" id="drawer-new-chat">
134
+ New Chat
135
+ </button>
136
+ <div class="language-selector-container">
137
+ <div class="custom-select" id="language-selector">
138
+ <div class="select-trigger" id="language-trigger">
139
+ <span id="selected-language-text">English</span>
140
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="chevron"><path d="m6 9 6 6 6-6"/></svg>
141
+ </div>
142
+ <div class="select-options" id="language-options"></div>
143
+ </div>
144
+ </div>
145
+ <div class="drawer-divider" style="height: 1px; background: #e2e8f0; margin: 8px 0;"></div>
146
+
147
+ <div id="drawer-threads" class="threads-container">
148
+ <!-- Threads will be rendered here -->
149
+ <div class="threads-loading">Loading history...</div>
150
+ </div>
36
151
  </div>
152
+
37
153
  </div>
38
- <button class="chat-close" id="chat-close">
39
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
40
- <line x1="18" y1="6" x2="6" y2="18"></line>
41
- <line x1="6" y1="6" x2="18" y2="18"></line>
42
- </svg>
43
- </button>
44
- </div>
45
- <div class="chat-messages" id="chat-messages">
46
- <div class="chat-welcome">
47
- <div class="welcome-icon">👋</div>
48
- <div class="welcome-text">Hello! How can I help you today?</div>
49
- </div>
50
- </div>
51
- <div class="chat-input-wrapper">
52
- <input type="text" id="chat-input" placeholder="${this.placeholder}" autocomplete="off" />
53
- <button id="chat-send" disabled>
54
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
55
- <line x1="22" y1="2" x2="11" y2="13"></line>
56
- <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
57
- </svg>
58
- </button>
154
+ <div class="drawer-backdrop" id="drawer-backdrop"></div>
59
155
  </div>
60
156
  </div>
61
157
  `;
62
158
  document.body.appendChild(this.container);
63
159
  this._applyStyles();
160
+ this._initScreens();
161
+ this._renderScreen();
162
+ this._populateLanguageOptions();
64
163
  this._bindEvents();
164
+
65
165
  }
66
166
 
67
167
  _applyStyles() {
@@ -76,62 +176,15 @@ class ChatWidget {
76
176
  z-index: 10000;
77
177
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
78
178
  }
79
-
80
- .chat-widget-minimized {
81
- width: 60px;
82
- height: 60px;
83
- border-radius: 50%;
84
- background: linear-gradient(135deg, ${this.primaryColor} 0%, #8b5cf6 100%);
85
- color: white;
179
+ .text-chat-screen {
180
+ flex: 1;
86
181
  display: flex;
87
- align-items: center;
88
- justify-content: center;
89
- cursor: pointer;
90
- box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4);
91
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
92
- animation: pulse 2s infinite;
93
- }
94
-
95
- .chat-widget-minimized:hover {
96
- transform: scale(1.1);
97
- box-shadow: 0 12px 32px rgba(99, 102, 241, 0.5);
98
- }
99
-
100
- @keyframes pulse {
101
- 0%, 100% { box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4); }
102
- 50% { box-shadow: 0 8px 32px rgba(99, 102, 241, 0.6); }
103
- }
104
-
105
- .chat-widget-expanded {
106
- width: 380px;
107
- height: 600px;
108
- background: white;
109
- border-radius: 16px;
110
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
111
- display: none;
112
182
  flex-direction: column;
113
183
  overflow: hidden;
114
- animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
115
- }
116
-
117
- @keyframes slideUp {
118
- from {
119
- opacity: 0;
120
- transform: translateY(20px) scale(0.95);
121
- }
122
- to {
123
- opacity: 1;
124
- transform: translateY(0) scale(1);
125
- }
126
- }
127
-
128
- .chat-widget-expanded.visible {
129
- display: flex;
130
184
  }
131
185
 
132
186
  .chat-header {
133
- background: linear-gradient(135deg, ${this.primaryColor} 0%, #8b5cf6 100%);
134
- color: white;
187
+ color: ${this.primaryColor};
135
188
  padding: 20px;
136
189
  display: flex;
137
190
  align-items: center;
@@ -142,6 +195,25 @@ class ChatWidget {
142
195
  display: flex;
143
196
  align-items: center;
144
197
  gap: 12px;
198
+ flex: 1;
199
+ }
200
+
201
+ .chat-back {
202
+ background: transparent;
203
+ border: none;
204
+ color: white;
205
+ cursor: pointer;
206
+ padding: 8px;
207
+ border-radius: 8px;
208
+ display: flex;
209
+ align-items: center;
210
+ justify-content: center;
211
+ transition: all 0.2s;
212
+ margin-right: 8px;
213
+ }
214
+
215
+ .chat-back:hover {
216
+ background: rgba(255, 255, 255, 0.15);
145
217
  }
146
218
 
147
219
  .chat-avatar {
@@ -160,10 +232,10 @@ class ChatWidget {
160
232
  flex-direction: column;
161
233
  gap: 2px;
162
234
  }
163
-
235
+
164
236
  .chat-title {
165
237
  font-weight: 600;
166
- font-size: 16px;
238
+ font-size: 20px;
167
239
  }
168
240
 
169
241
  .chat-status {
@@ -175,284 +247,2283 @@ class ChatWidget {
175
247
  }
176
248
 
177
249
  .chat-close {
178
- background: transparent;
250
+ background: ${this.primaryColor};
179
251
  border: none;
180
252
  color: white;
181
253
  cursor: pointer;
182
254
  padding: 8px;
183
- border-radius: 8px;
255
+ border-radius: 50%;
184
256
  display: flex;
185
257
  align-items: center;
186
258
  justify-content: center;
187
259
  transition: all 0.2s;
188
260
  }
189
261
 
190
- .chat-close:hover {
191
- background: rgba(255, 255, 255, 0.15);
192
- }
193
-
194
- .chat-messages {
195
- flex: 1;
196
- padding: 20px;
197
- overflow-y: auto;
198
- background: #f9fafb;
262
+ .chat-widget-minimized {
263
+ width: 60px;
264
+ height: 60px;
265
+ border-radius: 50%;
266
+ background: ${this.primaryColor};
267
+ color: white;
199
268
  display: flex;
200
- flex-direction: column;
201
- gap: 12px;
202
- }
203
-
204
- .chat-messages::-webkit-scrollbar {
205
- width: 6px;
206
- }
207
-
208
- .chat-messages::-webkit-scrollbar-track {
209
- background: transparent;
210
- }
211
-
212
- .chat-messages::-webkit-scrollbar-thumb {
213
- background: #cbd5e1;
214
- border-radius: 3px;
215
- }
216
-
217
- .chat-welcome {
218
- text-align: center;
219
- padding: 40px 20px;
220
- color: #64748b;
269
+ align-items: center;
270
+ justify-content: center;
271
+ cursor: pointer;
272
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
221
273
  }
222
274
 
223
- .welcome-icon {
224
- font-size: 48px;
225
- margin-bottom: 12px;
275
+ .chat-widget-minimized:hover {
276
+ transform: scale(1.1);
226
277
  }
227
278
 
228
- .welcome-text {
229
- font-size: 15px;
230
- font-weight: 500;
231
- color: #475569;
279
+ @keyframes pulse {
280
+ 0%, 100% { box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4); }
281
+ 50% { box-shadow: 0 8px 32px rgba(99, 102, 241, 0.6); }
232
282
  }
233
283
 
234
- .chat-message {
235
- display: flex;
236
- gap: 8px;
237
- animation: messageSlide 0.3s ease-out;
284
+ .chat-widget-expanded {
285
+ position: relative;
286
+ width: 480px;
287
+ height: 640px;
288
+ background: white;
289
+ border-radius: 16px;
290
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
291
+ display: none;
292
+ flex-direction: column;
293
+ overflow: hidden;
294
+ animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
238
295
  }
239
296
 
240
- @keyframes messageSlide {
297
+ @keyframes slideUp {
241
298
  from {
242
299
  opacity: 0;
243
- transform: translateY(10px);
300
+ transform: translateY(20px) scale(0.95);
244
301
  }
245
302
  to {
246
303
  opacity: 1;
247
- transform: translateY(0);
304
+ transform: translateY(0) scale(1);
248
305
  }
249
306
  }
250
307
 
251
- .chat-message.user {
252
- flex-direction: row-reverse;
253
- }
254
-
255
- .message-bubble {
256
- max-width: 75%;
257
- padding: 12px 16px;
258
- border-radius: 16px;
259
- font-size: 14px;
260
- line-height: 1.5;
261
- word-wrap: break-word;
308
+ .chat-widget-expanded.visible {
309
+ display: flex;
262
310
  }
263
311
 
264
- .chat-message.user .message-bubble {
265
- background: linear-gradient(135deg, ${this.primaryColor} 0%, #8b5cf6 100%);
266
- color: white;
267
- border-bottom-right-radius: 4px;
312
+ .chat-screen-container {
313
+ flex: 1;
314
+ display: flex;
315
+ flex-direction: column;
316
+ overflow: hidden;
268
317
  }
269
318
 
270
- .chat-message.bot .message-bubble {
271
- background: white;
272
- color: #1e293b;
273
- border-bottom-left-radius: 4px;
274
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
319
+ /* Welcome Screen Styles */
320
+ .welcome-screen {
321
+ flex: 1;
322
+ height: 100%;
323
+ display: flex;
324
+ flex-direction: column;
325
+ align-items: stretch;
326
+ justify-content: start;
327
+ background: linear-gradient(180deg, white 10%, #E1EFCC );
328
+ padding: 0px;
275
329
  }
276
330
 
277
- .typing-indicator {
278
- display: flex;
279
- gap: 4px;
280
- padding: 12px 16px;
281
- background: white;
282
- border-radius: 16px;
283
- border-bottom-left-radius: 4px;
284
- max-width: 60px;
285
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
331
+ .welcome-content {
332
+ width: 80%;
333
+ margin: auto;
334
+ text-align: center;
335
+ padding-top: 20px;
286
336
  }
287
337
 
288
- .typing-dot {
289
- width: 8px;
290
- height: 8px;
291
- border-radius: 50%;
292
- background: #94a3b8;
293
- animation: typing 1.4s infinite;
338
+ .welcome-icon {
339
+ font-size: 64px;
340
+ margin-bottom: 16px;
341
+ animation: bounce 2s infinite;
294
342
  }
295
343
 
296
- .typing-dot:nth-child(2) {
297
- animation-delay: 0.2s;
344
+ @keyframes bounce {
345
+ 0%, 100% { transform: translateY(0); }
346
+ 50% { transform: translateY(-10px); }
298
347
  }
299
348
 
300
- .typing-dot:nth-child(3) {
301
- animation-delay: 0.4s;
349
+ .welcome-title {
350
+ font-size: 24px;
351
+ font-weight: 600;
352
+ color: #1e293b;
353
+ margin: 0 0 8px 0;
302
354
  }
303
355
 
304
- @keyframes typing {
305
- 0%, 60%, 100% {
306
- transform: translateY(0);
307
- opacity: 0.7;
308
- }
309
- 30% {
310
- transform: translateY(-10px);
311
- opacity: 1;
312
- }
356
+ .welcome-subtitle {
357
+ font-size: 14px;
358
+ color: #64748b;
359
+ margin: 0 0 32px 0;
313
360
  }
314
361
 
315
- .chat-input-wrapper {
362
+ .welcome-options {
316
363
  display: flex;
317
- padding: 16px;
318
- gap: 8px;
319
- background: white;
320
- border-top: 1px solid #e2e8f0;
364
+ flex-direction: column;
365
+ gap: 12px;
321
366
  }
322
367
 
323
- #chat-input {
324
- flex: 1;
368
+ .welcome-option-btn {
369
+ background: white;
325
370
  border: 2px solid #e2e8f0;
326
371
  border-radius: 12px;
327
- padding: 12px 16px;
328
- font-size: 14px;
329
- outline: none;
372
+ padding: 16px;
373
+ display: flex;
374
+ align-items: center;
375
+ gap: 12px;
376
+ cursor: pointer;
330
377
  transition: all 0.2s;
331
- font-family: inherit;
378
+ text-align: left;
379
+ width: 100%;
332
380
  }
333
381
 
334
- #chat-input:focus {
382
+ .welcome-option-btn:hover {
335
383
  border-color: ${this.primaryColor};
336
- box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
384
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
385
+ transform: translateY(-2px);
337
386
  }
338
387
 
339
- #chat-send {
340
- background: linear-gradient(135deg, ${this.primaryColor} 0%, #8b5cf6 100%);
341
- color: white;
342
- border: none;
343
- border-radius: 12px;
344
- padding: 12px 16px;
345
- cursor: pointer;
346
- display: flex;
347
- align-items: center;
348
- justify-content: center;
349
- transition: all 0.2s;
388
+ .option-icon {
389
+ font-size: 32px;
390
+ flex-shrink: 0;
350
391
  }
351
392
 
352
- #chat-send:disabled {
353
- opacity: 0.5;
354
- cursor: not-allowed;
393
+ .option-content {
394
+ flex: 1;
355
395
  }
356
396
 
357
- #chat-send:not(:disabled):hover {
358
- transform: scale(1.05);
359
- box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
397
+ .option-title {
398
+ font-size: 16px;
399
+ font-weight: 600;
400
+ color: #1e293b;
401
+ margin-bottom: 4px;
360
402
  }
361
403
 
362
- #chat-send:not(:disabled):active {
363
- transform: scale(0.95);
404
+ .option-description {
405
+ font-size: 13px;
406
+ color: #64748b;
364
407
  }
365
- `;
366
- document.head.appendChild(style);
408
+
409
+ .welcome-option-btn svg {
410
+ color: #94a3b8;
411
+ flex-shrink: 0;
412
+ }
413
+
414
+ .welcome-option-btn:hover svg {
415
+ color: ${this.primaryColor};
416
+ }
417
+ .gradient-sphere-welcome-screen {
418
+ width: 200px !important;
419
+ height: 200px !important;
420
+ border-radius: 50%;
421
+ background: linear-gradient(135deg, #0a0d120f 0%, #85bc31 50%, #d0f19e 100%)
422
+ !important;
423
+ position: relative;
424
+ margin: 20px auto 30px auto;
425
+ box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
426
+ animation: float 3s ease-in-out infinite;
427
+ flex-shrink: 0;
428
+ }
429
+
430
+ .sphere-highlight {
431
+ position: absolute;
432
+ top: 20%;
433
+ right: 20%;
434
+ width: 35px;
435
+ height: 35px;
436
+ background: radial-gradient(
437
+ circle,
438
+ rgba(255, 255, 255, 0.8) 0%,
439
+ transparent 70%
440
+ );
441
+ border-radius: 50%;
442
+ filter: blur(1px);
443
+ }
444
+
445
+ @keyframes float {
446
+ 0%,
447
+ 100% {
448
+ transform: translateY(0px);
367
449
  }
450
+ 50% {
451
+ transform: translateY(-10px);
452
+ }
453
+ }
368
454
 
369
- _bindEvents() {
370
- const toggle = this.container.querySelector("#chat-toggle");
371
- const closeBtn = this.container.querySelector("#chat-close");
372
- const expanded = this.container.querySelector("#chat-expanded");
373
- const input = this.container.querySelector("#chat-input");
374
- const sendBtn = this.container.querySelector("#chat-send");
455
+ .welcome-text {
456
+ max-width: 400px;
457
+ margin-bottom: 30px;
458
+ flex-shrink: 0;
459
+ text-align: left;
460
+ }
375
461
 
376
- toggle.addEventListener("click", () => {
377
- toggle.style.display = "none";
378
- expanded.classList.add("visible");
379
- input.focus();
380
- });
462
+ .greeting {
463
+ font-size: 24px;
464
+ font-weight: 600;
465
+ color: #1a5c4b;
466
+ margin: 0 0 16px 0;
467
+ }
381
468
 
382
- closeBtn.addEventListener("click", () => {
383
- expanded.classList.remove("visible");
384
- toggle.style.display = "flex";
385
- });
469
+ .intro {
470
+ font-size: 18px;
471
+ font-weight: 500;
472
+ color: #1a5c4b;
473
+ margin: 0 0 12px 0;
474
+ line-height: 1.4;
475
+ }
386
476
 
387
- input.addEventListener("input", () => {
388
- sendBtn.disabled = !input.value.trim();
389
- });
390
477
 
391
- const send = () => {
392
- const text = input.value.trim();
393
- if (!text) return;
478
+ .action-buttons {
479
+ display: flex;
480
+ align-items: center;
481
+ gap: 16px;
482
+ flex-shrink: 0;
483
+ margin-top: auto;
484
+ /* padding-top: 10px; */
485
+ padding-bottom: 20px;
486
+ justify-content: center;
487
+ width: 100%;
488
+ align-self: center;
489
+ }
394
490
 
395
- this._addMessage(text, true);
396
- input.value = "";
397
- sendBtn.disabled = true;
491
+ .primary-button {
492
+ background: #1a5c4b;
493
+ display:flex;
494
+ color: white;
495
+ border: none;
496
+ padding: 16px 32px;
497
+ border-radius: 25px;
498
+ font-size: 16px;
499
+ font-weight: 600;
500
+ cursor: pointer;
501
+ transition: all 0.3s ease;
502
+ box-shadow: 0 4px 12px rgba(26, 92, 75, 0.3);
503
+ }
398
504
 
399
- this._showTypingIndicator();
505
+ .primary-button:hover {
506
+ transform: translateY(-2px);
507
+ box-shadow: 0 6px 16px rgba(26, 92, 75, 0.4);
508
+ }
400
509
 
401
- setTimeout(() => {
402
- this._hideTypingIndicator();
403
- this._addMessage(`Thanks for your message! You said: "${text}"`, false);
404
- }, 1000 + Math.random() * 1000);
405
- };
510
+ @media (max-width: 768px) {
511
+ #chat-widget-container {
512
+ bottom: 16px;
513
+ right: 16px;
514
+ }
406
515
 
407
- sendBtn.addEventListener("click", send);
408
- input.addEventListener("keypress", (e) => {
409
- if (e.key === "Enter" && !sendBtn.disabled) send();
410
- });
411
- }
516
+ .chat-widget-expanded {
517
+ width: 100vw;
518
+ height: 100vh;
519
+ border-radius: 0;
520
+ max-width: 100vw;
521
+ max-height: 100vh;
522
+ position: fixed;
523
+ top: 0;
524
+ left: 0;
525
+ right: 0;
526
+ bottom: 0;
527
+ }
412
528
 
413
- _addMessage(text, isUser) {
414
- const messagesContainer = this.container.querySelector("#chat-messages");
415
- const welcome = messagesContainer.querySelector(".chat-welcome");
416
- if (welcome) welcome.remove();
529
+ .chat-widget-expanded.visible {
530
+ display: flex;
531
+ }
417
532
 
418
- const messageEl = document.createElement("div");
419
- messageEl.className = `chat-message ${isUser ? "user" : "bot"}`;
420
- messageEl.innerHTML = `<div class="message-bubble">${this._escapeHtml(text)}</div>`;
421
- messagesContainer.appendChild(messageEl);
422
- messagesContainer.scrollTop = messagesContainer.scrollHeight;
423
- }
533
+ .welcome-content {
534
+ max-width: 100%;
535
+ padding-top: 40px;
536
+ }
424
537
 
425
- _showTypingIndicator() {
426
- const messagesContainer = this.container.querySelector("#chat-messages");
427
- const indicator = document.createElement("div");
428
- indicator.className = "chat-message bot";
429
- indicator.id = "typing-indicator";
430
- indicator.innerHTML = `
431
- <div class="typing-indicator">
432
- <div class="typing-dot"></div>
433
- <div class="typing-dot"></div>
434
- <div class="typing-dot"></div>
435
- </div>
436
- `;
437
- messagesContainer.appendChild(indicator);
438
- messagesContainer.scrollTop = messagesContainer.scrollHeight;
439
- }
538
+ .chat-drawer {
539
+ width: 85% !important; /* Wider drawer on mobile */
540
+ }
541
+ }
440
542
 
441
- _hideTypingIndicator() {
442
- const indicator = this.container.querySelector("#typing-indicator");
443
- if (indicator) indicator.remove();
444
- }
543
+ /* Drawer Styles */
544
+ .chat-drawer-overlay {
545
+ position: absolute;
546
+ top: 0;
547
+ left: 0;
548
+ right: 0;
549
+ bottom: 0;
550
+ z-index: 2000;
551
+ display: flex;
552
+ pointer-events: none;
553
+ visibility: hidden;
554
+ }
555
+
556
+ .chat-drawer-overlay.visible {
557
+ pointer-events: auto;
558
+ visibility: visible;
559
+ }
560
+
561
+ .chat-drawer {
562
+ width: 65%;
563
+ background: white;
564
+ height: 100%;
565
+ transform: translateX(-100%);
566
+ transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
567
+ display: flex;
568
+ flex-direction: column;
569
+ z-index: 2002;
570
+ box-shadow: 4px 0 24px rgba(0,0,0,0.1);
571
+ }
572
+
573
+ .chat-drawer-overlay.visible .chat-drawer {
574
+ transform: translateX(0);
575
+ }
576
+
577
+ .drawer-backdrop {
578
+ flex: 1;
579
+ background: rgba(0, 0, 0, 0.5);
580
+ opacity: 0;
581
+ transition: opacity 0.3s ease;
582
+ backdrop-filter: blur(2px);
583
+ cursor: pointer;
584
+ }
585
+
586
+ .chat-drawer-overlay.visible .drawer-backdrop {
587
+ opacity: 1;
588
+ }
589
+
590
+ .drawer-header {
591
+ padding: 24px;
592
+ border-bottom: 1px solid #f1f5f9;
593
+ }
594
+
595
+ .drawer-title {
596
+ font-size: 20px;
597
+ font-weight: 600;
598
+ color: ${this.primaryColor};
599
+ }
600
+
601
+ .drawer-content {
602
+ flex: 1;
603
+ padding: 16px;
604
+ display: flex;
605
+ flex-direction: column;
606
+ gap: 8px;
607
+ overflow-y: auto;
608
+ }
609
+
610
+ .drawer-item {
611
+ display: flex;
612
+ align-items: center;
613
+ gap: 12px;
614
+ padding: 12px 16px;
615
+ background: transparent;
616
+ border: none;
617
+ border-radius: 8px;
618
+ color: #475569;
619
+ font-size: 15px;
620
+ font-weight: 500;
621
+ cursor: pointer;
622
+ transition: all 0.2s;
623
+ text-align: left;
624
+ }
625
+
626
+ .drawer-item:hover {
627
+ background: #f1f5f9;
628
+ color: ${this.primaryColor};
629
+ }
630
+
631
+ .drawer-item svg {
632
+ opacity: 0.7;
633
+ }
634
+
635
+ .drawer-item:hover svg {
636
+ opacity: 1;
637
+ color: ${this.primaryColor};
638
+ }
639
+
640
+ .drawer-footer {
641
+ padding: 16px 24px;
642
+ border-top: 1px solid #f1f5f9;
643
+ }
644
+
645
+ .drawer-version {
646
+ font-size: 12px;
647
+ color: #94a3b8;
648
+ text-align: center;
649
+ }
650
+
651
+ /* Language Selector Styles */
652
+ .language-selector-container {
653
+ margin-top: 8px;
654
+ margin-bottom: 8px;
655
+ }
656
+
657
+ .language-label {
658
+ font-size: 11px;
659
+ font-weight: 600;
660
+ color: #94a3b8;
661
+ margin-bottom: 6px;
662
+ text-transform: uppercase;
663
+ letter-spacing: 0.5px;
664
+ padding-left: 4px;
665
+ }
666
+
667
+ .custom-select {
668
+ position: relative;
669
+ width: 100%;
670
+ user-select: none;
671
+ }
672
+
673
+ .select-trigger {
674
+ display: flex;
675
+ align-items: center;
676
+ justify-content: space-between;
677
+ padding: 10px 12px;
678
+ background: #f8fafc;
679
+ border: 1px solid #e2e8f0;
680
+ border-radius: 8px;
681
+ cursor: pointer;
682
+ transition: all 0.2s;
683
+ font-size: 14px;
684
+ color: #334155;
685
+ }
686
+
687
+ .select-trigger:hover {
688
+ border-color: ${this.primaryColor};
689
+ background: white;
690
+ }
691
+
692
+ .select-trigger.active {
693
+ border-color: ${this.primaryColor};
694
+ background: white;
695
+ box-shadow: 0 0 0 2px rgba(26, 92, 75, 0.1);
696
+ }
697
+
698
+ .select-options {
699
+ position: absolute;
700
+ top: calc(100% + 4px);
701
+ left: 0;
702
+ right: 0;
703
+ background: white;
704
+ border: 1px solid #e2e8f0;
705
+ border-radius: 8px;
706
+ box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
707
+ max-height: 200px;
708
+ overflow-y: auto;
709
+ z-index: 50;
710
+ display: none;
711
+ opacity: 0;
712
+ transform: translateY(-10px);
713
+ transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
714
+ }
715
+
716
+ .select-options.open {
717
+ display: block;
718
+ opacity: 1;
719
+ transform: translateY(0);
720
+ }
721
+
722
+ .select-option {
723
+ padding: 10px 12px;
724
+ font-size: 14px;
725
+ color: #334155;
726
+ cursor: pointer;
727
+ transition: all 0.1s;
728
+ }
729
+
730
+ .select-option:hover {
731
+ background: #f1f5f9;
732
+ color: ${this.primaryColor};
733
+ }
734
+
735
+ .select-option.selected {
736
+ background: rgba(26, 92, 75, 0.08);
737
+ color: ${this.primaryColor};
738
+ font-weight: 500;
739
+ }
740
+
741
+ .chevron {
742
+ transition: transform 0.2s ease;
743
+ color: #94a3b8;
744
+ }
745
+
746
+ .select-trigger.active .chevron {
747
+ transform: rotate(180deg);
748
+ color: ${this.primaryColor};
749
+ }
750
+
751
+ /* Thread List Styles */
752
+ .threads-container {
753
+ flex: 1;
754
+ overflow-y: auto;
755
+ display: flex;
756
+ flex-direction: column;
757
+ gap: 4px;
758
+ padding-top: 8px;
759
+ }
760
+
761
+ .threads-loading {
762
+ padding: 16px;
763
+ text-align: center;
764
+ color: #94a3b8;
765
+ font-size: 13px;
766
+ }
767
+
768
+ .thread-item {
769
+ display: flex;
770
+ flex-direction: column;
771
+ padding: 10px 12px;
772
+ border-radius: 8px;
773
+ cursor: pointer;
774
+ transition: all 0.2s;
775
+ text-align: left;
776
+ border: none;
777
+ background: transparent;
778
+ width: 100%;
779
+ color: #475569;
780
+ }
781
+
782
+ .thread-item:hover {
783
+ background-color: #f1f5f9; /* action.hover */
784
+ color: ${this.primaryColor};
785
+ }
786
+
787
+ .thread-item.selected {
788
+ background-color: rgba(26, 92, 75, 0.08); /* action.selected */
789
+ }
790
+
791
+ .thread-content {
792
+ font-size: 0.9rem;
793
+ color: #334155;
794
+ line-height: 1.3;
795
+ margin-bottom: 4px;
796
+ display: -webkit-box;
797
+ -webkit-line-clamp: 2;
798
+ -webkit-box-orient: vertical;
799
+ overflow: hidden;
800
+ font-weight: 500;
801
+ }
802
+
803
+ .thread-date {
804
+ font-size: 0.75rem;
805
+ font-weight: 600;
806
+ color: #94a3b8;
807
+ }
808
+
809
+ .no-history {
810
+ padding: 16px;
811
+ text-align: center;
812
+ color: #94a3b8;
813
+ font-size: 14px;
814
+ }
815
+ `;
816
+ document.head.appendChild(style);
817
+ }
818
+
819
+ _renderScreen() {
820
+ const screenContainer = this.container.querySelector("#chat-screen-container");
821
+
822
+ switch (this.currentScreen) {
823
+ case "welcome":
824
+ this._renderWelcomeScreen(screenContainer);
825
+ break;
826
+ case "text":
827
+ this._renderTextChatScreen(screenContainer);
828
+ break;
829
+ case "audio":
830
+ this._renderAudioChatScreen(screenContainer);
831
+ break;
832
+ }
833
+ }
834
+
835
+ _initScreens() {
836
+ // Initialize text chat screen
837
+ this.textChatScreen = new TextChatScreen({
838
+ title: this.title,
839
+ placeholder: this.placeholder,
840
+ primaryColor: this.primaryColor,
841
+ onMessage: (text, respond) => {
842
+ this._handleUserMessage(text, respond);
843
+ },
844
+ onBack: () => {
845
+ this.currentScreen = "welcome";
846
+ this._renderScreen();
847
+ },
848
+ onOpenDrawer: () => {
849
+ this._toggleDrawer(true);
850
+ },
851
+ onClose: () => {
852
+ const expanded = this.container.querySelector("#chat-expanded");
853
+ const toggle = this.container.querySelector("#chat-toggle");
854
+ expanded.classList.remove("visible");
855
+ toggle.style.display = "flex";
856
+ this.currentScreen = "welcome";
857
+ this.messages = [];
858
+ this.contentBlocks = [];
859
+ this._initScreens();
860
+ },
861
+ messages: this.messages,
862
+ sendMessage: (text, contentBlocks) => {
863
+ return this.sendMessage(text, contentBlocks);
864
+ },
865
+ contentBlocks: this.contentBlocks,
866
+ onContentBlocksChange: (contentBlocks) => {
867
+ this.contentBlocks = contentBlocks;
868
+ },
869
+ navigateToAudioScreen: () => {
870
+ this._navigateToScreen("audio")
871
+ }
872
+ });
873
+
874
+ // Initialize audio chat screen
875
+ this.audioChatScreen = new AudioChatScreen({
876
+ title: this.title,
877
+ primaryColor: this.primaryColor,
878
+ onRecordStart: () => {
879
+ // Handle recording start
880
+ },
881
+ onRecordStop: () => {
882
+ // Handle recording stop
883
+ },
884
+ onBack: () => {
885
+ this.currentScreen = "welcome";
886
+ this._renderScreen();
887
+ },
888
+ onOpenDrawer: () => {
889
+ this._toggleDrawer(true);
890
+ },
891
+ onClose: () => {
892
+ const expanded = this.container.querySelector("#chat-expanded");
893
+ const toggle = this.container.querySelector("#chat-toggle");
894
+ expanded.classList.remove("visible");
895
+ toggle.style.display = "flex";
896
+ this.currentScreen = "welcome";
897
+ this.messages = [];
898
+ this._initScreens();
899
+ },
900
+ messages: this.messages,
901
+ sendMessage: (text, contentBlocks) => {
902
+ return this.sendMessage(text, contentBlocks);
903
+ },
904
+ selectedLanguage: this.selectedLanguage,
905
+ navigateToTextScreen: () => {
906
+ this._navigateToScreen("text")
907
+ }
908
+ });
909
+ }
910
+
911
+ _renderWelcomeScreen(container) {
912
+ container.innerHTML = `
913
+ <main class="welcome-screen">
914
+ <div class="chat-header">
915
+ <div class="chat-header-content visible">
916
+ <div class="chat-header-text">
917
+ <div class="chat-title">${this.title}</div>
918
+ </div>
919
+ </div>
920
+ <button class="chat-close" id="text-chat-close">
921
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
922
+ <line x1="18" y1="6" x2="6" y2="18"></line>
923
+ <line x1="6" y1="6" x2="18" y2="18"></line>
924
+ </svg>
925
+ </button>
926
+ </div>
927
+ <div >
928
+ <div class="welcome-content">
929
+ <div class="gradient-sphere-welcome-screen">
930
+ <div class="sphere-highlight">
931
+ </div>
932
+ </div>
933
+
934
+ <div class="welcome-text">
935
+ <p class="greeting">Hello!</p>
936
+ <p class="intro">
937
+ We are your Krishi Vigyan Sahayak—KVS, a companion to help with every farming question! Tell us, what do you want to know today?
938
+ </p>
939
+ </div>
940
+
941
+ <div class="action-buttons">
942
+ <button
943
+ class="primary-button !rounded-full"
944
+ id="welcome-audio-btn"
945
+ >
946
+ Let's talk &#8203; &#8203; <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-mic-icon lucide-mic"><path d="M12 19v3"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><rect x="9" y="2" width="6" height="13" rx="3"/></svg>
947
+ </button>
948
+ </div>
949
+
950
+
951
+
952
+ </div>
953
+ </div>
954
+ </main>
955
+ `;
956
+
957
+ // Bind welcome screen events
958
+ // const textBtn = container.querySelector("#welcome-text-btn");
959
+ const audioBtn = container.querySelector("#welcome-audio-btn");
960
+ const closeBtn = container.querySelector("#text-chat-close");
961
+
962
+ // textBtn.addEventListener("click", () => this._navigateToScreen("text"));
963
+ audioBtn.addEventListener("click", () => this._navigateToScreen("audio"));
964
+
965
+ if (closeBtn) {
966
+ closeBtn.addEventListener("click", () => {
967
+ const expanded = this.container.querySelector("#chat-expanded");
968
+ const toggle = this.container.querySelector("#chat-toggle");
969
+ expanded.classList.remove("visible");
970
+ toggle.style.display = "flex";
971
+ this.currentScreen = "welcome";
972
+ this.messages = [];
973
+ this._initScreens();
974
+ });
975
+ }
976
+ }
977
+
978
+ _renderTextChatScreen(container) {
979
+ if (this.textChatScreen) {
980
+ // Sync contentBlocks before rendering
981
+ this.textChatScreen.contentBlocks = this.contentBlocks;
982
+ this.textChatScreen.messages = this.messages;
983
+ this.textChatScreen.render(container);
984
+ }
985
+ }
986
+
987
+ _renderAudioChatScreen(container) {
988
+ if (this.audioChatScreen) {
989
+ this.audioChatScreen.messages = this.messages;
990
+ this.audioChatScreen.render(container);
991
+ }
992
+ }
993
+
994
+
995
+
996
+ _navigateToScreen(screen) {
997
+ this.currentScreen = screen;
998
+ this._renderScreen();
999
+ }
1000
+
1001
+ _populateLanguageOptions() {
1002
+ const optionsContainer = this.container.querySelector("#language-options");
1003
+ if (!optionsContainer) return;
1004
+
1005
+ optionsContainer.innerHTML = this.languageOptions.map(opt => `
1006
+ <div class="select-option ${opt.value === this.selectedLanguage ? 'selected' : ''}" data-value="${opt.value}">
1007
+ ${opt.label}
1008
+ </div>
1009
+ `).join('');
1010
+
1011
+ this._updateSelectedLanguageDisplay();
1012
+ }
1013
+
1014
+ _updateSelectedLanguageDisplay() {
1015
+ const textSpan = this.container.querySelector("#selected-language-text");
1016
+ if (textSpan) {
1017
+ const option = this.languageOptions.find(opt => opt.value === this.selectedLanguage);
1018
+ textSpan.textContent = option ? option.label : "English";
1019
+ }
1020
+ }
1021
+
1022
+ _bindLanguageSelectorEvents() {
1023
+ const selector = this.container.querySelector("#language-selector");
1024
+ const trigger = this.container.querySelector("#language-trigger");
1025
+ const optionsFn = this.container.querySelector("#language-options");
1026
+
1027
+ if (trigger && optionsFn) {
1028
+ trigger.addEventListener("click", (e) => {
1029
+ e.stopPropagation();
1030
+ const isOpen = optionsFn.classList.contains("open");
1031
+ if (isOpen) {
1032
+ optionsFn.classList.remove("open");
1033
+ trigger.classList.remove("active");
1034
+ } else {
1035
+ optionsFn.classList.add("open");
1036
+ trigger.classList.add("active");
1037
+ }
1038
+ });
1039
+
1040
+ const options = optionsFn.querySelectorAll(".select-option");
1041
+ options.forEach(opt => {
1042
+ opt.addEventListener("click", (e) => {
1043
+ const value = e.currentTarget.dataset.value;
1044
+ this.selectedLanguage = value;
1045
+
1046
+ // Update UI
1047
+ this._updateSelectedLanguageDisplay();
1048
+ optionsFn.querySelectorAll(".select-option").forEach(o => o.classList.remove("selected"));
1049
+ e.currentTarget.classList.add("selected");
1050
+
1051
+ // Close dropdown
1052
+ optionsFn.classList.remove("open");
1053
+ trigger.classList.remove("active");
1054
+
1055
+ console.log("Language selected:", this.selectedLanguage);
1056
+ });
1057
+ });
1058
+
1059
+ // Close on click outside
1060
+ document.addEventListener("click", (e) => {
1061
+ if (selector && !selector.contains(e.target)) {
1062
+ optionsFn.classList.remove("open");
1063
+ trigger.classList.remove("active");
1064
+ }
1065
+ });
1066
+ }
1067
+ }
1068
+
1069
+ async _fetchThreads() {
1070
+ const threadsContainer = this.container.querySelector("#drawer-threads");
1071
+ if (!threadsContainer) return;
1072
+
1073
+ threadsContainer.innerHTML = '<div class="threads-loading">Loading history...</div>';
1074
+
1075
+ try {
1076
+ const storedUser = localStorage.getItem("DfsWeb.user-info");
1077
+ const user = storedUser ? JSON.parse(storedUser) : null;
1078
+
1079
+ if (!user?.uuid) {
1080
+ threadsContainer.innerHTML = '<div class="no-history">Please log in to view history</div>';
1081
+ return;
1082
+ }
1083
+
1084
+ console.log("USER ID", user.id, "USER UUID", user.uuid);
1085
+
1086
+ const data = await this.getUserThreads({ userId: user.id, userUuid: user.uuid });
1087
+ console.log("THREAD DATA", data);
1088
+
1089
+ const threads = data.threads || [];
1090
+ const threadsWithHistory = threads.filter((thread) => thread.history && thread.history.length > 0);
1091
+
1092
+ this._renderThreadList(threadsWithHistory);
1093
+
1094
+ } catch (error) {
1095
+ console.error("UNEXPECTED ERROR IN FETCHING THREADS", error.message);
1096
+ threadsContainer.innerHTML = '<div class="no-history">Failed to load history</div>';
1097
+ }
1098
+ }
1099
+
1100
+ _renderThreadList(threads) {
1101
+ const threadsContainer = this.container.querySelector("#drawer-threads");
1102
+ if (!threadsContainer) return;
1103
+
1104
+ if (threads.length === 0) {
1105
+ threadsContainer.innerHTML = '<div class="no-history">No history available</div>';
1106
+ return;
1107
+ }
1108
+
1109
+ threadsContainer.innerHTML = '';
1110
+
1111
+ threads.forEach(thread => {
1112
+ const isSelected = thread.thread_id === this.threadId; // Use current threadId
1113
+
1114
+ const threadItem = document.createElement('div');
1115
+ threadItem.className = `thread-item ${isSelected ? 'selected' : ''}`;
1116
+
1117
+ // Get primary text (first user message)
1118
+ const primaryText = thread.history[0]?.values?.messages[0]?.content || "New Chat";
1119
+ // Handle array content (if content is array of blocks)
1120
+ let displayText = primaryText;
1121
+ if (Array.isArray(primaryText)) {
1122
+ const textBlock = primaryText.find(b => b.type === 'text');
1123
+ displayText = textBlock ? textBlock.text : "Multimedia Message";
1124
+ } else if (typeof primaryText === 'object') {
1125
+ displayText = "Message";
1126
+ }
1127
+
1128
+ const date = new Date(thread.created_at).toLocaleString();
1129
+
1130
+ threadItem.innerHTML = `
1131
+ <div class="thread-content">${displayText}</div>
1132
+ <div class="thread-date">${date}</div>
1133
+ `;
1134
+
1135
+ threadItem.addEventListener('click', () => {
1136
+ this._handleThreadSelect(thread.thread_id);
1137
+ });
1138
+
1139
+ threadsContainer.appendChild(threadItem);
1140
+ });
1141
+ }
1142
+
1143
+ _handleThreadSelect(threadId) {
1144
+ console.log("Select thread:", threadId);
1145
+ this.threadId = threadId;
1146
+ this._toggleDrawer(false);
1147
+
1148
+ // Switch to text screen to show history
1149
+ this.currentScreen = "text";
1150
+
1151
+ // Clear current messages
1152
+ this.messages = [];
1153
+ this.setIsLoading = true; // Set loading state if you have setter, otherwise this.isLoading = true
1154
+ this.isLoading = true;
1155
+
1156
+ // Re-initialize screens (clears them)
1157
+ // this._initScreens(); // Can't fully re-init as it might break event listeners
1158
+ // Better to just load history and render
1159
+
1160
+ this._renderScreen();
1161
+
1162
+ // Load history for this thread
1163
+ this.loadHistory(threadId).then(() => {
1164
+ this.isLoading = false;
1165
+ this._renderScreen(); // Re-render with new messages
1166
+ });
1167
+ }
1168
+
1169
+ _bindEvents() {
1170
+ const toggle = this.container.querySelector("#chat-toggle");
1171
+ const expanded = this.container.querySelector("#chat-expanded");
1172
+
1173
+ // Ensure toggle button is visible
1174
+ if (toggle) {
1175
+ toggle.style.display = "flex";
1176
+ }
1177
+
1178
+ toggle.addEventListener("click", () => {
1179
+ console.log("Clicked")
1180
+ toggle.style.display = "none";
1181
+ expanded.classList.add("visible");
1182
+ this.currentScreen = "welcome";
1183
+ this._renderScreen();
1184
+ });
1185
+
1186
+ // Drawer events
1187
+ const drawerBackdrop = this.container.querySelector("#drawer-backdrop");
1188
+ if (drawerBackdrop) {
1189
+ drawerBackdrop.addEventListener("click", () => {
1190
+ this._toggleDrawer(false);
1191
+ });
1192
+ }
1193
+
1194
+ const drawerItems = this.container.querySelectorAll(".drawer-item");
1195
+ drawerItems.forEach(item => {
1196
+ item.addEventListener("click", (e) => {
1197
+ // Handle drawer item click
1198
+ this._toggleDrawer(false);
1199
+ const targetId = e.currentTarget.id;
1200
+ if (targetId === "drawer-new-chat") {
1201
+ this._resetChat();
1202
+ }
1203
+ });
1204
+ });
1205
+
1206
+ this._bindLanguageSelectorEvents();
1207
+ }
1208
+
1209
+ _toggleDrawer(show) {
1210
+ const overlay = this.container.querySelector("#chat-drawer-overlay");
1211
+ if (!overlay) return;
1212
+
1213
+ if (show) {
1214
+ overlay.classList.add("visible");
1215
+ // Fetch threads when drawer is opened
1216
+ this._fetchThreads();
1217
+ } else {
1218
+ overlay.classList.remove("visible");
1219
+ }
1220
+ }
1221
+
1222
+ _resetChat() {
1223
+ this.messages = [];
1224
+ this.threadId = null;
1225
+ this.contentBlocks = [];
1226
+ // this.currentScreen = "welcome";
1227
+ this._initScreens();
1228
+ this._renderScreen();
1229
+ }
1230
+
1231
+ _handleUserMessage(text, respond) {
1232
+ // Simple echo response - just returns what the user typed
1233
+ // The respond callback is provided by TextChatScreen
1234
+ if (respond) {
1235
+ respond(`You said: "${text}"`);
1236
+ }
1237
+ }
1238
+
1239
+ // Add message to shared messages array and update UI
1240
+ _addMessageToArray(message) {
1241
+ this.messages.push(message);
1242
+ this._notifyScreensUpdate();
1243
+ }
1244
+
1245
+ // Update message in shared messages array
1246
+ _updateMessageInArray(messageId, updates) {
1247
+ const index = this.messages.findIndex(msg => msg.id === messageId);
1248
+ if (index !== -1) {
1249
+ this.messages[index] = { ...this.messages[index], ...updates };
1250
+ this._notifyScreensUpdate();
1251
+ }
1252
+ }
1253
+
1254
+ // Notify all screens to update their UI
1255
+ _notifyScreensUpdate() {
1256
+ if (this.textChatScreen && this.textChatScreen.container) {
1257
+ this.textChatScreen._syncMessages(this.messages);
1258
+ }
1259
+ if (this.audioChatScreen && this.audioChatScreen.container) {
1260
+ this.audioChatScreen._syncMessages(this.messages);
1261
+ }
1262
+ }
1263
+
1264
+ // Send message function adapted from React version
1265
+ async sendMessage(inputValue, contentBlocks = []) {
1266
+ if ((!inputValue.trim() && contentBlocks.length === 0) || this.isLoading) {
1267
+ return;
1268
+ }
1269
+
1270
+
1271
+ console.log(
1272
+ "📤 Sending text message - Language:",
1273
+ this.selectedLanguage,
1274
+ "Assistant ID:",
1275
+ this.assistantId || "Not available",
1276
+ "Thread ID:",
1277
+ this.threadId || "Not available",
1278
+ "Access token:",
1279
+ this.accessToken ? "Present" : "Empty - backend will handle",
1280
+ );
1281
+
1282
+ // Prepare content blocks for the message
1283
+ const messageContent = [];
1284
+
1285
+ // Add text content if present
1286
+ if (inputValue.trim()) {
1287
+ const textContent = inputValue;
1288
+ messageContent.push({ type: "text", text: textContent });
1289
+ }
1290
+
1291
+ // Add file attachments
1292
+ contentBlocks.forEach((block) => {
1293
+ messageContent.push(block);
1294
+ });
1295
+
1296
+ // Create user message for display
1297
+ const userMessage = {
1298
+ id: Date.now(),
1299
+ content: inputValue.trim() || "📎 File attachments",
1300
+ sender: "user",
1301
+ timestamp: new Date().toISOString(),
1302
+ attachments: contentBlocks.length > 0 ? contentBlocks : null,
1303
+ };
1304
+
1305
+ console.log("USER MESSAGE", userMessage);
1306
+ console.log("USER MESSAGE CONTENTBLOCKS", contentBlocks);
1307
+ console.log("USER MESSAGE CONTENT", messageContent);
1308
+
1309
+ this._addMessageToArray(userMessage);
1310
+ this.contentBlocks = [];
1311
+
1312
+ // Clear contentBlocks in text chat screen
1313
+ if (this.textChatScreen) {
1314
+ this.textChatScreen.contentBlocks = [];
1315
+ this.textChatScreen.renderFilePreview();
1316
+ this.textChatScreen.updateSendButton();
1317
+ }
1318
+
1319
+ // Reset states for text messages
1320
+ this.playedAudioIds.clear();
1321
+ this.currentInputAudio = null;
1322
+ this.submissionInProgress = false;
1323
+ this.processingAudioId = null;
1324
+
1325
+ this.isLoading = true;
1326
+
1327
+ try {
1328
+ // Always attempt to send message, let backend handle auth
1329
+ await this.sendMessageWithStreaming(messageContent);
1330
+ } catch (error) {
1331
+ console.error("Error sending message:", error);
1332
+ const errorMessage = {
1333
+ id: Date.now() + 1,
1334
+ content: "Sorry, I encountered an error. Please try again.",
1335
+ sender: "assistant",
1336
+ timestamp: new Date().toISOString(),
1337
+ isError: true,
1338
+ };
1339
+ this._addMessageToArray(errorMessage);
1340
+ } finally {
1341
+ this.isLoading = false;
1342
+ }
1343
+ }
1344
+
1345
+ // Send message with streaming function adapted from React version
1346
+ async sendMessageWithStreaming(messageContent) {
1347
+ console.log("USER MESSAGE STREAMING", messageContent);
1348
+ console.log(
1349
+ "📤 Sending text message - Language:",
1350
+ this.selectedLanguage,
1351
+ "Access token:",
1352
+ this.accessToken ? "Present" : "Not found",
1353
+ );
1354
+
1355
+ const assistantMessage = {
1356
+ id: Date.now() + 1,
1357
+ content: "",
1358
+ sender: "assistant",
1359
+ timestamp: new Date().toISOString(),
1360
+ isStreaming: true,
1361
+ isProcessing: true,
1362
+ textSessionId: Date.now() + 1,
1363
+ hasAudioResponse: false,
1364
+ inputType: "text",
1365
+ };
1366
+
1367
+ this._addMessageToArray(assistantMessage);
1368
+
1369
+ let latestRunId = null;
1370
+
1371
+ try {
1372
+ // Get the latest checkpoint to resume from the latest state
1373
+ const latestCheckpoint = await this.getLatestCheckpoint(this.threadId);
1374
+
1375
+ console.log("📤 Sending message to backend:", {
1376
+ input: {
1377
+ messages: [
1378
+ {
1379
+ id: `msg-${Date.now()}`,
1380
+ type: "human",
1381
+ content: messageContent,
1382
+ },
1383
+ ],
1384
+ user_language: this.selectedLanguage,
1385
+ access_token: "[redacted]",
1386
+ user_info: JSON.stringify(this.userInfo),
1387
+ },
1388
+ config: { configurable: {} },
1389
+ metadata: {
1390
+ supabaseAccessToken: "[redacted]",
1391
+ user_language: this.selectedLanguage,
1392
+ input_type: "text",
1393
+ audio_content: null,
1394
+ },
1395
+ stream_mode: ["values", "messages-tuple", "custom"],
1396
+ stream_subgraphs: true,
1397
+ assistant_id: this.assistantId,
1398
+ on_disconnect: "cancel",
1399
+ ...(latestCheckpoint && { checkpoint: latestCheckpoint }),
1400
+ });
1401
+
1402
+ const response = await fetch(
1403
+ `${this.langgraphUrl}/threads/${this.threadId}/runs/stream`,
1404
+ {
1405
+ method: "POST",
1406
+ headers: this.getHeaders(),
1407
+ body: JSON.stringify({
1408
+ input: {
1409
+ messages: [
1410
+ {
1411
+ id: `msg-${Date.now()}`,
1412
+ type: "human",
1413
+ content: messageContent,
1414
+ },
1415
+ ],
1416
+ user_language: this.selectedLanguage,
1417
+ access_token: this.accessToken,
1418
+ user_info: JSON.stringify(this.userInfo),
1419
+ },
1420
+ config: { configurable: {} },
1421
+ metadata: {
1422
+ supabaseAccessToken: this.supabaseToken,
1423
+ user_language: this.selectedLanguage,
1424
+ },
1425
+ stream_mode: ["values", "messages-tuple", "custom"],
1426
+ stream_subgraphs: true,
1427
+ assistant_id: this.assistantId,
1428
+ on_disconnect: "cancel",
1429
+ ...(latestCheckpoint && { checkpoint: latestCheckpoint }),
1430
+ }),
1431
+ },
1432
+ );
1433
+
1434
+ if (!response.ok) {
1435
+ throw new Error(`HTTP error! status: ${response.status}`);
1436
+ }
1437
+
1438
+ // Handle streaming response
1439
+ const reader = response.body.getReader();
1440
+ const decoder = new TextDecoder();
1441
+ let buffer = "";
1442
+ let currentMessage = ""; // Local to this function scope
1443
+ let bestMessageText = "";
1444
+ let bestMessagePriority = -1;
1445
+ let lastUpdateTime = 0;
1446
+ const UPDATE_THROTTLE = 150; // Throttle updates to max ~7 per second
1447
+ const requestId = Date.now(); // Unique ID for this request
1448
+ let currentEvent = null; // Track current event type
1449
+ let currentData = null; // Track current data
1450
+ let hasReceivedMeaningfulResponse = false; // Track if we've received a meaningful response
1451
+ let finalResponse = ""; // Store the final meaningful response
1452
+ let latestUiAction = null; // Track the last ui_action from the last ui_action_mapper
1453
+ let endEventFinalized = false; // Track if we finalized on 'end' event
1454
+ let endFinalContent = ""; // Content used at 'end' event
1455
+ let currentAdditionalKwargs = null; // Chart-related additional kwargs captured from stream
1456
+ let chartUrlFromViz = null; // If stream provides a chart image URL, store it here and use it for the assistant message
1457
+
1458
+ console.log(
1459
+ "🔍 Starting to process streaming response for requestId:",
1460
+ requestId,
1461
+ );
1462
+
1463
+ // Prioritize human-readable assistant text over tool/JSON outputs
1464
+ const getNodePriority = (nodeKey) => {
1465
+ if (!nodeKey) return 0;
1466
+ const key = String(nodeKey).toLowerCase();
1467
+ if (
1468
+ key.includes("mdms_assistant") ||
1469
+ key.includes("grievance_assistant") ||
1470
+ key.includes("mandiprice_assistant")
1471
+ ) return 0;
1472
+ if (key.includes("assistant") && !key.includes("tools")) return 3;
1473
+ if (key.includes("response_processor")) return 2;
1474
+ if (key.includes("post_assistant")) return 2;
1475
+ if (key.includes("ui_action_mapper")) return 1;
1476
+ return 0;
1477
+ };
1478
+
1479
+ while (true) {
1480
+ const { done, value } = await reader.read();
1481
+ if (done) break;
1482
+
1483
+ buffer += decoder.decode(value, { stream: true });
1484
+ const lines = buffer.split("\n");
1485
+
1486
+ buffer = lines.pop() || "";
1487
+
1488
+ for (const line of lines) {
1489
+ if (line.trim() === "") continue;
1490
+
1491
+ console.log("📝 Processing SSE line:", {
1492
+ line: line.substring(0, 100) + (line.length > 100 ? "..." : ""),
1493
+ requestId: requestId,
1494
+ });
1495
+
1496
+ if (line.startsWith("data:")) {
1497
+ try {
1498
+ const data = JSON.parse(line.slice(5).trim());
1499
+ if (data.run_id) {
1500
+ console.log("🟢 Run ID:", data.run_id);
1501
+ latestRunId = data.run_id;
1502
+ }
1503
+ } catch (err) {
1504
+ console.error("Error parsing JSON:", err, line);
1505
+ }
1506
+ }
1507
+
1508
+ if (line.startsWith("event: ")) {
1509
+ currentEvent = line.slice(7).trim();
1510
+ console.log("🎯 Event type:", currentEvent);
1511
+ } else if (line.startsWith("data: ")) {
1512
+ const jsonStr = line.slice(6).trim();
1513
+
1514
+ if (jsonStr === "[DONE]") {
1515
+ console.log("🏁 Stream completed");
1516
+ break;
1517
+ }
1518
+
1519
+ try {
1520
+ const data = JSON.parse(jsonStr);
1521
+ currentData = data;
1522
+
1523
+ if (data.run_id) {
1524
+ console.log(
1525
+ "🟢 Capturing run_id from parsed data:",
1526
+ data.run_id,
1527
+ );
1528
+ latestRunId = data.run_id;
1529
+ }
1530
+
1531
+ // Handle end event
1532
+ if (currentEvent === "end") {
1533
+ console.log(
1534
+ "🏁 Received event: end - finalizing message with run_id:",
1535
+ latestRunId,
1536
+ );
1537
+ if (data.run_id) {
1538
+ latestRunId = data.run_id;
1539
+ console.log(
1540
+ "🟢 Updated run_id from end event:",
1541
+ latestRunId,
1542
+ );
1543
+ }
1544
+
1545
+ if (currentMessage && currentMessage.length > 0) {
1546
+ this._updateMessageInArray(assistantMessage.id, {
1547
+ content: currentMessage,
1548
+ additional_kwargs: currentAdditionalKwargs,
1549
+ isStreaming: false,
1550
+ isProcessing: false,
1551
+ hasAudioResponse: this.messages.find(m => m.id === assistantMessage.id)?.hasAudioResponse || false,
1552
+ latestRunId: latestRunId,
1553
+ });
1554
+ endEventFinalized = true;
1555
+ endFinalContent = currentMessage;
1556
+ } else if (latestRunId) {
1557
+ this._updateMessageInArray(assistantMessage.id, {
1558
+ latestRunId: latestRunId,
1559
+ isStreaming: false,
1560
+ isProcessing: false,
1561
+ });
1562
+ }
1563
+ }
1564
+
1565
+ console.log("🔍 Parsed SSE data:", {
1566
+ event: currentEvent,
1567
+ hasData: !!data,
1568
+ dataKeys: data ? Object.keys(data) : "no data",
1569
+ topLevelKeys: Object.keys(data),
1570
+ hasAudioContent: data?.audio_content ? "YES" : "NO",
1571
+ hasResponseProcessor: data?.response_processor ? "YES" : "NO",
1572
+ hasRunId: data?.run_id ? "YES" : "NO",
1573
+ runId: data?.run_id || "N/A",
1574
+ requestId: requestId,
1575
+ });
1576
+
1577
+ // Handle Authentication from smart_router
1578
+ if (
1579
+ data.smart_router &&
1580
+ data.smart_router.access_token &&
1581
+ data.smart_router.farmer_profile &&
1582
+ data.smart_router.farmer_profile_fetched === true
1583
+ ) {
1584
+ console.log(
1585
+ "🔐 Authentication data detected in smart_router:",
1586
+ {
1587
+ hasAccessToken: !!data.smart_router.access_token,
1588
+ mobileNumber: data.smart_router.mobile_number,
1589
+ userUuid: data.smart_router.userUuid,
1590
+ hasFarmerProfile: !!data.smart_router.farmer_profile,
1591
+ farmerId: data.smart_router.farmer_profile?.individualId,
1592
+ farmerName: data.smart_router.farmer_profile?.name,
1593
+ requestId: requestId,
1594
+ },
1595
+ );
1596
+
1597
+ try {
1598
+ const smartRouter = data.smart_router;
1599
+ const farmerProfile = smartRouter.farmer_profile;
1600
+ const accessToken = smartRouter.access_token;
1601
+
1602
+ localStorage.setItem("DfsWeb.access-token", accessToken);
1603
+
1604
+ let userInfo = {};
1605
+ if (farmerProfile.user_details) {
1606
+ userInfo = { ...farmerProfile.user_details };
1607
+ userInfo.name = farmerProfile.name || userInfo.name || "";
1608
+ if (!userInfo.uuid) {
1609
+ userInfo.uuid = smartRouter.userUuid;
1610
+ }
1611
+ if (!userInfo.mobileNumber) {
1612
+ userInfo.mobileNumber = smartRouter.mobile_number ||
1613
+ farmerProfile.mobileNumber;
1614
+ }
1615
+ } else {
1616
+ userInfo = {
1617
+ id: null,
1618
+ uuid: smartRouter.userUuid,
1619
+ userName: smartRouter.mobile_number,
1620
+ name: farmerProfile.name || "",
1621
+ mobileNumber: smartRouter.mobile_number ||
1622
+ farmerProfile.mobileNumber,
1623
+ emailId: farmerProfile.email || null,
1624
+ locale: null,
1625
+ type: "CITIZEN",
1626
+ roles: [
1627
+ {
1628
+ name: "Citizen",
1629
+ code: "CITIZEN",
1630
+ tenantId: farmerProfile.tenantId || "br",
1631
+ },
1632
+ ],
1633
+ active: true,
1634
+ tenantId: farmerProfile.tenantId || "br",
1635
+ permanentCity: null,
1636
+ };
1637
+ this.setUserInfoFromDirectChatLogin(userInfo);
1638
+ }
1639
+
1640
+ this.userInfo = userInfo;
1641
+ this.accessToken = accessToken;
1642
+
1643
+ if (userInfo.uuid) {
1644
+ console.log("USER INFO FOR UPDATING THREAD", userInfo);
1645
+ if (this.threadId) {
1646
+ this.updateThread(this.threadId, userInfo.uuid)
1647
+ .then((updatedThread) => {
1648
+ console.log(
1649
+ "✅ Thread updated after authentication:",
1650
+ updatedThread,
1651
+ );
1652
+ })
1653
+ .catch((error) => {
1654
+ console.error(
1655
+ "❌ Error updating thread after authentication:",
1656
+ error.message,
1657
+ );
1658
+ });
1659
+ }
1660
+
1661
+ this.getUserThreads({
1662
+ userId: userInfo.id,
1663
+ userUuid: userInfo.uuid,
1664
+ })
1665
+ .then((data) => {
1666
+ console.log(
1667
+ "✅ Thread data fetched after authentication:",
1668
+ data,
1669
+ );
1670
+ this.setUserThreads(data.threads);
1671
+ this.setUserThreadsMetaData({
1672
+ threads_processed: data.threads_processed,
1673
+ total_history_items: data.total_history_items,
1674
+ total_threads: data.total_threads,
1675
+ });
1676
+ })
1677
+ .catch((error) => {
1678
+ console.error(
1679
+ "❌ Error fetching threads after authentication:",
1680
+ error.message,
1681
+ );
1682
+ });
1683
+ }
1684
+ } catch (authError) {
1685
+ console.error(
1686
+ "❌ Error processing authentication data:",
1687
+ authError,
1688
+ );
1689
+ }
1690
+ }
1691
+
1692
+ // Handle UI Actions
1693
+ let uiActionSource = null;
1694
+ let actions = null;
1695
+
1696
+ if (
1697
+ data.response_processor &&
1698
+ Array.isArray(data.response_processor.ui_actions)
1699
+ ) {
1700
+ actions = data.response_processor.ui_actions;
1701
+ } else if (
1702
+ data.response_processor && data.response_processor.messages &&
1703
+ Array.isArray(data.response_processor.messages) &&
1704
+ data.response_processor.messages.length > 0 &&
1705
+ data.response_processor.messages[0].additional_kwargs &&
1706
+ Array.isArray(
1707
+ data.response_processor.messages[0].additional_kwargs
1708
+ .ui_actions,
1709
+ )
1710
+ ) {
1711
+ actions =
1712
+ data.response_processor.messages[0].additional_kwargs
1713
+ .ui_actions;
1714
+ } else if (
1715
+ data.ui_action_mapper &&
1716
+ Array.isArray(data.ui_action_mapper.ui_actions)
1717
+ ) {
1718
+ uiActionSource = data.ui_action_mapper;
1719
+ actions = uiActionSource.ui_actions;
1720
+ } else if (
1721
+ data.mdms_ui_action_mapper &&
1722
+ Array.isArray(data.mdms_ui_action_mapper.ui_actions)
1723
+ ) {
1724
+ uiActionSource = data.mdms_ui_action_mapper;
1725
+ actions = uiActionSource.ui_actions;
1726
+ }
1727
+
1728
+ if (actions && actions.length > 0) {
1729
+ console.log("UI ACTIONS", actions);
1730
+ const action = actions[actions.length - 1];
1731
+ if (action.web && action.web.link) {
1732
+ let scrollToId = null;
1733
+ let navigationParams = {};
1734
+
1735
+ if (action.web.parameters) {
1736
+ if (action.web.parameters.scrollTo) {
1737
+ scrollToId = action.web.parameters.scrollTo;
1738
+ }
1739
+ navigationParams = { ...action.web.parameters };
1740
+ } else if (
1741
+ action.web.link &&
1742
+ action.web.link.includes("scrollTo=")
1743
+ ) {
1744
+ const urlParams = new URLSearchParams(
1745
+ action.web.link.split("?")[1],
1746
+ );
1747
+ scrollToId = urlParams.get("scrollTo");
1748
+ }
1749
+
1750
+ let finalLink = action.web.link;
1751
+ let finalMessage = action.message || "";
1752
+
1753
+ const hasSchemeId = action.web.parameters?.schemeId &&
1754
+ action.web.parameters.schemeId !== "";
1755
+ let hasHelpName = null;
1756
+
1757
+ if (action.web.parameters?.button_title) {
1758
+ hasHelpName = true;
1759
+ } else if (action.web.parameters?.name) {
1760
+ hasHelpName = true;
1761
+ } else {
1762
+ hasHelpName = false;
1763
+ }
1764
+
1765
+ if (!hasSchemeId && !hasHelpName) {
1766
+ finalLink = "/help";
1767
+ finalMessage =
1768
+ "Please find more information about available schemes and services";
1769
+ }
1770
+ latestUiAction = {
1771
+ content: "",
1772
+ url: finalLink && !finalLink.startsWith("http")
1773
+ ? window.location.origin + finalLink
1774
+ : finalLink,
1775
+ originalUrl: finalLink,
1776
+ uiActionType: action.ui_action,
1777
+ scrollToId: scrollToId,
1778
+ navigationParams: {
1779
+ ...navigationParams,
1780
+ ...(hasHelpName && {
1781
+ name: action.web.parameters?.button_title ||
1782
+ action.web.parameters?.name,
1783
+ }),
1784
+ },
1785
+ };
1786
+ }
1787
+ }
1788
+
1789
+ // Chart Image Extraction
1790
+ if (
1791
+ data.analytics_visualization_node &&
1792
+ data.analytics_visualization_node.messages
1793
+ ) {
1794
+ const vizMessages =
1795
+ data.analytics_visualization_node.messages;
1796
+ if (vizMessages.length > 0) {
1797
+ const vizMessage = vizMessages[vizMessages.length - 1];
1798
+
1799
+ if (
1800
+ typeof vizMessage === "string" &&
1801
+ vizMessage.includes("additional_kwargs")
1802
+ ) {
1803
+ const kwargsStart =
1804
+ vizMessage.indexOf("additional_kwargs=") + 18;
1805
+ const kwargsEnd = vizMessage.indexOf(
1806
+ "} response_metadata",
1807
+ );
1808
+
1809
+ if (kwargsStart < kwargsEnd) {
1810
+ const kwargsString = vizMessage.substring(
1811
+ kwargsStart,
1812
+ kwargsEnd + 1,
1813
+ );
1814
+ try {
1815
+ let cleanedKwargsString = kwargsString
1816
+ .replace(/'/g, '"')
1817
+ .replace(/None/g, "null")
1818
+ .replace(/True/g, "true")
1819
+ .replace(/False/g, "false");
1820
+
1821
+ const additionalKwargs = JSON.parse(
1822
+ cleanedKwargsString,
1823
+ );
1824
+
1825
+ if (additionalKwargs.chart_image_url) {
1826
+ console.log(
1827
+ "🎯 Found chart image URL:",
1828
+ additionalKwargs.chart_image_url,
1829
+ );
1830
+ currentAdditionalKwargs = additionalKwargs;
1831
+ try {
1832
+ const chartUrl = String(
1833
+ additionalKwargs.chart_image_url,
1834
+ ).trim();
1835
+ if (chartUrl.startsWith("http")) {
1836
+ chartUrlFromViz = chartUrl;
1837
+ console.log(
1838
+ "🔖 Stored chartUrlFromViz:",
1839
+ chartUrlFromViz,
1840
+ );
1841
+ }
1842
+ } catch (e) {
1843
+ console.warn(
1844
+ "Failed to store chart image URL:",
1845
+ e,
1846
+ );
1847
+ }
1848
+ } else if (additionalKwargs.antv_chart_data) {
1849
+ console.log(
1850
+ "🎯 Found chart data (fallback):",
1851
+ additionalKwargs.antv_chart_data,
1852
+ );
1853
+ currentAdditionalKwargs = additionalKwargs;
1854
+ }
1855
+ } catch (e) {
1856
+ console.warn(
1857
+ "Failed to parse chart image additional_kwargs:",
1858
+ e,
1859
+ );
1860
+ }
1861
+ }
1862
+ }
1863
+ if (typeof vizMessage === "string") {
1864
+ const contentMatch = vizMessage.match(
1865
+ /content=['"]([^'"]+)['"]/,
1866
+ );
1867
+ if (contentMatch && contentMatch[1]) {
1868
+ const extractedUrl = contentMatch[1].trim();
1869
+ if (extractedUrl.startsWith("http")) {
1870
+ chartUrlFromViz = extractedUrl;
1871
+ console.log(
1872
+ "🔖 Stored extracted chartUrlFromViz:",
1873
+ chartUrlFromViz,
1874
+ );
1875
+ }
1876
+ }
1877
+ }
1878
+ }
1879
+ }
1880
+
1881
+ // Generic Content Extraction
1882
+ let lastContent = null;
1883
+ let lastNodeKey = null;
1884
+ let lastNodeMessages = null;
1885
+ Object.keys(data).forEach((nodeKey) => {
1886
+ if (
1887
+ nodeKey !== "audio_content" &&
1888
+ nodeKey !== "audio_processor" &&
1889
+ nodeKey !== "ui_action_mapper"
1890
+ ) {
1891
+ const nodeData = data[nodeKey];
1892
+ if (
1893
+ nodeData &&
1894
+ Array.isArray(nodeData.messages) &&
1895
+ nodeData.messages.length > 0
1896
+ ) {
1897
+ lastNodeKey = nodeKey;
1898
+ lastNodeMessages = nodeData.messages;
1899
+ }
1900
+ }
1901
+ });
1902
+ if (lastNodeMessages && lastNodeMessages.length > 0) {
1903
+ let lastMessage =
1904
+ lastNodeMessages[lastNodeMessages.length - 1];
1905
+ let content = "";
1906
+ if (typeof lastMessage === "string") {
1907
+ if (
1908
+ lastMessage.startsWith("content='") &&
1909
+ lastMessage.includes("' additional_kwargs")
1910
+ ) {
1911
+ const start = lastMessage.indexOf("content='") + 9;
1912
+ const end = lastMessage.indexOf("' additional_kwargs");
1913
+ content = lastMessage
1914
+ .substring(start, end)
1915
+ .replace(/\\n/g, "\n")
1916
+ .replace(/\\t/g, "\t")
1917
+ .replace(/\\"/g, '"')
1918
+ .replace(/\\'/g, "'");
1919
+ } else if (
1920
+ lastMessage.startsWith('content="') &&
1921
+ lastMessage.includes('" additional_kwargs')
1922
+ ) {
1923
+ const start = lastMessage.indexOf('content="') + 9;
1924
+ const end = lastMessage.indexOf('" additional_kwargs');
1925
+ content = lastMessage
1926
+ .substring(start, end)
1927
+ .replace(/\\n/g, "\n")
1928
+ .replace(/\\t/g, "\t")
1929
+ .replace(/\\"/g, '"')
1930
+ .replace(/\\'/g, "'");
1931
+ } else {
1932
+ const singleQuoteMatch = lastMessage.match(
1933
+ /content='([^']+)'/,
1934
+ );
1935
+ const doubleQuoteMatch = lastMessage.match(
1936
+ /content="([^"]+)"/,
1937
+ );
1938
+ if (singleQuoteMatch) {
1939
+ content = singleQuoteMatch[1];
1940
+ } else if (doubleQuoteMatch) {
1941
+ content = doubleQuoteMatch[1];
1942
+ } else {
1943
+ content = lastMessage;
1944
+ }
1945
+ }
1946
+ } else if (lastMessage && typeof lastMessage === "object") {
1947
+ if (typeof lastMessage.content === "string") {
1948
+ content = lastMessage.content;
1949
+ } else if (
1950
+ Array.isArray(lastMessage.content) &&
1951
+ lastMessage.content.length > 0
1952
+ ) {
1953
+ const textParts = lastMessage.content
1954
+ .map((part) =>
1955
+ typeof part === "string"
1956
+ ? part
1957
+ : typeof part?.text === "string"
1958
+ ? part.text
1959
+ : typeof part?.value === "string"
1960
+ ? part.value
1961
+ : ""
1962
+ )
1963
+ .filter(Boolean);
1964
+ content = textParts.join(" ").trim();
1965
+ } else {
1966
+ content = "";
1967
+ }
1968
+ }
1969
+ if (
1970
+ typeof content === "string" &&
1971
+ content.trim().length > 0
1972
+ ) {
1973
+ const looksLikeJson = content.trim().startsWith("{") ||
1974
+ content.trim().startsWith("[");
1975
+ const priority = getNodePriority(lastNodeKey);
1976
+ if (looksLikeJson && priority < 2) {
1977
+ console.log(
1978
+ `⏭️ Skipping JSON-like content from ${lastNodeKey}`,
1979
+ );
1980
+ } else {
1981
+ const MAX_LEN = 8000;
1982
+ const safeContent = content.length > MAX_LEN
1983
+ ? content.slice(0, MAX_LEN) + "\n\n… (truncated)"
1984
+ : content;
1985
+ currentMessage = safeContent;
1986
+ if (
1987
+ priority > bestMessagePriority ||
1988
+ (priority === bestMessagePriority &&
1989
+ safeContent.length > bestMessageText.length)
1990
+ ) {
1991
+ bestMessageText = safeContent;
1992
+ bestMessagePriority = priority;
1993
+ }
1994
+ hasReceivedMeaningfulResponse = true;
1995
+ console.log(
1996
+ `🟢 Found content from ${lastNodeKey}:`,
1997
+ safeContent.substring(0, 100) + "...",
1998
+ );
1999
+ }
2000
+ }
2001
+ }
2002
+
2003
+ // Process based on event type
2004
+ if (data) {
2005
+ // Set default event type for data messages without explicit event
2006
+ const eventType = currentEvent || "values";
2007
+
2008
+ console.log("🎵 Processing data message:", {
2009
+ eventType: eventType,
2010
+ currentEvent: currentEvent,
2011
+ dataKeys: Object.keys(data),
2012
+ requestId: requestId,
2013
+ });
2014
+
2015
+ // Handle audio content in response
2016
+ if (
2017
+ data.audio_content &&
2018
+ typeof data.audio_content === "string"
2019
+ ) {
2020
+ console.log("🎵 AUDIO CONTENT FOUND in text stream:", {
2021
+ audioContentLength: data.audio_content.length,
2022
+ audioContentPreview: data.audio_content.substring(0, 20) +
2023
+ "...",
2024
+ });
2025
+
2026
+ const audioResponseId = `text_response_${requestId}_${data.audio_content.substring(
2027
+ 0,
2028
+ 30,
2029
+ )
2030
+ }`;
2031
+ const alreadyPlayed = this.playedAudioIds.has(
2032
+ audioResponseId,
2033
+ );
2034
+
2035
+ console.log("🔊 Text stream audio content received:", {
2036
+ audioResponseId: audioResponseId,
2037
+ requestId: requestId,
2038
+ alreadyPlayed: alreadyPlayed,
2039
+ audioContentLength: data.audio_content.length,
2040
+ });
2041
+
2042
+ if (!alreadyPlayed) {
2043
+ this.playedAudioIds.add(audioResponseId);
2044
+ // Mark the current assistant message as having audio response
2045
+ console.log("🔍 Setting audio content for message:", {
2046
+ targetMessageId: assistantMessage.id,
2047
+ audioContentLength: data.audio_content.length,
2048
+ audioContentPreview:
2049
+ data.audio_content.substring(0, 20) + "...",
2050
+ });
2051
+ this._updateMessageInArray(assistantMessage.id, {
2052
+ hasAudioResponse: true,
2053
+ audioContent: data.audio_content,
2054
+ latestRunId: latestRunId,
2055
+ });
2056
+ console.log("✅ Stored audio response (text stream)");
2057
+
2058
+ // Clean up old audio IDs to prevent memory issues
2059
+ if (this.playedAudioIds.size > 10) {
2060
+ const audioIds = Array.from(this.playedAudioIds);
2061
+ this.playedAudioIds.clear();
2062
+ audioIds
2063
+ .slice(-5)
2064
+ .forEach((id) => this.playedAudioIds.add(id));
2065
+ }
2066
+ } else {
2067
+ console.log("⏭️ Skipping audio: already played");
2068
+ }
2069
+ } else {
2070
+ console.log(
2071
+ "❌ No audio_content found in text stream data",
2072
+ );
2073
+ }
2074
+
2075
+ // Handle audio content in response_processor
2076
+ if (
2077
+ data.response_processor &&
2078
+ data.response_processor.audio_content &&
2079
+ typeof data.response_processor.audio_content === "string"
2080
+ ) {
2081
+ console.log(
2082
+ "🔍 Found audio_content in response_processor:",
2083
+ {
2084
+ audioContentLength:
2085
+ data.response_processor.audio_content.length,
2086
+ audioContentPreview:
2087
+ data.response_processor.audio_content.substring(
2088
+ 0,
2089
+ 50,
2090
+ ) + "...",
2091
+ },
2092
+ );
2093
+
2094
+ const audioResponseId = `text_response_${requestId}_${data.response_processor.audio_content.substring(
2095
+ 0,
2096
+ 30,
2097
+ )
2098
+ }`;
2099
+ const alreadyPlayed = this.playedAudioIds.has(
2100
+ audioResponseId,
2101
+ );
2102
+
2103
+ console.log(
2104
+ "🔊 Response processor audio content received:",
2105
+ {
2106
+ audioResponseId: audioResponseId,
2107
+ requestId: requestId,
2108
+ alreadyPlayed: alreadyPlayed,
2109
+ audioContentLength:
2110
+ data.response_processor.audio_content.length,
2111
+ },
2112
+ );
2113
+
2114
+ if (!alreadyPlayed) {
2115
+ this.playedAudioIds.add(audioResponseId);
2116
+
2117
+ // Mark the current assistant message as having audio response
2118
+ console.log(
2119
+ "🔍 Setting response processor audio content for message:",
2120
+ {
2121
+ targetMessageId: assistantMessage.id,
2122
+ audioContentLength:
2123
+ data.response_processor.audio_content.length,
2124
+ audioContentPreview:
2125
+ data.response_processor.audio_content.substring(
2126
+ 0,
2127
+ 20,
2128
+ ) + "...",
2129
+ },
2130
+ );
2131
+ this._updateMessageInArray(assistantMessage.id, {
2132
+ latestRunId: latestRunId,
2133
+ hasAudioResponse: true,
2134
+ audioContent:
2135
+ data.response_processor.audio_content,
2136
+ });
2137
+ console.log(
2138
+ "✅ Found matching message, setting response processor audio content",
2139
+ );
2140
+
2141
+ // Clean up old audio IDs to prevent memory issues
2142
+ if (this.playedAudioIds.size > 10) {
2143
+ const audioIds = Array.from(this.playedAudioIds);
2144
+ this.playedAudioIds.clear();
2145
+ audioIds
2146
+ .slice(-5)
2147
+ .forEach((id) => this.playedAudioIds.add(id));
2148
+ }
2149
+ } else {
2150
+ console.log(
2151
+ "⏭️ Skipping response processor audio: already played",
2152
+ );
2153
+ }
2154
+ }
2155
+ }
2156
+ } catch (parseError) {
2157
+ console.log("⚠️ Failed to parse streaming data:", parseError);
2158
+ }
2159
+ }
2160
+ }
2161
+ }
2162
+
2163
+ // Ensure streaming is marked as complete for this specific assistant message
2164
+ console.log("🏁 Finalizing assistant message:", assistantMessage.id);
2165
+
2166
+ // Add a small delay to ensure audio content is properly set
2167
+ await new Promise((resolve) => setTimeout(resolve, 100));
2168
+
2169
+ // Get the current state to ensure we have the latest audio content
2170
+ const currentAssistantMessage = this.messages.find(
2171
+ (msg) => msg.id === assistantMessage.id,
2172
+ );
2173
+ console.log("🔍 Current assistant message before finalization:", {
2174
+ messageId: assistantMessage.id,
2175
+ hasAudioContent: !!currentAssistantMessage?.audioContent,
2176
+ hasAudioResponse: currentAssistantMessage?.hasAudioResponse,
2177
+ audioContentLength: currentAssistantMessage?.audioContent?.length || 0,
2178
+ });
2179
+
2180
+ // If message was already finalized at 'end' with content, do not override
2181
+ if (
2182
+ endEventFinalized &&
2183
+ endFinalContent &&
2184
+ endFinalContent.length > 10
2185
+ ) {
2186
+ console.log(
2187
+ "✅ Message already finalized on end event; skipping overwrite",
2188
+ );
2189
+ } else {
2190
+ // Check if we have a meaningful response to display
2191
+ const finalText = bestMessageText && bestMessageText.length > 5
2192
+ ? bestMessageText
2193
+ : currentMessage;
2194
+ // If a chart URL was captured from the viz node, prefer it and show only the image
2195
+ const contentToSet =
2196
+ chartUrlFromViz && String(chartUrlFromViz).startsWith("http")
2197
+ ? chartUrlFromViz
2198
+ : finalText;
2199
+
2200
+ if (contentToSet && contentToSet.length > 10) {
2201
+ console.log("🔍 Finalizing message with content:", {
2202
+ messageId: assistantMessage.id,
2203
+ currentMessageLength: String(contentToSet).length,
2204
+ currentMessagePreview: String(contentToSet).substring(0, 50) +
2205
+ "...",
2206
+ });
2207
+ const currentMsg = this.messages.find(m => m.id === assistantMessage.id);
2208
+ console.log("🔍 Finalizing message:", {
2209
+ latestRunId,
2210
+ messageId: assistantMessage.id,
2211
+ existingAudioContent: !!currentMsg?.audioContent,
2212
+ existingAudioResponse: currentMsg?.hasAudioResponse,
2213
+ audioContentLength: currentMsg?.audioContent?.length || 0,
2214
+ });
2215
+ this._updateMessageInArray(assistantMessage.id, {
2216
+ latestRunId: latestRunId,
2217
+ content: contentToSet,
2218
+ additional_kwargs: currentAdditionalKwargs,
2219
+ isStreaming: false,
2220
+ isProcessing: false,
2221
+ hasAudioResponse: currentMsg?.hasAudioResponse || false, // Preserve existing audio response state
2222
+ audioContent: currentMsg?.audioContent || null, // Preserve existing audio content
2223
+ });
2224
+ } else {
2225
+ // If no meaningful response was found, show a clear, user-friendly fallback
2226
+ console.log("🔍 Finalizing message with friendly fallback");
2227
+ const currentMsg = this.messages.find(m => m.id === assistantMessage.id);
2228
+ this._updateMessageInArray(assistantMessage.id, {
2229
+ content: "Processing your request...",
2230
+ latestRunId: latestRunId,
2231
+ additional_kwargs: currentAdditionalKwargs,
2232
+ isStreaming: false,
2233
+ isProcessing: false,
2234
+ hasAudioResponse: currentMsg?.hasAudioResponse || false,
2235
+ audioContent: currentMsg?.audioContent || null,
2236
+ });
2237
+ }
2238
+ }
2239
+
2240
+ // Handle UI actions if present
2241
+ if (latestUiAction) {
2242
+ console.log("🔗 Adding UI action message:", latestUiAction);
2243
+ const uiActionMessage = {
2244
+ id: Date.now() + 2,
2245
+ content: "",
2246
+ sender: "assistant",
2247
+ timestamp: new Date().toISOString(),
2248
+ isUiAction: true,
2249
+ url: latestUiAction.url,
2250
+ uiActionType: latestUiAction.uiActionType,
2251
+ scrollToId: latestUiAction.scrollToId,
2252
+ navigationParams: latestUiAction.navigationParams,
2253
+ originalUrl: latestUiAction.originalUrl,
2254
+ isScrollAction: latestUiAction.uiActionType === "scroll",
2255
+ isNavigateStateAction:
2256
+ latestUiAction.uiActionType === "navigate-state",
2257
+ };
2258
+
2259
+ const lastMessage = this.messages[this.messages.length - 1];
2260
+ if (lastMessage) {
2261
+ const updatedLastMessage = {
2262
+ ...lastMessage,
2263
+ uiActionMessage,
2264
+ latestRunId,
2265
+ };
2266
+ console.log("UPDATED LAST MESSAGE", updatedLastMessage);
2267
+ this._updateMessageInArray(lastMessage.id, {
2268
+ uiActionMessage,
2269
+ latestRunId,
2270
+ });
2271
+ }
2272
+ }
2273
+ } catch (error) {
2274
+ console.error("❌ Streaming error:", error);
2275
+ const currentMsg = this.messages.find(m => m.id === assistantMessage.id);
2276
+ this._updateMessageInArray(assistantMessage.id, {
2277
+ isStreaming: false,
2278
+ isProcessing: false,
2279
+ isError: true,
2280
+ content: "Error occurred while processing request",
2281
+ latestRunId: latestRunId || currentMsg?.latestRunId, // Preserve or set latestRunId
2282
+ });
2283
+ }
2284
+ }
2285
+
2286
+ // Fetch assistant ID from API
2287
+ async fetchAssistantId() {
2288
+ try {
2289
+ console.log("🔍 Fetching assistant ID from API...");
2290
+
2291
+ // Use provided authToken or fallback to accessToken
2292
+ const authToken = this.authToken || this.accessToken;
2293
+ const supabaseToken = this.supabaseToken || authToken;
2294
+
2295
+ const response = await fetch(`${this.langgraphUrl}/assistants/search`, {
2296
+ method: "POST",
2297
+ headers: {
2298
+ "Content-Type": "application/json",
2299
+ Authorization: `Bearer ${authToken}`,
2300
+ "x-supabase-access-token": supabaseToken,
2301
+ Origin: window.location.origin || "*",
2302
+ },
2303
+ body: JSON.stringify({
2304
+ limit: 100,
2305
+ offset: 0,
2306
+ }),
2307
+ });
2308
+
2309
+ if (!response.ok) {
2310
+ console.log(
2311
+ `❌ API call failed with status: ${response.status} - backend may have rejected due to auth`,
2312
+ );
2313
+ return null; // Return null instead of throwing to let backend handle auth
2314
+ }
2315
+
2316
+ const assistants = await response.json();
2317
+ console.log("📋 Available assistants:", assistants);
2318
+
2319
+ // Log assistant details for debugging
2320
+ assistants.forEach((assistant, index) => {
2321
+ console.log(`Assistant ${index}:`, {
2322
+ id: assistant.assistant_id,
2323
+ name: assistant.name,
2324
+ hasName: !!assistant.name,
2325
+ type: typeof assistant.name,
2326
+ });
2327
+ });
2328
+
2329
+ // Find the assistant with name "Default Assistant"
2330
+ const defaultAssistant = assistants.filter(
2331
+ (assistant) => assistant.name && assistant.name.includes("Default"),
2332
+ )[0];
2333
+
2334
+ if (defaultAssistant) {
2335
+ console.log(
2336
+ "✅ Found Default Assistant:",
2337
+ defaultAssistant.assistant_id,
2338
+ );
2339
+ this.assistantId = defaultAssistant.assistant_id;
2340
+ return defaultAssistant.assistant_id;
2341
+ } else {
2342
+ console.log("⚠️ Default Assistant not found in the list");
2343
+
2344
+ // Find first assistant with a valid name
2345
+ const firstValidAssistant = assistants.find(
2346
+ (assistant) => assistant.name && assistant.name.trim() !== "",
2347
+ );
2348
+
2349
+ if (firstValidAssistant) {
2350
+ console.log(
2351
+ "⚠️ Using first valid assistant as fallback:",
2352
+ firstValidAssistant.assistant_id,
2353
+ "Name:",
2354
+ firstValidAssistant.name,
2355
+ );
2356
+ this.assistantId = firstValidAssistant.assistant_id;
2357
+ return firstValidAssistant.assistant_id;
2358
+ } else {
2359
+ console.log("❌ No assistants with valid names available");
2360
+ return null;
2361
+ }
2362
+ }
2363
+ } catch (error) {
2364
+ console.error("❌ Error fetching assistant ID:", error);
2365
+ console.log("🔍 Error details:", {
2366
+ name: error.name,
2367
+ message: error.message,
2368
+ isNetworkError: error.name === "TypeError",
2369
+ });
2370
+ return null; // Return null instead of throwing to let backend handle auth
2371
+ }
2372
+ }
2373
+
2374
+ // Load conversation history for a thread
2375
+ async loadHistory(threadId) {
2376
+ try {
2377
+ const response = await fetch(
2378
+ `${this.langgraphUrl}/threads/${threadId}/history`,
2379
+ {
2380
+ method: "POST",
2381
+ headers: this.getHeaders(),
2382
+ body: JSON.stringify({ limit: 10 }),
2383
+ },
2384
+ );
2385
+
2386
+ if (response.ok) {
2387
+ const history = await response.json();
2388
+ console.log("📜 Loaded history:", history);
2389
+
2390
+ // Get only the LATEST state (first item) which contains the complete conversation
2391
+ const latestState = history[0];
2392
+
2393
+ if (!latestState?.values?.messages) {
2394
+ console.log("No messages found in history");
2395
+ return;
2396
+ }
2397
+
2398
+ // Convert messages from the latest state only
2399
+ const historyMessages = [];
2400
+ latestState.values.messages.forEach((msg, msgIndex) => {
2401
+ if (msg.type === "human") {
2402
+ // Handle both text and audio content
2403
+ let content = "";
2404
+ let isAudio = false;
2405
+
2406
+ if (Array.isArray(msg.content)) {
2407
+ const textContent = msg.content.find(
2408
+ (c) => c.type === "text",
2409
+ );
2410
+ const audioContent = msg.content.find(
2411
+ (c) => c.type === "audio",
2412
+ );
2413
+
2414
+ if (audioContent) {
2415
+ content = "🎤 Audio message";
2416
+ isAudio = true;
2417
+ } else if (textContent) {
2418
+ content = textContent.text;
2419
+ }
2420
+ } else {
2421
+ content = msg.content;
2422
+ }
2423
+
2424
+ historyMessages.push({
2425
+ id: `history-${msgIndex}-human`,
2426
+ content: content,
2427
+ sender: "user",
2428
+ timestamp: new Date().toISOString(),
2429
+ isAudio: isAudio,
2430
+ });
2431
+ } else if (msg.type === "ai") {
2432
+ historyMessages.push({
2433
+ id: `history-${msgIndex}-ai`,
2434
+ content: msg.content,
2435
+ sender: "assistant",
2436
+ timestamp: new Date().toISOString(),
2437
+ });
2438
+ }
2439
+ });
2440
+
2441
+ if (historyMessages && historyMessages.length > 0) {
2442
+ console.log(`📝 Loading ${historyMessages.length} messages from history`);
2443
+ // Add history messages to the messages array
2444
+ historyMessages.forEach(msg => {
2445
+ this._addMessageToArray(msg);
2446
+ });
2447
+ }
2448
+ }
2449
+ } catch (error) {
2450
+ console.error("❌ Failed to load history:", error);
2451
+ }
2452
+ }
2453
+
2454
+ // Initialize chat - fetch assistant ID and create thread
2455
+ async initializeChat() {
2456
+ try {
2457
+ console.log("🔄 Initializing chat...");
2458
+
2459
+ // Always attempt API calls, let backend handle authentication
2460
+ const currentToken = localStorage.getItem("DfsWeb.access-token");
2461
+ console.log(
2462
+ "🔑 Access token status:",
2463
+ currentToken ? "Present" : "Empty - backend will handle",
2464
+ );
2465
+
2466
+ // Always attempt to fetch assistant ID
2467
+ console.log("📞 Making API call to /assistants/search...");
2468
+ const fetchedAssistantId = await this.fetchAssistantId();
2469
+
2470
+ if (!fetchedAssistantId) {
2471
+ console.log(
2472
+ "❌ Failed to fetch assistant ID - backend may have rejected due to auth",
2473
+ );
2474
+ this.isConnected = false;
2475
+ this.initialized = true;
2476
+ return;
2477
+ }
2478
+
2479
+ console.log(
2480
+ "✅ Assistant ID fetched successfully:",
2481
+ fetchedAssistantId,
2482
+ );
2483
+
2484
+ const storedUser = localStorage.getItem("DfsWeb.user-info");
2485
+ const user = storedUser ? JSON.parse(storedUser) : null;
2486
+
2487
+ // Always attempt to create thread
2488
+ console.log("📞 Making API call to /threads...");
2489
+ const response = await fetch(`${this.langgraphUrl}/threads`, {
2490
+ method: "POST",
2491
+ headers: this.getHeaders(),
2492
+ body: JSON.stringify({
2493
+ metadata: {
2494
+ user_id: user?.id || null,
2495
+ user_uuid: user?.uuid || null,
2496
+ },
2497
+ }),
2498
+ });
2499
+
2500
+ if (response.ok) {
2501
+ const thread = await response.json();
2502
+ this.threadId = thread.thread_id;
2503
+ this.isConnected = true;
2504
+ console.log("✅ Thread created:", thread.thread_id, "\n", thread);
2505
+
2506
+ // Load conversation history
2507
+ await this.loadHistory(thread.thread_id);
2508
+ } else {
2509
+ console.log("Thread created NOT");
2510
+ const errorText = await response.text();
2511
+ console.error(
2512
+ "❌ Failed to create thread:",
2513
+ response.status,
2514
+ errorText,
2515
+ );
2516
+ this.isConnected = false;
2517
+ }
445
2518
 
446
- _escapeHtml(text) {
447
- const div = document.createElement("div");
448
- div.textContent = text;
449
- return div.innerHTML;
2519
+ this.initialized = true;
2520
+ } catch (error) {
2521
+ console.error("❌ Thread creation error:", error);
2522
+ this.isConnected = false;
2523
+ this.initialized = true;
2524
+ }
450
2525
  }
451
2526
  }
452
2527
 
453
- // Export as UMD and ESM compatible
454
- if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
455
- module.exports = ChatWidget;
456
- } else {
457
- window.ChatWidget = ChatWidget;
458
- }
2528
+ // Export as ESM (Rollup will handle UMD conversion)
2529
+ export default ChatWidget;