forked from ComposioHQ/open-chatgpt-atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.tsx
More file actions
1504 lines (1326 loc) · 52.4 KB
/
sidepanel.tsx
File metadata and controls
1504 lines (1326 loc) · 52.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
import { useState, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import type { Settings, MCPClient, Message } from './types';
import { GeminiResponseSchema } from './types';
import { experimental_createMCPClient, stepCountIs } from 'ai';
// Custom component to handle link clicks - opens in new tab
const LinkComponent = ({ href, children }: { href?: string; children?: React.ReactNode }) => {
const handleLinkClick = (e: React.MouseEvent) => {
e.preventDefault();
if (href && (href.startsWith('http://') || href.startsWith('https://'))) {
chrome.tabs.create({ url: href });
}
};
return (
<a
href={href}
onClick={handleLinkClick}
style={{ color: '#2563eb', textDecoration: 'underline', cursor: 'pointer' }}
title={href}
target="_blank"
rel="noopener noreferrer"
>
{children}
</a>
);
};
// Component to parse and display assistant messages with better formatting
const MessageParser = ({ content }: { content: string }) => {
// Split message into logical sections - only on strong breaks (double newlines or numbered/bulleted lists)
const sections = content
.split(/\n+/)
.map((section) => section.trim())
.filter((section) => section.length > 0);
// If only one section or very short content, just return as-is
if (sections.length <= 1 || content.length < 150) {
return (
<ReactMarkdown remarkPlugins={[remarkGfm]} components={{ a: LinkComponent as any }}>
{content}
</ReactMarkdown>
);
}
// Display each section separately
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
{sections.map((section, idx) => (
<div
key={idx}
style={{
padding: '10px 12px',
backgroundColor: '#2d2d2d',
borderLeft: '3px solid #4d4d4d',
borderRadius: '4px',
}}
>
<ReactMarkdown remarkPlugins={[remarkGfm]} components={{ a: LinkComponent as any }}>
{section}
</ReactMarkdown>
</div>
))}
</div>
);
};
function ChatSidebar() {
const messagesEndRef = useRef<HTMLDivElement>(null);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const [settings, setSettings] = useState<Settings | null>(null);
const [showSettings, setShowSettings] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [browserToolsEnabled, setBrowserToolsEnabled] = useState(false);
const [showBrowserToolsWarning, setShowBrowserToolsWarning] = useState(false);
const [isUserScrolled, setIsUserScrolled] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const mcpClientRef = useRef<MCPClient | null>(null);
const mcpToolsRef = useRef<Record<string, unknown> | null>(null);
const listenerAttachedRef = useRef(false);
const settingsHashRef = useRef('');
const mcpInitPromiseRef = useRef<Promise<void> | null>(null);
const composioSessionRef = useRef<{ expiresAt: number } | null>(null);
const executeTool = async (toolName: string, parameters: any, retryCount = 0): Promise<any> => {
const MAX_RETRIES = 3;
const RETRY_DELAY = 1500; // 1.5 seconds to allow page to load
return new Promise((resolve, reject) => {
const handleResponse = (response: any) => {
const errorMsg = response?.error || chrome.runtime.lastError?.message || '';
const isConnectionError = errorMsg.includes('Receiving end does not exist') ||
errorMsg.includes('Could not establish connection');
if (isConnectionError && retryCount < MAX_RETRIES) {
setTimeout(async () => {
try {
const result = await executeTool(toolName, parameters, retryCount + 1);
resolve(result);
} catch (error) {
reject(error);
}
}, RETRY_DELAY);
} else {
// Return response as-is (could be success or error)
resolve(response);
}
};
if (toolName === 'screenshot') {
chrome.runtime.sendMessage({ type: 'TAKE_SCREENSHOT' }, handleResponse);
} else if (toolName === 'click') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'click',
selector: parameters.selector,
coordinates: parameters.x !== undefined ? { x: parameters.x, y: parameters.y } : undefined
}, handleResponse);
} else if (toolName === 'type') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'fill',
target: parameters.selector,
value: parameters.text
}, handleResponse);
} else if (toolName === 'scroll') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'scroll',
direction: parameters.direction,
target: parameters.selector,
amount: parameters.amount
}, handleResponse);
} else if (toolName === 'getPageContext') {
chrome.runtime.sendMessage({ type: 'GET_PAGE_CONTEXT' }, handleResponse);
} else if (toolName === 'navigate') {
chrome.runtime.sendMessage({ type: 'NAVIGATE', url: parameters.url }, handleResponse);
} else if (toolName === 'getBrowserHistory') {
chrome.runtime.sendMessage({
type: 'GET_HISTORY',
query: parameters.query,
maxResults: parameters.maxResults
}, handleResponse);
} else if (toolName === 'pressKey') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'press_key',
key: parameters.key
}, handleResponse);
} else if (toolName === 'clearInput') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'clear_input'
}, handleResponse);
} else if (toolName === 'keyCombo') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'key_combination',
keys: parameters.keys
}, handleResponse);
} else if (toolName === 'hover') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'hover',
coordinates: { x: parameters.x, y: parameters.y }
}, handleResponse);
} else if (toolName === 'dragDrop') {
chrome.runtime.sendMessage({
type: 'EXECUTE_ACTION',
action: 'drag_drop',
coordinates: { x: parameters.x, y: parameters.y },
destination: { x: parameters.destination_x, y: parameters.destination_y }
}, handleResponse);
} else {
reject(new Error(`Unknown tool: ${toolName}`));
}
});
};
const loadSettings = async (forceRefresh = false) => {
chrome.storage.local.get(['atlasSettings'], async (result) => {
if (result.atlasSettings) {
setSettings(result.atlasSettings);
const settingsHash = JSON.stringify(result.atlasSettings);
const hasSettingsChanged = forceRefresh || settingsHash !== settingsHashRef.current;
if (hasSettingsChanged && result.atlasSettings.composioApiKey) {
settingsHashRef.current = settingsHash;
try {
const { initializeComposioToolRouter } = await import('./tools');
const toolRouterSession = await initializeComposioToolRouter(
result.atlasSettings.composioApiKey
);
composioSessionRef.current = { expiresAt: toolRouterSession.expiresAt };
chrome.storage.local.set({
composioSessionId: toolRouterSession.sessionId,
composioChatMcpUrl: toolRouterSession.chatSessionMcpUrl,
composioToolRouterMcpUrl: toolRouterSession.toolRouterMcpUrl,
});
} catch (error) {
console.error('Failed to initialize Composio:', error);
}
}
} else {
setShowSettings(true);
}
});
};
useEffect(() => {
// Load settings on mount
loadSettings();
// Attach settings update listener only once to prevent duplicates
if (!listenerAttachedRef.current) {
const handleMessage = (request: any) => {
if (request.type === 'SETTINGS_UPDATED') {
console.log('Settings updated, refreshing...');
loadSettings();
}
};
chrome.runtime.onMessage.addListener(handleMessage);
listenerAttachedRef.current = true;
// Cleanup listener on unmount
return () => {
chrome.runtime.onMessage.removeListener(handleMessage);
listenerAttachedRef.current = false;
};
}
}, []);
const openSettings = () => {
chrome.runtime.openOptionsPage();
};
const isComposioSessionExpired = (): boolean => {
if (!composioSessionRef.current) return true;
return Date.now() > composioSessionRef.current.expiresAt;
};
const ensureApiKey = (): string => {
if (!settings?.apiKey) {
throw new Error('Google API key not configured. Please add it in Settings.');
}
return settings.apiKey;
};
const ensureModel = (): string => {
if (!settings?.model) {
throw new Error('AI model not configured. Please select a model in Settings.');
}
return settings.model;
};
const toggleBrowserTools = async () => {
const newValue = !browserToolsEnabled;
// Check if user has Google API key before enabling Browser Tools
if (newValue) {
if (!settings) {
alert('⚠️ Please configure your settings first.');
openSettings();
return;
}
if (settings.provider !== 'google' || !settings.apiKey) {
const confirmed = window.confirm(
'🌐 Browser Tools requires a Google API key\n\n' +
'Browser Tools uses Gemini 2.5 Computer Use for browser automation.\n\n' +
'Would you like to open Settings to add your Google API key?'
);
if (confirmed) {
openSettings();
}
return;
}
}
setBrowserToolsEnabled(newValue);
if (newValue) {
// Clear MCP cache when enabling browser tools
if (mcpClientRef.current) {
try {
await mcpClientRef.current.close();
} catch (error) {
console.error('Error closing MCP client:', error);
}
}
mcpClientRef.current = null;
mcpToolsRef.current = null;
setShowBrowserToolsWarning(false);
}
};
const stop = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
setIsLoading(false);
}
};
const newChat = async () => {
// Clear messages
setMessages([]);
setInput('');
setShowBrowserToolsWarning(false);
// Force close and clear ALL cached state
if (mcpClientRef.current) {
try {
await mcpClientRef.current.close();
console.log('Closed previous MCP client');
} catch (error) {
console.error('Error closing MCP client:', error);
}
}
mcpClientRef.current = null;
mcpToolsRef.current = null;
// Reinitialize Composio session if API key present
if (settings?.composioApiKey) {
try {
const { initializeComposioToolRouter } = await import('./tools');
// Use unique, persistent user ID
const toolRouterSession = await initializeComposioToolRouter(
settings.composioApiKey
);
chrome.storage.local.set({
composioSessionId: toolRouterSession.sessionId,
composioChatMcpUrl: toolRouterSession.chatSessionMcpUrl,
composioToolRouterMcpUrl: toolRouterSession.toolRouterMcpUrl,
});
console.log('New Composio session created');
console.log('Session ID:', toolRouterSession.sessionId);
} catch (error) {
console.error('Failed to create new Composio session:', error);
}
}
};
const streamWithGeminiComputerUse = async (messages: Message[]) => {
try {
const apiKey = ensureApiKey();
// Add initial assistant message
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
role: 'assistant',
content: '',
};
setMessages(prev => [...prev, assistantMessage]);
// Get initial screenshot with retry logic
let screenshot = await executeTool('screenshot', {});
if (!screenshot?.screenshot) {
const errorMsg = screenshot?.error || 'Unknown error capturing screenshot';
console.error('❌ Screenshot failed. Full response:', JSON.stringify(screenshot, null, 2));
throw new Error(`Failed to capture screenshot: ${errorMsg}`);
}
// Prepare conversation history
const contents: any[] = [];
// Add message history
for (const msg of messages) {
if (msg.role === 'user') {
contents.push({
role: 'user',
parts: [{ text: msg.content }]
});
} else {
contents.push({
role: 'model',
parts: [{ text: msg.content }]
});
}
}
if (screenshot && screenshot.screenshot) {
const lastUserContent = contents[contents.length - 1];
if (lastUserContent && lastUserContent.role === 'user') {
lastUserContent.parts.push({
inline_data: {
mime_type: 'image/png',
data: screenshot.screenshot.split(',')[1]
}
});
}
}
let responseText = '';
const maxTurns = 30;
const systemInstruction = `You are a browser automation assistant with ONLY browser control capabilities.
CRITICAL: You can ONLY use the computer_use tool functions for browser automation. DO NOT attempt to call any other functions like print, execute, or any programming functions.
AVAILABLE ACTIONS (computer_use tool only):
- click / click_at: Click at coordinates
- type_text_at: Type text (optionally with press_enter)
- scroll / scroll_down / scroll_up: Scroll the page
- navigate: Navigate to a URL
- wait / wait_5_seconds: Wait for page load
GUIDELINES:
1. NAVIGATION: Use 'navigate' function to go to websites
Example: navigate({url: "https://www.reddit.com"})
2. INTERACTION: Use coordinates from the screenshot you see
- Click at coordinates to interact with elements
- Type text at coordinates to fill forms
3. NO HALLUCINATING: Only use the functions listed above. Do NOT invent or call functions like print(), execute(), or any code functions.
4. EFFICIENCY: Complete tasks in fewest steps possible.`;
for (let turn = 0; turn < maxTurns; turn++) {
if (abortControllerRef.current?.signal.aborted) {
setMessages(prev => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg && lastMsg.role === 'assistant') {
lastMsg.content += '\n\n🛑 **Stopped by user**';
}
return updated;
});
return; // Exit the agent loop
}
console.log(`\n--- Turn ${turn + 1}/${maxTurns} ---`);
const requestBody = {
contents,
tools: [{
computer_use: {
environment: 'ENVIRONMENT_BROWSER'
}
}],
systemInstruction: {
parts: [{ text: systemInstruction }]
},
generationConfig: {
temperature: 1.0,
},
safetySettings: [
{
category: 'HARM_CATEGORY_HARASSMENT',
threshold: 'BLOCK_NONE'
},
{
category: 'HARM_CATEGORY_HATE_SPEECH',
threshold: 'BLOCK_NONE'
},
{
category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
threshold: 'BLOCK_NONE'
},
{
category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
threshold: 'BLOCK_NONE'
}
]
};
// Create abort controller with timeout
const abortController = new AbortController();
const timeoutId = setTimeout(() => abortController.abort(), 60000); // 60 second timeout
// Always use computer-use model for browser tools
const computerUseModel = 'gemini-2.5-computer-use-preview-10-2025';
let response;
try {
response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/${computerUseModel}:generateContent?key=${apiKey}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
signal: abortController.signal,
}
);
} finally {
clearTimeout(timeoutId);
}
if (!response.ok) {
let errorDetails;
try {
errorDetails = await response.json();
console.error('❌ Gemini API Error Response:', JSON.stringify(errorDetails, null, 2));
} catch (e) {
console.error('❌ Failed to parse error response:', e);
errorDetails = { statusText: response.statusText };
}
const errorMessage = errorDetails?.error?.message || `API request failed with status ${response.status}: ${response.statusText}`;
console.error('❌ Full error details:', errorDetails);
throw new Error(errorMessage);
}
const data = await response.json();
// Validate response structure with Zod
let validatedData;
try {
validatedData = GeminiResponseSchema.parse(data);
} catch (validationError) {
console.error('❌ Gemini API response failed validation:', validationError);
throw new Error(`Invalid Gemini API response format: ${(validationError as any).message}`);
}
// Check for safety blocks and prompt feedback
if (validatedData.promptFeedback?.blockReason) {
const blockReason = validatedData.promptFeedback.blockReason;
console.error('🚫 Request blocked by safety filter:', blockReason);
// Show detailed error to user
setMessages(prev => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg && lastMsg.role === 'assistant') {
lastMsg.content = `⚠️ **Safety Filter Blocked Request**\n\nReason: ${blockReason}\n\nThis request was blocked by Gemini's safety filters. Try:\n- Using a different webpage\n- Simplifying your request\n- Avoiding sensitive actions\n\nFull response:\n\`\`\`json\n${JSON.stringify(validatedData, null, 2)}\n\`\`\``;
}
return updated;
});
return; // Exit the loop
}
const candidate = validatedData.candidates?.[0];
if (!candidate) {
console.error('❌ No candidate in response. Full response:', JSON.stringify(data, null, 2));
throw new Error(`No candidate in Gemini response. Finish reason: ${data.candidates?.[0]?.finishReason || 'unknown'}. Full response: ${JSON.stringify(data)}`);
}
// Check if candidate has safety response requiring confirmation
const safetyResponse = candidate.safetyResponse;
if (safetyResponse?.requireConfirmation) {
// Show confirmation dialog to user
const confirmMessage = safetyResponse.message || 'This action requires confirmation. Do you want to proceed?';
const userConfirmed = window.confirm(`🔒 Human Confirmation Required\n\n${confirmMessage}\n\nProceed with this action?`);
if (!userConfirmed) {
setMessages(prev => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg && lastMsg.role === 'assistant') {
lastMsg.content += '\n\n❌ Action cancelled by user.';
}
return updated;
});
return; // Exit the loop
}
// Add confirmation to conversation
contents.push({
role: 'user',
parts: [{ text: 'CONFIRMED: User approved this action. Please proceed.' }]
});
// Continue to next iteration to re-run with confirmation
continue;
}
// Add model response to conversation
contents.push(candidate.content);
// Check if there are function calls
const parts = candidate.content?.parts || [];
const hasFunctionCalls = parts.some((p: any) => 'functionCall' in p && p.functionCall);
if (!hasFunctionCalls) {
// No more actions - task complete
for (const part of parts) {
if ('text' in part && typeof part.text === 'string') {
responseText += part.text;
}
}
break;
}
// Execute function calls
const functionResponses: any[] = [];
for (const part of parts) {
if ('text' in part && typeof part.text === 'string') {
responseText += part.text + '\n';
} else if ('functionCall' in part && part.functionCall) {
// Check if user clicked stop button
if (abortControllerRef.current?.signal.aborted) {
setMessages(prev => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg && lastMsg.role === 'assistant') {
lastMsg.content = responseText + '\n\n🛑 **Stopped by user**';
}
return updated;
});
return; // Exit the agent loop
}
const funcName = part.functionCall.name;
const funcArgs = part.functionCall.args || {};
responseText += `\n[Executing: ${funcName}]\n`;
// Execute the browser action
const result = await executeBrowserAction(funcName, funcArgs);
// Wait longer after navigation actions for page to load
const isNavigationAction = ['navigate', 'open_web_browser', 'navigate_to', 'go_to', 'click', 'click_at', 'mouse_click', 'go_back', 'back', 'go_forward', 'forward'].includes(funcName);
if (isNavigationAction) {
await new Promise(resolve => setTimeout(resolve, 2500)); // Wait 2.5 seconds for page to load
} else {
await new Promise(resolve => setTimeout(resolve, 500)); // Normal wait
}
screenshot = await executeTool('screenshot', {});
if (!screenshot || !screenshot.screenshot) {
console.warn('Failed to capture screenshot after action');
screenshot = { screenshot: '' }; // Continue without screenshot
}
// Get current page URL and viewport dimensions (required by Gemini)
let currentUrl = '';
let viewportInfo = '';
try {
const pageInfo = await executeTool('getPageContext', {});
currentUrl = pageInfo?.url || '';
// Include viewport dimensions to help Gemini understand coordinate space
if (pageInfo?.viewport) {
viewportInfo = ` Viewport: ${pageInfo.viewport.width}x${pageInfo.viewport.height}`;
}
} catch (error) {
console.warn('Failed to get page URL:', error);
}
// Build function response with URL and viewport info (required by Gemini)
const functionResponse: any = {
name: funcName,
response: {
...result,
url: currentUrl, // Gemini requires this
viewport_info: viewportInfo,
success: result.success !== false
}
};
functionResponses.push(functionResponse);
// Update UI
setMessages(prev => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg && lastMsg.role === 'assistant') {
lastMsg.content = responseText;
}
return updated;
});
}
}
// Add function responses back to conversation with new screenshot
if (functionResponses.length > 0) {
const userParts: any[] = functionResponses.map(fr => ({
function_response: fr
}));
// Add new screenshot
if (screenshot && screenshot.screenshot) {
userParts.push({
inline_data: {
mime_type: 'image/png',
data: screenshot.screenshot.split(',')[1]
}
});
}
contents.push({
role: 'user',
parts: userParts
});
}
}
// Final update
setMessages(prev => {
const updated = [...prev];
const lastMsg = updated[updated.length - 1];
if (lastMsg && lastMsg.role === 'assistant') {
lastMsg.content = responseText || 'Task completed';
}
return updated;
});
} catch (error: any) {
console.error('❌ Error with Gemini Computer Use:');
console.error('Error name:', error?.name);
console.error('Error message:', error?.message);
console.error('Error stack:', error?.stack);
console.error('Full error object:', error);
throw error;
}
};
// Scale coordinates from Gemini's 1000x1000 grid to actual viewport
const scaleCoordinates = async (x: number, y: number) => {
try {
// Get actual viewport dimensions
const pageInfo = await executeTool('getPageContext', {});
const viewportWidth = pageInfo?.viewport?.width || 1440;
const viewportHeight = pageInfo?.viewport?.height || 900;
// Gemini uses 1000x1000 normalized coordinates
const scaledX = Math.round((x / 1000) * viewportWidth);
const scaledY = Math.round((y / 1000) * viewportHeight);
return { x: scaledX, y: scaledY };
} catch (error) {
console.error('Failed to scale coordinates:', error);
// Fallback to original coordinates if scaling fails
return { x, y };
}
};
const requiresUserConfirmation = async (functionName: string, args: any): Promise<boolean> => {
let pageContext: any = {};
try {
pageContext = await executeTool('getPageContext', {});
} catch (e) {
console.warn('Could not get page context');
}
const url = pageContext?.url?.toLowerCase() || '';
const pageText = pageContext?.text?.toLowerCase() || '';
const alwaysConfirm = ['key_combination'];
const isSensitivePage =
url.includes('checkout') ||
url.includes('payment') ||
url.includes('login') ||
url.includes('signin') ||
url.includes('admin') ||
url.includes('delete') ||
url.includes('remove') ||
pageText.includes('checkout') ||
pageText.includes('payment') ||
pageText.includes('purchase') ||
pageText.includes('confirm order') ||
pageText.includes('delete') ||
pageText.includes('remove account');
const isSensitiveInput = functionName.includes('type') && (
args.text?.toLowerCase().includes('password') ||
args.text?.match(/\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}/) ||
pageText.includes('credit card') ||
pageText.includes('cvv') ||
pageText.includes('social security')
);
const isFormSubmission = functionName === 'type_text_at' && args.press_enter === true;
if (alwaysConfirm.includes(functionName) || isSensitivePage || isSensitiveInput || isFormSubmission) {
const confirmMessage = `🔒 Confirm Action\n\nAction: ${functionName}\nPage: ${url}` +
`${isSensitivePage ? '\n⚠️ Sensitive page' : ''}` +
`${isSensitiveInput ? '\n⚠️ Sensitive data' : ''}` +
`${isFormSubmission ? '\n⚠️ Form submission' : ''}\n\nProceed?`;
return window.confirm(confirmMessage);
}
return false;
};
const executeBrowserAction = async (functionName: string, args: any) => {
const userConfirmed = await requiresUserConfirmation(functionName, args);
if (!userConfirmed && (
['key_combination'].includes(functionName) ||
functionName.includes('type') ||
functionName === 'type_text_at'
)) {
return { success: false, error: 'Action cancelled by user', userCancelled: true };
}
switch (functionName) {
case 'click':
case 'click_at':
case 'mouse_click':
// Scale coordinates from Gemini's 1000x1000 grid to actual viewport
const clickCoords = await scaleCoordinates(
args.x || args.coordinate?.x || 0,
args.y || args.coordinate?.y || 0
);
return await executeTool('click', clickCoords);
case 'type':
case 'type_text':
case 'keyboard_input':
case 'input_text':
return await executeTool('type', {
selector: 'input:focus, textarea:focus, [contenteditable="true"]:focus',
text: args.text || args.input || args.content
});
case 'scroll':
case 'scroll_down':
case 'scroll_up':
case 'mouse_scroll':
const direction = functionName === 'scroll_up' ? 'up' :
functionName === 'scroll_down' ? 'down' :
args.direction || 'down';
return await executeTool('scroll', {
direction,
amount: args.amount || args.pixels || args.delta || 500
});
case 'navigate':
case 'open_web_browser':
case 'navigate_to':
case 'go_to':
return await executeTool('navigate', {
url: args.url || args.address || args.uri
});
case 'get_screenshot':
case 'take_screenshot':
case 'screenshot':
return await executeTool('screenshot', {});
case 'get_page_info':
case 'get_url':
case 'get_page_content':
return await executeTool('getPageContext', {});
case 'wait':
case 'sleep':
case 'delay':
const waitTime = (args.seconds || args.milliseconds / 1000 || 1) * 1000;
await new Promise(resolve => setTimeout(resolve, waitTime));
return { success: true, message: `Waited ${waitTime}ms` };
case 'press_key':
case 'key_press':
// Handle special keys like Enter, Tab, etc.
return await executeTool('type', {
selector: 'input:focus, textarea:focus, [contenteditable="true"]:focus',
text: args.key || args.keyCode
});
case 'type_text_at':
// Type text at coordinates (click first, then type)
// This mimics Python's playwright keyboard.type() behavior
if (args.x !== undefined && args.y !== undefined) {
// Scale coordinates before clicking
const typeCoords = await scaleCoordinates(args.x, args.y);
await executeTool('click', typeCoords);
// Wait for element to focus
await new Promise(resolve => setTimeout(resolve, 500));
}
// Clear existing text if requested
if (args.clear_before_typing !== false) {
// Use keyboard shortcuts to select all and delete (like Python implementation)
const isMac = navigator.userAgent.toUpperCase().indexOf('MAC') >= 0;
if (isMac) {
await executeTool('keyCombo', { keys: ['Meta', 'a'] });
} else {
await executeTool('keyCombo', { keys: ['Control', 'a'] });
}
await new Promise(resolve => setTimeout(resolve, 50));
await executeTool('pressKey', { key: 'Delete' });
await new Promise(resolve => setTimeout(resolve, 50));
}
// Use keyboard_type action which simulates actual keyboard typing
const typeResult = await new Promise<any>((resolve) => {
chrome.runtime.sendMessage(
{
type: 'EXECUTE_ACTION',
action: 'keyboard_type',
value: args.text || args.content
},
(response) => {
resolve(response);
}
);
});
// If press_enter is requested, send Enter key
if (args.press_enter) {
await new Promise(resolve => setTimeout(resolve, 100));
await executeTool('pressKey', { key: 'Enter' });
}
return typeResult;
case 'key_combination':
// Press keyboard key combinations like ["Control", "A"] or ["Enter"]
const keys = args.keys || [args.key] || ['Enter'];
return await executeTool('keyCombo', { keys });
case 'hover_at':
// Hover mouse at coordinates
const hoverCoords = await scaleCoordinates(args.x || 0, args.y || 0);
return await executeTool('hover', hoverCoords);
case 'scroll_document':
// Scroll the entire page
const scrollDir = args.direction || 'down';
return await executeTool('scroll', { direction: scrollDir, amount: 800 });
case 'scroll_at':
// Scroll at specific coordinates
return await executeTool('scroll', {
direction: args.direction || 'down',
amount: args.magnitude || 800
});
case 'wait_5_seconds':
await new Promise(resolve => setTimeout(resolve, 5000));
return { success: true, message: 'Waited 5 seconds' };
case 'go_back':
case 'back':
// Go back in browser history - properly async
return new Promise<any>((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]?.id) {
chrome.tabs.goBack(tabs[0].id);
// Add small delay for navigation to register
setTimeout(() => {
resolve({ success: true, message: 'Navigated back' });
}, 300);
} else {
resolve({ success: false, error: 'No active tab found' });
}
});
});
case 'go_forward':
case 'forward':
// Go forward in browser history - properly async
return new Promise<any>((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]?.id) {
chrome.tabs.goForward(tabs[0].id);
// Add small delay for navigation to register
setTimeout(() => {
resolve({ success: true, message: 'Navigated forward' });
}, 300);
} else {
resolve({ success: false, error: 'No active tab found' });
}
});
});
case 'search':
// Navigate to Google search
return await executeTool('navigate', { url: 'https://www.google.com' });
case 'drag_and_drop':
return await executeTool('dragDrop', {
x: args.x,
y: args.y,
destination_x: args.destination_x,
destination_y: args.destination_y
});
default:
console.warn('⚠️ Unknown Gemini function:', functionName, args);
return { success: false, error: `Unknown function: ${functionName}`, args };
}
};
// Stream with AI SDK using MCP tools
const streamWithAISDKAndMCP = async (messages: Message[], tools: any) => {
try {