-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1179 lines (999 loc) · 43.2 KB
/
script.js
File metadata and controls
1179 lines (999 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
document.addEventListener('DOMContentLoaded', () => {
const taskInput = document.getElementById('task-input');
const addTaskBtn = document.getElementById('add-task-btn');
const taskList = document.getElementById('task-list');
const runTasksBtn = document.getElementById('run-tasks-btn');
const executionStatus = document.getElementById('execution-status');
const screenshotDisplay = document.getElementById('screenshot-display');
const downloadReceiptBtn = document.getElementById('download-receipt-btn');
const actionLog = document.getElementById('action-log');
let tasks = [];
let draggedIndex = null;
let currentSessionId = null;
let originalTabId = null; // Track the original tab
let isExecuting = false;
let liveViewInterval = null;
let isLiveViewActive = false;
let isClickMode = false;
let isTypeMode = false;
// API configuration
const API_BASE = window.location.origin;
// Interactive API functions
async function sendInteractiveCommand(sessionId, command) {
try {
const response = await fetch(`${API_BASE}/api/sessions/${sessionId}/interactive`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
command: command
})
});
if (!response.ok) {
throw new Error(`Interactive command failed: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error sending interactive command:', error);
throw error;
}
}
async function getCurrentScreenshot(sessionId) {
try {
const response = await fetch(`${API_BASE}/api/sessions/${sessionId}/screenshot`);
if (!response.ok) {
throw new Error(`Failed to get screenshot: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error getting screenshot:', error);
throw error;
}
}
async function getSessionState(sessionId) {
try {
const response = await fetch(`${API_BASE}/api/sessions/${sessionId}/state`);
if (!response.ok) {
throw new Error(`Failed to get session state: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error getting session state:', error);
throw error;
}
}
// Interactive mode functions
function enableInteractiveMode() {
const interactiveControls = document.getElementById('interactive-controls');
if (currentSessionId && interactiveControls) {
interactiveControls.style.display = 'block';
logAction('🎮 Interactive mode enabled');
}
}
function disableInteractiveMode() {
const interactiveControls = document.getElementById('interactive-controls');
if (interactiveControls) {
interactiveControls.style.display = 'none';
stopLiveView();
logAction('🎮 Interactive mode disabled');
}
}
async function startLiveView() {
if (!currentSessionId) {
logAction('❌ No active session for live view');
return;
}
if (isLiveViewActive) {
stopLiveView();
return;
}
isLiveViewActive = true;
const liveViewBtn = document.getElementById('enable-live-view');
if (liveViewBtn) {
liveViewBtn.textContent = '⏹️ Stop Live View';
liveViewBtn.classList.add('btn-danger');
}
const screenshotDisplay = document.getElementById('screenshot-display');
if (screenshotDisplay) {
screenshotDisplay.classList.add('live-view-active');
}
logAction('📹 Live view started');
liveViewInterval = setInterval(async () => {
try {
const data = await getCurrentScreenshot(currentSessionId);
if (data.success && data.screenshot) {
updateScreenshotDisplay(data.screenshot, false); // Don't log each update
// Update session state indicators
if (data.sessionState && data.sessionState.isPaused) {
screenshotDisplay.classList.add('session-paused');
updateInteractionStatus(`⏸️ Session paused: ${data.sessionState.pauseReason || 'Unknown reason'}`);
} else {
screenshotDisplay.classList.remove('session-paused');
}
}
} catch (error) {
console.error('Live view update failed:', error);
// Don't spam the log with live view errors
}
}, 2000); // Update every 2 seconds
}
function stopLiveView() {
isLiveViewActive = false;
if (liveViewInterval) {
clearInterval(liveViewInterval);
liveViewInterval = null;
}
const liveViewBtn = document.getElementById('enable-live-view');
if (liveViewBtn) {
liveViewBtn.textContent = '📹 Live View';
liveViewBtn.classList.remove('btn-danger');
}
const screenshotDisplay = document.getElementById('screenshot-display');
if (screenshotDisplay) {
screenshotDisplay.classList.remove('live-view-active');
}
logAction('📹 Live view stopped');
}
function enableClickMode() {
if (!currentSessionId) {
logAction('❌ No active session for click mode');
return;
}
isClickMode = !isClickMode;
isTypeMode = false; // Disable type mode
const clickBtn = document.getElementById('click-mode');
const typeBtn = document.getElementById('type-mode');
const screenshotDisplay = document.getElementById('screenshot-display');
if (isClickMode) {
clickBtn.textContent = '🖱️ Click: ON';
clickBtn.classList.add('btn-success');
screenshotDisplay.classList.add('screenshot-interactive');
updateInteractionStatus('🖱️ Click mode active - Click anywhere on the screenshot to interact');
logAction('🖱️ Click mode enabled');
} else {
clickBtn.textContent = '🖱️ Click Mode';
clickBtn.classList.remove('btn-success');
screenshotDisplay.classList.remove('screenshot-interactive');
updateInteractionStatus('💡 Click mode disabled');
logAction('🖱️ Click mode disabled');
}
// Reset type button
if (typeBtn) {
typeBtn.textContent = '⌨️ Type Mode';
typeBtn.classList.remove('btn-success');
}
document.getElementById('type-text').style.display = 'none';
}
function enableTypeMode() {
if (!currentSessionId) {
logAction('❌ No active session for type mode');
return;
}
isTypeMode = !isTypeMode;
isClickMode = false; // Disable click mode
const typeBtn = document.getElementById('type-mode');
const clickBtn = document.getElementById('click-mode');
const typeInput = document.getElementById('type-text');
const screenshotDisplay = document.getElementById('screenshot-display');
if (isTypeMode) {
typeBtn.textContent = '⌨️ Type: ON';
typeBtn.classList.add('btn-success');
typeInput.style.display = 'block';
typeInput.focus();
updateInteractionStatus('⌨️ Type mode active - Enter text and press Enter to type');
logAction('⌨️ Type mode enabled');
} else {
typeBtn.textContent = '⌨️ Type Mode';
typeBtn.classList.remove('btn-success');
typeInput.style.display = 'none';
updateInteractionStatus('💡 Type mode disabled');
logAction('⌨️ Type mode disabled');
}
// Reset click button and mode
if (clickBtn) {
clickBtn.textContent = '🖱️ Click Mode';
clickBtn.classList.remove('btn-success');
}
screenshotDisplay.classList.remove('screenshot-interactive');
}
function updateInteractionStatus(message) {
const statusElement = document.getElementById('interaction-status');
if (statusElement) {
statusElement.innerHTML = `<small>${message}</small>`;
}
}
function updateScreenshotDisplay(screenshot, shouldLog = true) {
const screenshotDisplay = document.getElementById('screenshot-display');
if (!screenshotDisplay || !screenshot) return;
// Clear existing content but preserve classes
const existingClasses = screenshotDisplay.className;
screenshotDisplay.innerHTML = '';
screenshotDisplay.className = existingClasses + ' has-screenshot';
const img = document.createElement('img');
if (screenshot.base64) {
img.src = `data:image/png;base64,${screenshot.base64}`;
} else if (screenshot.url) {
img.src = screenshot.url.startsWith('/') ? `${API_BASE}${screenshot.url}` : screenshot.url;
}
img.alt = 'Browser screenshot';
img.onerror = () => {
screenshotDisplay.innerHTML = '<p>Failed to load screenshot</p>';
screenshotDisplay.classList.remove('has-screenshot');
};
// Add click handler for interactive mode
img.onclick = async (e) => {
if (isClickMode && currentSessionId) {
const rect = img.getBoundingClientRect();
const scaleX = img.naturalWidth / img.width;
const scaleY = img.naturalHeight / img.height;
const x = Math.round((e.clientX - rect.left) * scaleX);
const y = Math.round((e.clientY - rect.top) * scaleY);
// Show click coordinates
const clickIndicator = document.createElement('div');
clickIndicator.className = 'click-coordinates';
clickIndicator.textContent = `(${x}, ${y})`;
clickIndicator.style.left = (e.clientX - rect.left) + 'px';
clickIndicator.style.top = (e.clientY - rect.top) + 'px';
screenshotDisplay.appendChild(clickIndicator);
try {
logAction(`🖱️ Clicking at coordinates (${x}, ${y})`);
const result = await sendInteractiveCommand(currentSessionId, {
type: 'click',
x: x,
y: y
});
if (result.success) {
logAction(`✅ Click successful at (${x}, ${y})`);
if (result.screenshot) {
// Update screenshot after click
setTimeout(() => updateScreenshotDisplay(result.screenshot), 1000);
}
}
} catch (error) {
logAction(`❌ Click failed: ${error.message}`);
}
}
};
const info = document.createElement('div');
info.className = 'screenshot-info';
const timestamp = screenshot.timestamp ? new Date(screenshot.timestamp).toLocaleTimeString() : 'now';
info.textContent = `Screenshot taken at ${timestamp}`;
screenshotDisplay.appendChild(img);
screenshotDisplay.appendChild(info);
if (shouldLog) {
logAction('📸 Screenshot updated');
}
}
async function pauseSession() {
if (!currentSessionId) {
logAction('❌ No active session to pause');
return;
}
try {
const result = await sendInteractiveCommand(currentSessionId, {
type: 'pause',
reason: 'manual_pause'
});
if (result.success) {
logAction('⏸️ Session paused manually');
updateInteractionStatus('⏸️ Session is paused - click Resume to continue');
}
} catch (error) {
logAction(`❌ Failed to pause session: ${error.message}`);
}
}
async function resumeSession() {
if (!currentSessionId) {
logAction('❌ No active session to resume');
return;
}
try {
const result = await sendInteractiveCommand(currentSessionId, {
type: 'resume'
});
if (result.success) {
logAction('▶️ Session resumed');
updateInteractionStatus('▶️ Session resumed - ready for interaction');
}
} catch (error) {
logAction(`❌ Failed to resume session: ${error.message}`);
}
}
async function sendTypeCommand(text) {
if (!currentSessionId || !text.trim()) {
return;
}
try {
logAction(`⌨️ Typing: "${text}"`);
const result = await sendInteractiveCommand(currentSessionId, {
type: 'type',
text: text
});
if (result.success) {
logAction(`✅ Text typed successfully: "${text}"`);
if (result.screenshot) {
// Update screenshot after typing
setTimeout(() => updateScreenshotDisplay(result.screenshot), 1000);
}
// Clear the input
document.getElementById('type-text').value = '';
}
} catch (error) {
logAction(`❌ Typing failed: ${error.message}`);
}
}
function renderTasks() {
taskList.innerHTML = '';
tasks.forEach((task, index) => {
const li = document.createElement('li');
li.dataset.index = index;
li.setAttribute('draggable', 'true');
// Check if the task is being edited
if (task.isEditing) {
li.innerHTML = `
<input type="text" class="edit-input" value="${task.description}">
<div class="task-actions">
<button class="save-btn" title="Save Task">✔️</button>
</div>
`;
} else {
li.innerHTML = `
<span class="task-text">${task.description}</span>
<div class="task-actions">
<button class="edit-btn" title="Edit Task">✏️</button>
<button class="delete-btn" title="Delete Task">🗑️</button>
</div>
`;
}
taskList.appendChild(li);
});
}
function addTask() {
const taskDescription = taskInput.value.trim();
if (taskDescription) {
tasks.push({
id: Date.now(),
type: 'user-question',
description: taskDescription,
isEditing: false // Add editing state
});
taskInput.value = '';
renderTasks();
logAction(`Task added: "${taskDescription}"`);
}
}
function deleteTask(index) {
const taskDescription = tasks[index].description;
tasks.splice(index, 1);
renderTasks();
logAction(`Task removed: "${taskDescription}"`);
}
function toggleEditState(index) {
tasks.forEach((task, i) => {
task.isEditing = (i === index);
});
renderTasks();
// Focus the new input field
const editInput = taskList.querySelector('.edit-input');
if (editInput) {
editInput.focus();
editInput.select();
}
}
function saveTask(index, newDescription) {
const oldDescription = tasks[index].description;
if (newDescription && newDescription.trim() !== '') {
tasks[index].description = newDescription.trim();
logAction(`Task edited from "${oldDescription}" to "${newDescription.trim()}"`);
}
tasks[index].isEditing = false;
renderTasks();
}
function logAction(message) {
const logEntry = document.createElement('div');
logEntry.className = 'log-entry';
logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
actionLog.appendChild(logEntry);
actionLog.scrollTop = actionLog.scrollHeight; // Auto-scroll
}
function generateReceipt() {
const receipt = {
version: "1.0",
createdAt: new Date().toISOString(),
tasks: tasks.map(task => ({
id: task.id,
type: task.type,
params: {
query: task.description
}
}))
};
return receipt;
}
function downloadReceipt() {
const receipt = generateReceipt();
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(receipt, null, 2));
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", `receipt-${Date.now()}.json`);
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
logAction('Receipt downloaded.');
}
function showReceiptStatus(message, type = 'info') {
const statusDiv = document.getElementById('receipt-status');
statusDiv.textContent = message;
statusDiv.className = `status-message ${type}`;
statusDiv.style.display = 'block';
// Auto-hide after 5 seconds unless it's an error
if (type !== 'error') {
setTimeout(() => {
statusDiv.style.display = 'none';
}, 5000);
}
}
function validateReceipt(receipt) {
if (!receipt || typeof receipt !== 'object') {
throw new Error('Invalid receipt format: must be a JSON object');
}
if (!receipt.version) {
throw new Error('Invalid receipt: missing version field');
}
if (!Array.isArray(receipt.tasks)) {
throw new Error('Invalid receipt: tasks must be an array');
}
receipt.tasks.forEach((task, index) => {
if (!task.id) {
throw new Error(`Invalid task at index ${index}: missing id`);
}
if (!task.type) {
throw new Error(`Invalid task at index ${index}: missing type`);
}
if (!task.params || !task.params.query) {
throw new Error(`Invalid task at index ${index}: missing params.query`);
}
});
return true;
}
async function runReceiptTasks(receipt) {
if (!currentSessionId) {
// Create a new session if none exists
await createSession();
}
// Clear existing tasks and add receipt tasks
tasks = [];
renderTasks();
// Add tasks from receipt
for (const receiptTask of receipt.tasks) {
const task = {
id: Date.now() + Math.random(), // Generate new ID for UI
type: receiptTask.type,
description: receiptTask.params.query,
status: 'pending'
};
tasks.push(task);
}
renderTasks();
showReceiptStatus(`Loaded ${receipt.tasks.length} tasks from receipt. Running tasks...`, 'info');
logAction(`Receipt loaded with ${receipt.tasks.length} tasks.`);
// Run the tasks
await runAllTasks();
}
async function runReceiptViaAPI(receipt) {
try {
showReceiptStatus('Uploading receipt to server...', 'info');
const response = await fetch(`${API_BASE}/api/receipts/run`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(receipt)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ error: 'Unknown server error' }));
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const result = await response.json();
showReceiptStatus(`Receipt executed successfully! Session ID: ${result.sessionId}`, 'success');
logAction(`Receipt executed via API. Session: ${result.sessionId}`);
// Optionally switch to this session to view results
if (result.sessionId) {
currentSessionId = result.sessionId;
// Fetch and display any screenshots or results
await getCurrentScreenshot(currentSessionId);
}
return result;
} catch (error) {
showReceiptStatus(`API execution failed: ${error.message}`, 'error');
logAction(`Receipt API execution failed: ${error.message}`);
throw error;
}
}
function handleReceiptUpload() {
const fileInput = document.getElementById('receipt-file-input');
const file = fileInput.files[0];
if (!file) {
showReceiptStatus('Please select a receipt file', 'error');
return;
}
if (!file.name.endsWith('.json')) {
showReceiptStatus('Please select a JSON file', 'error');
return;
}
const reader = new FileReader();
reader.onload = async (e) => {
try {
const receiptText = e.target.result;
const receipt = JSON.parse(receiptText);
// Validate receipt format
validateReceipt(receipt);
showReceiptStatus('Receipt validated successfully. Choose execution method:', 'success');
logAction(`Receipt file "${file.name}" loaded and validated.`);
// Show execution options
const confirmDialog = confirm(
`Receipt loaded with ${receipt.tasks.length} tasks.\n\n` +
'Choose execution method:\n' +
'OK = Run locally in browser\n' +
'Cancel = Run via server API'
);
if (confirmDialog) {
// Run locally
await runReceiptTasks(receipt);
} else {
// Run via API
await runReceiptViaAPI(receipt);
}
} catch (error) {
if (error instanceof SyntaxError) {
showReceiptStatus('Invalid JSON file format', 'error');
} else {
showReceiptStatus(`Error: ${error.message}`, 'error');
}
logAction(`Receipt upload error: ${error.message}`);
}
};
reader.onerror = () => {
showReceiptStatus('Error reading file', 'error');
};
reader.readAsText(file);
}
// API functions
async function createSession() {
try {
// First, check for existing extension sessions
const sessionsResponse = await fetch(`${API_BASE}/api/sessions`);
const sessionsData = await sessionsResponse.json();
if (sessionsData.success && sessionsData.sessions) {
// Look for connected extension sessions
const extensionSessions = sessionsData.sessions.filter(session =>
session.isConnected &&
(session.hasExtension || (session.metadata && session.metadata.browser === 'chrome-extension'))
);
if (extensionSessions.length > 0) {
// Use the most recent connected extension session
const latestExtensionSession = extensionSessions.sort((a, b) =>
new Date(b.createdAt) - new Date(a.createdAt)
)[0];
logAction(`🔌 Using existing extension session: ${latestExtensionSession.id}`);
updateSessionStatus(latestExtensionSession.id, 'extension');
return latestExtensionSession.id;
}
}
// If no extension session found, create a new session
const response = await fetch(`${API_BASE}/api/sessions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
metadata: {
browser: 'chrome',
purpose: 'frontend-task-execution',
project: 'banedon-browser-frontend'
},
options: {
timeout: 120000,
maxCommands: 100
}
})
});
if (!response.ok) {
throw new Error(`Failed to create session: ${response.statusText}`);
}
const data = await response.json();
console.log('Session creation response:', data); // Debug log
if (!data.success || !data.session || !data.session.id) {
throw new Error('Invalid session creation response');
}
logAction(`🆕 Created new session: ${data.session.id}`);
updateSessionStatus(data.session.id, 'server');
return data.session.id;
} catch (error) {
console.error('Error creating session:', error);
throw error;
}
}
async function executeTask(sessionId, taskDescription) {
try {
if (!sessionId) {
throw new Error('No valid session ID provided');
}
const response = await fetch(`${API_BASE}/api/sessions/${sessionId}/nl-tasks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
task: taskDescription
})
});
if (!response.ok) {
throw new Error(`Failed to execute task: ${response.statusText}`);
}
const data = await response.json();
console.log('Task execution response:', data); // Debug log
return data.task;
} catch (error) {
console.error('Error executing task:', error);
throw error;
}
}
async function deleteSession(sessionId) {
try {
await fetch(`${API_BASE}/api/sessions/${sessionId}`, {
method: 'DELETE'
});
} catch (error) {
console.error('Error deleting session:', error);
}
}
function displayScreenshot(screenshot) {
if (!screenshot || (!screenshot.url && !screenshot.base64)) {
return;
}
updateScreenshotDisplay(screenshot, true);
}
function updateExecutionStatus(status, message, type = '') {
const executionStatus = document.getElementById('execution-status');
if (!executionStatus) return;
executionStatus.textContent = message;
executionStatus.className = type;
executionStatus.style.display = message ? 'block' : 'none';
}
function updateSessionStatus(sessionId, mode) {
const sessionStatus = document.getElementById('session-status');
if (!sessionStatus) return;
const modeIcon = mode === 'extension' ? '🔌' : '🤖';
const modeText = mode === 'extension' ? 'Extension Mode' : 'Server Mode';
sessionStatus.innerHTML = `${modeIcon} Session: ${sessionId} (${modeText})`;
sessionStatus.style.display = 'block';
}
async function runAllTasks() {
if (tasks.length === 0) {
updateExecutionStatus('error', 'No tasks to execute', 'error');
return;
}
if (isExecuting) {
return;
}
isExecuting = true;
const runTasksBtn = document.getElementById('run-tasks-btn');
if (runTasksBtn) {
runTasksBtn.disabled = true;
runTasksBtn.textContent = 'Running...';
}
try {
// Store the original tab ID before starting tasks
if (chrome && chrome.tabs) {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs.length > 0) {
originalTabId = tabs[0].id;
logAction(`📌 Stored original tab: ${tabs[0].title}`);
}
} catch (tabError) {
// Ignore tab access errors (not in extension context)
console.log('Not running in extension context, tab switching disabled');
}
}
updateExecutionStatus('running', 'Creating browser session...', 'running');
logAction('Starting task execution...');
// Clear previous task response
clearTaskResponse();
// Create a new session or use existing extension session
currentSessionId = await createSession();
// Note: createSession() now handles logging internally with appropriate message
// Execute tasks sequentially
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
updateExecutionStatus('running', `Executing task ${i + 1}/${tasks.length}: ${task.description.substring(0, 50)}...`, 'running');
logAction(`Executing: "${task.description}"`);
try {
const result = await executeTask(currentSessionId, task.description);
logAction(`✅ Task ${i + 1} completed: ${result.response ? result.response.substring(0, 100) + '...' : 'Success'}`);
// Display task response prominently
displayTaskResponse(result, task.description);
// Display final screenshot if available
if (result.screenshots && result.screenshots.final) {
displayScreenshot(result.screenshots.final);
logAction('📸 Final screenshot captured and displayed');
} else if (result.screenshots && result.screenshots.after) {
displayScreenshot(result.screenshots.after);
logAction('📸 Screenshot displayed');
}
// Enable interactive mode after task completion
enableInteractiveMode();
} catch (taskError) {
logAction(`❌ Task ${i + 1} failed: ${taskError.message}`);
console.error('Task execution error:', taskError);
// Display error response prominently
displayTaskResponse({
success: false,
error: taskError.message,
execution: { iterations: 0, duration: 0 }
}, task.description);
}
// Add a small delay between tasks
if (i < tasks.length - 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
updateExecutionStatus('completed', `All ${tasks.length} tasks completed successfully!`, 'completed');
logAction('🎉 All tasks completed!');
// Switch back to original tab if we stored one
if (originalTabId && chrome && chrome.tabs) {
try {
await chrome.tabs.update(originalTabId, { active: true });
logAction('🔄 Switched back to original tab');
} catch (tabError) {
console.log('Could not switch back to original tab:', tabError.message);
}
}
} catch (error) {
updateExecutionStatus('error', `Execution failed: ${error.message}`, 'error');
logAction(`❌ Execution failed: ${error.message}`);
console.error('Execution error:', error);
} finally {
// Clean up session
if (currentSessionId) {
try {
// Disable interactive mode before cleanup
disableInteractiveMode();
await deleteSession(currentSessionId);
logAction('🧹 Session cleaned up');
} catch (cleanupError) {
console.error('Session cleanup error:', cleanupError);
}
currentSessionId = null;
}
isExecuting = false;
if (runTasksBtn) {
runTasksBtn.disabled = false;
runTasksBtn.textContent = 'Run Tasks';
}
// Hide status after some time
setTimeout(() => {
const executionStatus = document.getElementById('execution-status');
if (executionStatus && executionStatus.classList.contains('completed')) {
updateExecutionStatus('', '', '');
}
}, 10000);
}
}
// Response display functions
function displayTaskResponse(taskResult, taskDescription) {
const responseContainer = document.getElementById('task-response-container');
const responseDisplay = document.getElementById('task-response-display');
if (!responseContainer || !responseDisplay || !taskResult) {
return;
}
// Show the response container
responseContainer.style.display = 'block';
// Clear previous content
responseDisplay.innerHTML = '';
responseDisplay.className = '';
// Determine if this is an error or success
const isError = !taskResult.success || taskResult.error;
const responseText = taskResult.response || taskResult.error || 'No response available';
// Apply appropriate styling
if (isError) {
responseDisplay.classList.add('has-error');
} else {
responseDisplay.classList.add('has-response');
}
// Create response header
const header = document.createElement('div');
header.className = 'response-header';
header.innerHTML = `
${isError ? '❌' : '✅'} Response for: "${taskDescription.substring(0, 60)}${taskDescription.length > 60 ? '...' : ''}"
`;
// Create response content
const content = document.createElement('div');
content.className = 'response-content';
content.textContent = responseText;
// Create metadata section
const metadata = document.createElement('div');
metadata.className = 'response-metadata';
const timestamp = new Date().toLocaleString();
const iterations = taskResult.iterations || taskResult.execution?.iterations || 0;
const duration = taskResult.execution?.duration || 0;
metadata.innerHTML = `
<span>📅 ${timestamp}</span>
<span>🔄 ${iterations} iterations</span>
<span>⏱️ ${Math.round(duration / 1000)}s</span>
<button class="copy-response-btn" onclick="copyResponseToClipboard('${responseText.replace(/'/g, "\\'")}')">📋 Copy</button>
`;
// Assemble the response display
responseDisplay.appendChild(header);
responseDisplay.appendChild(content);
responseDisplay.appendChild(metadata);
// Scroll the response into view
responseContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
logAction(`💬 Task response displayed prominently`);
}
// Global function for copy button (needed for onclick in HTML)
window.copyResponseToClipboard = function(text) {
navigator.clipboard.writeText(text).then(() => {
logAction('📋 Response copied to clipboard');
// Show temporary feedback
const btn = event.target;
const originalText = btn.textContent;
btn.textContent = '✅ Copied';
setTimeout(() => {