File size: 28,386 Bytes
9c48ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
let apiKey;
let serpApiKey;
let ws = null;
let taskId = null;
let imageBaseDir = "../images/";
let agentProfileImages = {};
let agentLists = [];

const apiHost = ((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + window.location.pathname.replace('demo.html', '') + "api";

// Helpers
const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
window.onload = async () => {
    await connect();
}

const getApiKey = document.getElementById('openai-api-key');
const getApiKeySerp = document.getElementById('serp-api-key');
getApiKey.addEventListener('input', () => {
    if (apiKey !== '' || apiKey !== undefined) {
        apiKey = getApiKey.value;
    }
});
getApiKeySerp.addEventListener('input', () => {
    if (serpApiKey !== '' || serpApiKey !== undefined) {
        serpApiKey = getApiKeySerp.value;
    }
});

function applyStyles(element) {
    element.style.backgroundColor = '#add8e6a8';
    element.style.padding = '12px';
    element.style.borderRadius = '1.2rem';
    element.style.marginTop = '30px !important';
}
function resetStyles(element) {
    element.style.backgroundColor = '';
    element.style.padding = '';
    element.style.borderRadius = '';
    element.style.marginTop = '';
}
function isEmpty(e) {
    if (e === undefined || e === null) {
        return true;
    }
    return false;
}
function profileImage(url) {
    const profileImage = document.createElement('img');
    profileImage.src = url;
    profileImage.height = 50;
    profileImage.width = 50;
    profileImage.className = 'agent-avatar';
    return profileImage;
}
function cleanResponseContent(content) {
    if (isEmpty(content)) { return; }

    // const contentWithoutHeadersOne = content.replace(/#\s+/g, '');
    const contentWithoutHeaders = content.replace(/##\s+/g, '');
    const cleanedContent = contentWithoutHeaders.replace(/"([^"]*)": ""\s*,?|{\s*}/g, '');
    const formattedContent = cleanedContent.replace(/\n/g, '<br>');
    const codeBlockRegex = /```([\s\S]*?)```/g;
    const formattedWithCodeBlocks = formattedContent.replace(codeBlockRegex, '<pre>$1</pre>');
    const codeSnippetRegex = /`([^`]+)`/g;
    const formattedFinal = formattedWithCodeBlocks.replace(codeSnippetRegex, '<code>$1</code>');
    return formattedFinal;
}



const imageFilenames = Array.from({ length: 20 }, (_, index) => `${index + 1}.jpg`);
let currentImageIndex = 0;

// Render agents on left col
function renderAgent(agent) {
    const agentName = agent.task_message.role;
    if (agentLists.indexOf(agentName) > -1) {
        return;
    }

    const agentsList = document.getElementById('agentsList');
    const listItem = document.createElement('li');
    const agentNameDiv = document.createElement('p');
    
    agentNameDiv.className = 'px-3 agents mt-3';
    agentsList.className = 'mt-4 py-3';
    listItem.className = 'list-group-item d-flex align-items-center';
    agentNameDiv.textContent = agentName;

    let agentProfileImage = '';
    if (agentProfileImages.hasOwnProperty(agentName)) {
        agentProfileImage = agentProfileImages[agentName];
    } else {
        agentProfileImage = currentImageIndex < imageFilenames.length
            ? `${imageBaseDir}${imageFilenames[currentImageIndex]}`
            : `${imageBaseDir}default.png`;
    
        currentImageIndex = (currentImageIndex + 1) % imageFilenames.length;
    
        agentProfileImages[agentName] = agentProfileImage;

    }

    const agentImage = profileImage(agentProfileImage);
    listItem.prepend(agentImage);

    listItem.appendChild(agentNameDiv);
    agentsList.appendChild(listItem);
    agentLists.push(agentName);
}

// Render Expert agents on left col
function renderExpertAgent(expertName) {
    if (agentLists.indexOf(expertName) > -1) {
        return;
    }

    const agentsList = document.getElementById('agentsList');
    const listItem = document.createElement('li');
    const agentNameDiv = document.createElement('p');

    agentNameDiv.className = 'px-3 agents mt-3';
    agentsList.className = 'mt-4 py-3';
    listItem.className = 'list-group-item d-flex align-items-center';
    agentNameDiv.textContent = expertName;

    const agentProfileImage = currentImageIndex < imageFilenames.length
        ? `${imageBaseDir}${imageFilenames[currentImageIndex]}`
        : `${imageBaseDir}default.png`;

    currentImageIndex = (currentImageIndex + 1) % imageFilenames.length;

    agentProfileImages[expertName] = agentProfileImage;
    const agentImage = profileImage(agentProfileImage);
    listItem.prepend(agentImage);

    listItem.appendChild(agentNameDiv);
    agentsList.appendChild(listItem);
    agentLists.push(expertName);
}


// Scroll to msg of clicked agent/step
let previousScrolledDiv = null; // track previously scrolled divs
function scrollToMessageDiv(agentRole) {
    const chatView = document.getElementById('chatView');
    const chatMessages = chatView.getElementsByClassName('chat-agent');

    for (const msgDiv of chatMessages) {
        if (msgDiv.getAttribute('data-role') === agentRole) {
            if (previousScrolledDiv) {
                resetStyles(previousScrolledDiv);
            }
            applyStyles(msgDiv);

            msgDiv.scrollIntoView({ behavior: 'smooth' });
            previousScrolledDiv = msgDiv;
            break;
        }
    }
}

// Render Lead agents responses
async function renderLeadAgentsResponses(responseData) {
    // console.info(responseData);
    const chatView = document.getElementById('chatView');

    // Get all lead agents
    const chatMessages = responseData.filter((msg) => msg.task_message.role === "Question/Task" || msg.task_message.role === "Manager" || msg.task_message.role === "Agents Observer" || msg.task_message.role === "Plan Observer" || msg.task_message.role !== "" || msg.task_message.content !== "");

    // Sort chat messages based on timestamp
    chatMessages.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

    for (const msg of chatMessages) {
        const agentDiv = createAgentChatDiv(msg.task_message);
        chatView.appendChild(agentDiv);

        chatView.scrollTop = chatView.scrollHeight;
        // showCallingNextAgentMessage().stop();
    }
    // showCallingNextAgentMessage();
    chatView.scrollTop = chatView.scrollHeight;
}

// render task agents message
async function renderTaskAgentsResponse(responseData) {
    const chatView = document.getElementById('chatView');

    const namedAgents = responseData.filter((msg) => msg.task_message.role !== "Question/Task" && msg.task_message.role !== "Manager" && msg.task_message.role !== "Agents Observer" && msg.task_message.role !== "Plan Observer" && msg.task_message.role !== "" && msg.task_message.content !== "");
    // Render work agents responses
    for (const agent of namedAgents) {

        const agentChatMessages = responseData.filter((msg) => msg.task_message.role === agent.role);
        for (const msg of agentChatMessages) {
            const agentDiv = createAgentChatDiv(msg.task_message);
            chatView.appendChild(agentDiv);
            chatView.scrollTop = chatView.scrollHeight;
        }
    }
}

// Invite and render work agents
async function inviteTaskAgents(responseData) {
    // console.info(responseData);
    const chatView = document.getElementById('chatView');
    const invitees = responseData.filter((msg) => msg.task_message.role === "Revised Role List");

    for (const agent of invitees) {
        const inviteMessageContainer = document.createElement('div');
        inviteMessageContainer.className = 'text-center invite-message fs';
        chatView.appendChild(inviteMessageContainer);

        for (const contentItem of agent.task_message.content) {
            const inviteMessage = document.createElement('p');
            inviteMessage.innerText = `Invited ${contentItem.name} to group chat`;
            inviteMessageContainer.appendChild(inviteMessage);
            chatView.scrollTop = chatView.scrollHeight;
            renderExpertAgent(contentItem.name);
            await sleep(1000);
        }
    }
}

let renderedLeadAgents = {};
async function renderLeadAgentsOnce(responseData) {
    // console.info(responseData);

    const leadAgents = responseData.filter((msg) => msg.task_message.role === "Question/Task" || msg.task_message.role === "Manager" || msg.task_message.role === "Agents Observer" || msg.task_message.role === "Plan Observer" || msg.task_message.role !== "" || msg.task_message.content !== "");

    for (const agent of leadAgents) {
        const agentRole = agent.task_message.role;
        if (!renderedLeadAgents.hasOwnProperty(agentRole)) {
            renderedLeadAgents[agentRole] = true;
            renderAgent(agent);
        }
    }
}


// Agent chat response divs
let renderedAgentMessage = {};
function createAgentChatDiv(msg) {
    const agentDiv = document.createElement('div');
    agentDiv.className = 'chat-agent d-flex';
    agentDiv.setAttribute('data-role', msg.role);

    const agentNameDiv = document.createElement('p');
    agentNameDiv.className = 'agent-name';

    const agentRole = msg.role;
    let agentCount = renderedAgentMessage.hasOwnProperty(agentRole) ? renderedAgentMessage[agentRole] + 1 : 1;
    renderedAgentMessage[agentRole] = agentCount;

    if (agentCount > 1) {
        agentNameDiv.textContent = `${agentRole}`;
    } else {
        agentNameDiv.textContent = agentRole;
    }

    const responseMessages = document.createElement('p');
    responseMessages.className = 'chat-bubble ms-2 px-3 pb-3';

    let agentProfileImage = ''
    if (agentProfileImages.hasOwnProperty(agentNameDiv.textContent)) {
        agentProfileImage = agentProfileImages[agentNameDiv.textContent];
    } else {
        agentProfileImage = currentImageIndex < imageFilenames.length
            ? `${imageBaseDir}${imageFilenames[currentImageIndex]}`
            : `${imageBaseDir}default.png`;
        currentImageIndex = (currentImageIndex + 1) % imageFilenames.length;

        agentProfileImages[agentNameDiv.textContent] = agentProfileImage;
    }

    let messageText = cleanResponseContent(msg.content);
    if(msg.role === 'Question/Task') {
        messageText = `Task "${messageText}" is submitted.<br/>Waiting for agents to cooperate to complete the task.`;
    }
    // console.log(messageText);

    if (msg.role === 'Question/Task' || msg.role === 'Manager' || msg.role === 'Agents Observer' || msg.role === 'Plan Observer') {
        responseMessages.style.backgroundColor = 'rgb(170, 253, 217)';
    }

    if (!isEmpty(messageText) && messageText.length > 300) {
      const truncatedText = messageText.substring(0, 500);
      const fullText = messageText;
      const showMoreButton = document.createElement('button');
      showMoreButton.className = 'read-more mt-2 btn btn-success';
      showMoreButton.textContent = 'Show More';
      showMoreButton.addEventListener('click', function() {
          showFullText(this);
      });

      responseMessages.innerHTML = `${truncatedText}`;
      responseMessages.appendChild(showMoreButton);
      responseMessages.prepend(agentNameDiv);
      responseMessages.dataset.fullText = fullText;
    } else {
        responseMessages.innerHTML = messageText;
    }
    chatView.scrollTop = chatView.scrollHeight;

    const agentImage = profileImage(agentProfileImage);
    agentDiv.prepend(agentImage);
    responseMessages.prepend(agentNameDiv);
    agentDiv.appendChild(responseMessages);
    return agentDiv;
}


let callingMessageCount = 0; // keep track of calling messages
function showCallingNextAgentMessage() {
    const chatView = document.getElementById('chatView');
    const callingMessage = document.createElement('p');
    callingMessage.className = 'calling-message fs';
    callingMessage.textContent = 'Calling next agent';
    callingMessage.dataset.messageId = callingMessageCount;
    chatView.appendChild(callingMessage);
    callingMessageCount++;

    const animationFrames = ['Calling', 'Calling next', 'Calling next agent..', 'Calling next agent...'];
    let frameIndex = 0;

    const updateMessage = () => {
        callingMessage.textContent = animationFrames[frameIndex];
        frameIndex = (frameIndex + 1) % animationFrames.length;
    };
    const interval = setInterval(updateMessage, 500);

    return {
        stop: () => {
            clearInterval(interval);
            chatView.removeChild(callingMessage);
        }
    };
}

function showFullText(element) {
    const parentMessage = element.parentElement;
    const fullText = parentMessage.dataset.fullText;
    const fullTextParagraph = document.createElement('p');
    const agentNameDiv = parentMessage.querySelector('.agent-name'); 
    fullTextParagraph.innerHTML = fullText;
    const foldButton = document.createElement('button');
    foldButton.className = 'read-more mt-2 btn btn-success';
    foldButton.textContent = 'Show less';
    foldButton.addEventListener('click', function() {
        hideFullText(this);
    });
    parentMessage.innerHTML = ''; 
    parentMessage.prepend(agentNameDiv);
    parentMessage.appendChild(fullTextParagraph);
    parentMessage.appendChild(foldButton);
}
  
function hideFullText(element) {
    const parentMessage = element.parentElement;
    const truncatedText = parentMessage.dataset.fullText.substring(0, 500);
    const agentNameDiv = parentMessage.querySelector('.agent-name'); 
    const truncatedTextParagraph = document.createElement('p');
    truncatedTextParagraph.innerHTML = truncatedText;
    const showMoreButton = document.createElement('button');
    showMoreButton.className = 'read-more mt-2 btn btn-success';
    showMoreButton.textContent = 'Show More';
    showMoreButton.addEventListener('click', function() {
        showFullText(this);
    });
    parentMessage.innerHTML = ''; 
    parentMessage.prepend(agentNameDiv);
    parentMessage.appendChild(truncatedTextParagraph);
    parentMessage.appendChild(showMoreButton);
}

// Render tasks in the right column
async function displayTasks(responseData) {
    // console.info(responseData);
    const taskView = document.getElementById('taskView');

    // tasks and their progress
    responseData.forEach((task) => {
        if (task.task_message.role === 'Question/Task') {
            const taskItem = document.createElement('div');
            taskItem.className = 'alert alert-primary fw-bold';
            taskItem.textContent = task.task_message.content;
            taskView.appendChild(taskItem);
        }
    });
}
function styleSelectedStep(item) {
    const allListItems = document.querySelectorAll('.task-step');
    allListItems.forEach((listItem) => {
        listItem.style.border = "none";
        listItem.style.backgroundColor = "#fff";
    });
    item.style.backgroundColor = "#add8e6a8";
    item.style.borderRadius = "1.3rem";
}

// Render task(s) and progress
let renderedTasks = {};
let taskStepCount = 0; 
async function displayTaskSteps(responseData) {
    // console.info(responseData);
    const taskView = document.getElementById('taskView');

    let completedStages = 0;
    // Progress bar
    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar';

    for (let i = 0; i < responseData.length; i++) {
        const step = responseData[i];

        if (step.task_message.role) {
            const agentRole = step.task_message.role;
            if (renderedTasks.hasOwnProperty(agentRole)) {
                renderedTasks[agentRole]++;
            } else {
                renderedTasks[agentRole] = 1;
            }

            const stepItem = document.createElement('div');
            stepItem.className = 'task-step';

            stepItem.addEventListener('click', () => {
                scrollToMessageDiv(step.task_message.role);
                styleSelectedStep(stepItem);
            });

            // Expert details
            const expertDetails = document.createElement('div');
            expertDetails.className = 'expert-details d-flex';

            // Use the taskStepCount to set the step number
            const stepNumber = document.createElement('div');
            stepNumber.className = 'step-number';
            stepNumber.textContent = ++taskStepCount; // Increment and assign

            const expertNameContent = renderedTasks[agentRole] > 1
                ? `${agentRole} ${renderedTasks[agentRole]}`
                : agentRole;

            expertDetails.innerHTML = `
                <div class="step-content ms-3">
                    <div class="expert-name fw-bold">${expertNameContent}</div>
                    <p class="status">Pending...</p>
                </div>
            `;

            expertDetails.insertBefore(stepNumber, expertDetails.firstChild);

            stepItem.appendChild(expertDetails);
            stepItem.appendChild(progressBar);
            taskView.appendChild(stepItem);
        }
    }
    // Animate progress bar
    const expertName = document.querySelectorAll('.expert-name');
    const status = document.querySelectorAll('.status');
    const stepNumberElements = taskView.querySelectorAll('.step-number');

    for (let i = 0; i <= completedStages; i++) {
        stepNumberElements[i].classList.add('step-number-completed');
        expertName[i].classList.add('completed');
        status[i].textContent = 'Completed task(s)';
        status[i].classList.add('completed');
        // await new Promise((resolve) => setTimeout(resolve, 1000));
        if (i < stepNumberElements.length - 1) {
          completedStages++;
        }
    }
    progressBar.classList.add('completed-stage');
}

// Disable buttons if no input or api keys
const sendButton = document.getElementById('sendButton');
const sendIput = document.getElementById('inputMessage');
sendButton.disabled = true;
sendButton.style.color = '#9d9d9d';

function sendBtn() {
    if (sendIput.value.trim() !== '') {
        sendButton.disabled = false;
        sendButton.style.color = '#079f49';
    } else {
        sendButton.disabled = true;
        sendButton.style.color = '#9d9d9d';
    }
}
sendIput.addEventListener('input', sendBtn);
sendBtn();

// handle sending messages in the chat
async function sendMessage(exampleMessage) {
    if(taskId != null) {
        alert("Previous task is not completed. Please wait for the result or click STOP to end.");
        return;
    }
    await clearChat();
    const apiKey = document.getElementById('openai-api-key').value;
    const serpApiKey = document.getElementById('serp-api-key').value;
    const exampleMessagesID = document.getElementById("example-messages");
    const intro = document.querySelector('.intro');

    const sentMessage = document.getElementById('inputMessage').value;
    const inputMessage = sentMessage || exampleMessage;

    if ((!apiKey || apiKey.trim() === '' || apiKey === undefined) && (!serpApiKey || serpApiKey.trim() === '' || serpApiKey === undefined)) {
        var colLeft = document.querySelector('.col-left');
        colLeft.classList.toggle('show');
        alert('Please enter both API keys');
        return;
    } else if (inputMessage === '') {
        alert('Please enter a message');
    } else {
        localStorage.setItem("llm_api_key", apiKey.trim());
        localStorage.setItem("serpapi_key", serpApiKey.trim());
        // Get the input message and render into chat
        const chatView = document.getElementById('chatView');

        const messageDiv = document.createElement('div');

        const sentMesage = document.createElement('p');
        sentMesage.className = 'chat-bubble me-2 p-3';
        sentMesage.textContent = inputMessage;

        const senderImage = document.createElement('img');
        senderImage.src = '../images/default.jpg';
        senderImage.height = 50;
        senderImage.width = 50;
        senderImage.className = 'agent-avatar';

        messageDiv.className = 'chat-user d-flex mb-2 mt-5 justify-content-end';
        messageDiv.appendChild(sentMesage);
        messageDiv.appendChild(senderImage);
        chatView.appendChild(messageDiv);

        ws.send(JSON.stringify({
            "action": "run_task",
            "data": {
                "llm_api_key": apiKey,
                "serpapi_key": serpApiKey,
                "idea": inputMessage
            }
        }));

        // Clear the input field
        document.getElementById('inputMessage').value = '';
        intro.style.display = 'none';
        exampleMessagesID.style.display = 'none';

        // show Stop button
        interruptButton.textContent = 'Stop';
        interruptButton.style.color = 'black';
        interruptButton.style.display = '';
        document.getElementById('calling-next-agent').style.display = 'block';
    }
}

async function clearChat() {
    // agent list
    const agentsList = document.getElementById('agentsList');
    agentsList.innerHTML = '';
    agentsList.className = 'list-group list-group-flush';

    // chat view
    const chatUsers = document.getElementsByClassName('chat-user');
    for(var i = chatUsers.length-1; i >=0; i--){
        chatUsers[i].remove();
    }
    const chatAgents = document.getElementsByClassName('chat-agent');
    for(var i = chatAgents.length-1; i >= 0; i--) {
        chatAgents[i].remove();
    }
    const invitedExperts = document.getElementsByClassName('invite-message');
    for(var i = invitedExperts.length-1; i >= 0; i--) {
        invitedExperts[i].remove();
    }
    document.getElementById('calling-next-agent').style.display = 'none';
    // progress
    document.getElementById('taskView').innerHTML = '';
    // examples
    document.getElementById('example-messages').style.display = '';

    // global variables
    currentImageIndex = 0;
    previousScrolledDiv = null;
    renderedAgentMessage = {};
    renderedLeadAgents = {};
    callingMessageCount = 0;
    renderedTasks = {};
    taskStepCount = 0;
    agentProfileImages = {};
    agentLists = [];

    // button state, task_id, agentList
    interruptButton.textContent = 'Stop';
    interruptButton.style.color = 'black';
    interruptButton.style.display = 'none';

    clearButton.style.display = 'none';

    taskId = null;

    // ws connect
    if (ws == null || ws.readyState != 1) {
        await connect();
        await sleep(800);
    }
}

// Add event listener to send button
document.getElementById('sendButton').addEventListener('click', sendMessage);
document.getElementById('inputMessage').addEventListener('keydown', function(e){
    if(e.key == "Enter"){
        sendMessage();
    }
})

document.addEventListener("DOMContentLoaded", function () {
    const exampleInputs = document.querySelectorAll(".example-input");
    exampleInputs.forEach(function (example) {
        // if (ws = null){ example.disabled = true;}
        example.addEventListener("click", function () {
            const inputValue = example.getAttribute("data-input");
            sendMessage(inputValue);
        });
    });
});

const interruptButton = document.getElementById('interruptButton');
interruptButton.addEventListener('click', async () => {
    if (taskId && ws) {
        ws.send(JSON.stringify({
            "action": "interrupt",
            "data": {
                "task_id": taskId
            }
        }));
    } else {
        interruptButton.style.color = 'red';
        if(interruptButton.textContent == 'Stop'){
            interruptButton.textContent = 'Stopped';
        }
        
        const callingMessages = document.querySelectorAll("calling-message");
        callingMessages.forEach((callingMessage) => {
            callingMessage.style.display = "none !important";
        })

        clearButton.style.display = '';
        document.getElementById('calling-next-agent').style.display = 'none';
    }
});
const clearButton = document.getElementById('clearButton');
clearButton.addEventListener('click', async () => {
    await clearChat();
});

// Websocket connection
async function connect() {
    ws = new WebSocket(apiHost);
    ws.onopen = function (e) {
        console.log('ws opened');
        if (ws.readyState == 1) {
            console.log('ws connected');
        }
    };

    ws.onmessage = async function (e) {
        console.log(e['data'])
        var response = JSON.parse(e['data']);
        if (response["action"] == "run_task") {
            // console.log(response);
            // nothing to do
            if (response['msg'] == 'ok') {
                taskId = response['data']['task_id'];
                // console.log(response["data"])
                let responseData = [response["data"]];
                // data rendering fxns
                await renderLeadAgentsResponses(responseData).then(inviteTaskAgents(responseData));
                await renderLeadAgentsOnce(responseData);
                await renderTaskAgentsResponse(responseData)
                await displayTasks(responseData);
                await displayTaskSteps(responseData);
            } else if (response['msg'] == 'finished') {
                console.log("task: " + taskId + " finished.");
                taskId = null;

                interruptButton.style.display = '';
                interruptButton.style.color = 'red';
                if(interruptButton.textContent == 'Stop') {
                    interruptButton.textContent = 'Finished';
                }
                
                clearButton.style.display = '';
                document.getElementById('calling-next-agent').style.display = 'none';
                
            } else {
                // errors
                console.log("task error:" + response['msg']);
                interruptButton.click();
                alert("An error occurred in the task, please check the logs.");
            }
        }
        else if (response['action'] == "interrupt") {
            if (response['msg'] == 'ok') {
                console.log("task: " + taskId + " interrupted.");
                
                interruptButton.style.color = 'red';
                if(interruptButton.textContent == 'Stop'){
                    interruptButton.textContent = 'Stopped';
                }
                
                const callingMessages = document.querySelectorAll("calling-message");
                callingMessages.forEach((callingMessage) => {
                    callingMessage.style.display = "none !important";
                })
    
                clearButton.style.display = '';
                document.getElementById('calling-next-agent').style.display = 'none';
            }
        }
    }
    ws.onerror = function (err) {
        console.info('ws error: ' + err);
        ws = null;
    }

    ws.onclose = function (e) {
        console.info('ws close: ' + e);
        ws = null;
    };
}

document.addEventListener('DOMContentLoaded', function () {
    var toggleLeftBtn = document.getElementById('toggleLeft');
    var toggleRightBtn = document.getElementById('toggleRight');
    var colLeft = document.querySelector('.col-left');
    var colRight = document.querySelector('.col-right');

    toggleLeftBtn.addEventListener('click', function () {
        colLeft.classList.toggle('show');
        colLeft.style.transition = 'all 0.3s ease-in-out !important';
        colRight.classList.remove('show');
    });

    toggleRightBtn.addEventListener('click', function () {
        colRight.classList.toggle('show');
        colLeft.classList.remove('show');
    });

    let apiKey = localStorage.getItem("llm_api_key");
    let serpApiKey = localStorage.getItem("serpapi_key");
    if(apiKey) {
        document.getElementById('openai-api-key').value = apiKey;
        localStorage.removeItem('llm_api_key');
    }
    if(serpApiKey) {
        document.getElementById('serp-api-key').value = serpApiKey;
        localStorage.removeItem('serpapi_key');
    }
    setInterval(callingNextAgent, 100);
});

function callingNextAgent() {
    node = document.getElementById('calling-next-agent');
    let text = node.getAttribute('data-content');
    var i = parseInt(node.getAttribute('data-index'));
    if(i == 0) {
        node.textContent = '';
    }
    if (i < text.length) {
        node.textContent += text.charAt(i);
        i = (i+1) % text.length;
        node.setAttribute('data-index', i.toString());
    }
}