-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2484 lines (2161 loc) · 101 KB
/
Copy pathserver.js
File metadata and controls
2484 lines (2161 loc) · 101 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
#!/usr/bin/env node
import 'dotenv/config';
import express from 'express';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import { WebSocketServer } from 'ws';
import http from 'http';
import https from 'https';
import fs from 'fs';
import os from 'os';
import WebSocket from 'ws';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { inspectUI } from './ui_inspector.js';
import { execSync } from 'child_process';
import multer from 'multer';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PORTS = [9000, 9001, 9002, 9003];
const POLL_INTERVAL = 1000; // 1 second
const SERVER_PORT = process.env.PORT || 3000;
const APP_PASSWORD = process.env.APP_PASSWORD || 'antigravity';
const AUTH_COOKIE_NAME = 'ag_auth_token';
// Security warning for default credentials
if (APP_PASSWORD === 'antigravity') {
console.warn('\n\x1b[33m%s\x1b[0m', '⚠️ SECURITY WARNING: Using default APP_PASSWORD ("antigravity").');
console.warn('\x1b[33m%s\x1b[0m', ' Set a strong APP_PASSWORD in your .env file for production use.\n');
}
// Note: hashString is defined later, so we'll initialize the token inside createServer or use a simple string for now.
let AUTH_TOKEN = 'ag_default_token';
// Multi-instance CDP manager
// Each entry: { cdp, title, workspacePath, lastSnapshot, lastSnapshotHash }
const cdpInstances = new Map();
let activePort = null; // Currently viewed workspace port
// Backward-compatible helper: returns the active CDP connection
function getActiveCDP() {
if (!activePort || !cdpInstances.has(activePort)) return null;
return cdpInstances.get(activePort).cdp;
}
// Get snapshot for the active instance
function getActiveSnapshot() {
if (!activePort || !cdpInstances.has(activePort)) return null;
return cdpInstances.get(activePort).lastSnapshot;
}
// Kill any existing process on the server port (prevents EADDRINUSE)
function killPortProcess(port) {
try {
if (process.platform === 'win32') {
// Windows: Find PID using netstat and kill it
const result = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
const lines = result.trim().split('\n');
const pids = new Set();
for (const line of lines) {
const parts = line.trim().split(/\s+/);
const pid = parts[parts.length - 1];
if (pid && pid !== '0') pids.add(pid);
}
for (const pid of pids) {
try {
execSync(`taskkill /PID ${pid} /F`, { stdio: 'pipe' });
console.log(`⚠️ Killed existing process on port ${port} (PID: ${pid})`);
} catch (e) { /* Process may have already exited */ }
}
} else {
// Linux/macOS: Use lsof and kill
const result = execSync(`lsof -ti:${port}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
const pids = result.trim().split('\n').filter(p => p);
for (const pid of pids) {
try {
execSync(`kill -9 ${pid}`, { stdio: 'pipe' });
console.log(`⚠️ Killed existing process on port ${port} (PID: ${pid})`);
} catch (e) { /* Process may have already exited */ }
}
}
// Small delay to let the port be released
return new Promise(resolve => setTimeout(resolve, 500));
} catch (e) {
// No process found on port - this is fine
return Promise.resolve();
}
}
// Get local IP address for mobile access
// Prefers real network IPs (192.168.x.x, 10.x.x.x) over virtual adapters (172.x.x.x from WSL/Docker)
function getLocalIP() {
const interfaces = os.networkInterfaces();
const candidates = [];
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
// Skip internal and non-IPv4 addresses
if (iface.family === 'IPv4' && !iface.internal) {
candidates.push({
address: iface.address,
name: name,
// Prioritize common home/office network ranges
priority: iface.address.startsWith('192.168.') ? 1 :
iface.address.startsWith('10.') ? 2 :
iface.address.startsWith('172.') ? 3 : 4
});
}
}
}
// Sort by priority and return the best one
candidates.sort((a, b) => a.priority - b.priority);
return candidates.length > 0 ? candidates[0].address : 'localhost';
}
// Helper: HTTP GET JSON
function getJson(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try { resolve(JSON.parse(data)); } catch (e) { reject(e); }
});
}).on('error', reject);
});
}
// Find Antigravity CDP endpoint (single - kept for backward compat)
async function discoverCDP() {
const errors = [];
for (const port of PORTS) {
try {
const list = await getJson(`http://127.0.0.1:${port}/json/list`);
// Priority 1: Standard Workbench (The main window)
const workbench = list.find(t => t.url?.includes('workbench.html') || (t.title && t.title.includes('workbench')));
if (workbench && workbench.webSocketDebuggerUrl) {
console.log('Found Workbench target:', workbench.title);
return { port, url: workbench.webSocketDebuggerUrl, title: workbench.title };
}
// Priority 2: Jetski/Launchpad (Fallback)
const jetski = list.find(t => t.url?.includes('jetski') || t.title === 'Launchpad');
if (jetski && jetski.webSocketDebuggerUrl) {
console.log('Found Jetski/Launchpad target:', jetski.title);
return { port, url: jetski.webSocketDebuggerUrl, title: jetski.title };
}
} catch (e) {
errors.push(`${port}: ${e.message}`);
}
}
const errorSummary = errors.length ? `Errors: ${errors.join(', ')}` : 'No ports responding';
throw new Error(`CDP not found. ${errorSummary}`);
}
// Discover ALL running Antigravity instances across all debug ports
async function discoverAllCDP() {
const instances = [];
for (const port of PORTS) {
try {
const list = await getJson(`http://127.0.0.1:${port}/json/list`);
const workbench = list.find(t => t.url?.includes('workbench.html') || (t.title && t.title.includes('workbench')));
if (workbench && workbench.webSocketDebuggerUrl) {
// Extract workspace name from the window title
// Typical title: "filename - WorkspaceName - Antigravity"
const rawTitle = workbench.title || '';
let workspaceName = rawTitle;
// Try to extract just the workspace/project name
const parts = rawTitle.split(' - ');
if (parts.length >= 2) {
// Usually the second-to-last part is the workspace name
workspaceName = parts.length >= 3 ? parts[parts.length - 2] : parts[0];
}
instances.push({
port,
url: workbench.webSocketDebuggerUrl,
title: workspaceName.trim(),
fullTitle: rawTitle
});
continue;
}
const jetski = list.find(t => t.url?.includes('jetski') || t.title === 'Launchpad');
if (jetski && jetski.webSocketDebuggerUrl) {
instances.push({
port,
url: jetski.webSocketDebuggerUrl,
title: jetski.title || `Workspace (port ${port})`,
fullTitle: jetski.title || ''
});
}
} catch (e) {
// Port not responding - skip
}
}
return instances;
}
// Connect to CDP
async function connectCDP(url) {
const ws = new WebSocket(url);
await new Promise((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', reject);
});
let idCounter = 1;
const pendingCalls = new Map(); // Track pending calls by ID
const contexts = [];
const CDP_CALL_TIMEOUT = 30000; // 30 seconds timeout
// Single centralized message handler (fixes MaxListenersExceeded warning)
ws.on('message', (msg) => {
try {
const data = JSON.parse(msg);
// Handle CDP method responses
if (data.id !== undefined && pendingCalls.has(data.id)) {
const { resolve, reject, timeoutId } = pendingCalls.get(data.id);
clearTimeout(timeoutId);
pendingCalls.delete(data.id);
if (data.error) reject(data.error);
else resolve(data.result);
}
// Handle execution context events
if (data.method === 'Runtime.executionContextCreated') {
contexts.push(data.params.context);
} else if (data.method === 'Runtime.executionContextDestroyed') {
const id = data.params.executionContextId;
const idx = contexts.findIndex(c => c.id === id);
if (idx !== -1) contexts.splice(idx, 1);
} else if (data.method === 'Runtime.executionContextsCleared') {
contexts.length = 0;
}
} catch (e) { }
});
const call = (method, params) => new Promise((resolve, reject) => {
const id = idCounter++;
// Setup timeout to prevent memory leaks from never-resolved calls
const timeoutId = setTimeout(() => {
if (pendingCalls.has(id)) {
pendingCalls.delete(id);
reject(new Error(`CDP call ${method} timed out after ${CDP_CALL_TIMEOUT}ms`));
}
}, CDP_CALL_TIMEOUT);
pendingCalls.set(id, { resolve, reject, timeoutId });
ws.send(JSON.stringify({ id, method, params }));
});
await call("Runtime.enable", {});
await new Promise(r => setTimeout(r, 1000));
return { ws, call, contexts };
}
// Capture chat snapshot
async function captureSnapshot(cdp) {
const CAPTURE_SCRIPT = `(async () => {
const cascade = document.getElementById('conversation') || document.getElementById('chat') || document.getElementById('cascade');
if (!cascade) {
// Debug info
const body = document.body;
const childIds = Array.from(body.children).map(c => c.id).filter(id => id).join(', ');
return { error: 'chat container not found', debug: { hasBody: !!body, availableIds: childIds } };
}
const cascadeStyles = window.getComputedStyle(cascade);
// Find the main scrollable container
const scrollContainer = cascade.querySelector('.overflow-y-auto, [data-scroll-area]') || cascade;
const scrollInfo = {
scrollTop: scrollContainer.scrollTop,
scrollHeight: scrollContainer.scrollHeight,
clientHeight: scrollContainer.clientHeight,
scrollPercent: scrollContainer.scrollTop / (scrollContainer.scrollHeight - scrollContainer.clientHeight) || 0
};
// Mark fixed/absolute elements in the original DOM before cloning
// This is the only way to reliably catch CSS-class-based positioning
const candidates = cascade.querySelectorAll('*');
candidates.forEach(el => {
try {
const pos = window.getComputedStyle(el).position;
if (pos === 'fixed' || pos === 'absolute') {
el.setAttribute('data-ag-rem', 'true');
}
} catch(e) {}
});
// Clone cascade to modify it without affecting the original
const clone = cascade.cloneNode(true);
// Clean up markers from the original DOM immediately after cloning
candidates.forEach(el => el.removeAttribute('data-ag-rem'));
// Aggressively remove the entire interaction/input/review area
try {
// 1. Identify common interaction wrappers by class combinations
const interactionSelectors = [
'.relative.flex.flex-col.gap-8',
'.flex.grow.flex-col.justify-start.gap-8',
'div[class*="interaction-area"]',
'.p-1.bg-gray-500\\/10',
'.outline-solid.justify-between',
'[contenteditable="true"]',
'[data-lexical-editor]',
'form',
// New aggressive selectors for recent Antigravity versions
'.mx-8.mb-8',
'.mx-4.mb-4',
'.fixed.bottom-0',
'.absolute.bottom-0'
];
interactionSelectors.forEach(selector => {
clone.querySelectorAll(selector).forEach(el => {
try {
// Protect elements that contain interactive buttons the user might need
const text = (el.innerText || '').toLowerCase();
const isActionArea = text.includes('allow') || text.includes('deny') ||
text.includes('review') || text.includes('run') ||
text.includes('confirm') || text.includes('apply') ||
text.includes('accept') || text.includes('reject') ||
text.includes('save') || text.includes('keep') ||
text.includes('discard');
// BUT: If it's specifically an input-related element, we DON'T protect it
const isEditor = el.getAttribute('contenteditable') === 'true' ||
el.hasAttribute('data-lexical-editor') ||
text.includes('ask anything') ||
text.includes('to mention');
if (!isEditor && isActionArea && selector !== '[contenteditable="true"]') {
return; // Protect action bars
}
// For the editor or its container, remove it
// Go up to find the main floating box if it's a deep selector
let targetToRemove = el;
if (isEditor || selector.includes('bottom-0')) {
// Find the common container for the input box (usually has margins or padding)
let parent = el.parentElement;
for (let i = 0; i < 4; i++) {
if (!parent || parent === clone) break;
const pCls = (parent.className || '').toString();
if (pCls.includes('mx-') || pCls.includes('mb-') || pCls.includes('bg-')) {
targetToRemove = parent;
}
parent = parent.parentElement;
}
}
if (targetToRemove && targetToRemove !== clone) {
targetToRemove.remove();
} else {
el.remove();
}
} catch(e) {}
});
});
// 2. Text-based cleanup for stray status bars and redundant desktop inputs
const allElements = clone.querySelectorAll('*');
allElements.forEach(el => {
try {
const text = (el.innerText || '').toLowerCase();
const placeholder = (el.getAttribute('placeholder') || '').toLowerCase();
const isInputPlaceholder = text.includes('ask anything') ||
text.includes('to mention') ||
placeholder.includes('ask anything');
// IF it's the main chat box (contains placeholder text), remove its container
if (isInputPlaceholder) {
// Find the container (usually a few levels up)
let container = el;
for (let i = 0; i < 5; i++) {
if (!container.parentElement || container.parentElement === clone) break;
const cls = (container.className || '').toString();
if (cls.includes('flex-col') || cls.includes('input') || cls.includes('area')) {
container.remove();
return;
}
container = container.parentElement;
}
el.remove();
return;
}
} catch(e) {}
});
// 3. NUCLEAR: If any editor or redundant UI remains, remove its entire branch
const redundantElements = clone.querySelectorAll('[contenteditable="true"], [data-lexical-editor], [role="textbox"], form, .mx-8.mb-8, .mx-4.mb-4');
redundantElements.forEach(el => {
try {
let branch = el;
// Go up to find the highest container that is still within the clone
// This ensures we remove the entire "box" (with chips, submit btn, etc)
while (branch.parentElement && branch.parentElement !== clone) {
const p = branch.parentElement;
const pCls = (p.className || '').toString().toLowerCase();
// Stop going up if we hit a main message/conversation wrapper
if (pCls.includes('message') || pCls.includes('bubble') || pCls.includes('conversation')) break;
branch = p;
}
if (branch && branch !== clone) branch.remove();
else el.remove();
} catch(e) {}
});
// 4. Force hide any fixed/absolute elements (desktop overlays)
// These were marked in the original before cloning to ensure accurate computed styles
clone.querySelectorAll('[data-ag-rem]').forEach(el => {
try {
const text = (el.innerText || '').toLowerCase();
// Exclude Action Bars we want to keep
if (text.includes('allow') || text.includes('deny') || text.includes('review') ||
text.includes('apply') || text.includes('accept') || text.includes('reject') ||
text.includes('save') || text.includes('run') || text.includes('confirm')) {
el.removeAttribute('data-ag-rem');
return;
}
el.remove();
} catch(e) {}
});
} catch (globalErr) { }
// Convert local images to base64
const images = clone.querySelectorAll('img');
const promises = Array.from(images).map(async (img) => {
const rawSrc = img.getAttribute('src');
if (rawSrc && (rawSrc.startsWith('/') || rawSrc.startsWith('vscode-file:')) && !rawSrc.startsWith('data:')) {
try {
const res = await fetch(rawSrc);
const blob = await res.blob();
await new Promise(r => {
const reader = new FileReader();
reader.onloadend = () => { img.src = reader.result; r(); };
reader.onerror = () => r();
reader.readAsDataURL(blob);
});
} catch(e) {}
}
});
await Promise.all(promises);
// Fix inline file references: Antigravity nests <div> elements inside
// <span> and <p> tags (e.g. file-type icons). Browsers auto-close <p> and
// <span> when they encounter a <div>, causing unwanted line breaks.
// Solution: Convert any <div> inside an inline parent to a <span>.
try {
const inlineTags = new Set(['SPAN', 'P', 'A', 'LABEL', 'EM', 'STRONG', 'CODE']);
const allDivs = Array.from(clone.querySelectorAll('div'));
for (const div of allDivs) {
try {
if (!div.parentNode) continue;
const parent = div.parentElement;
if (!parent) continue;
const parentIsInline = inlineTags.has(parent.tagName) ||
(parent.className && (parent.className.includes('inline-flex') || parent.className.includes('inline-block')));
if (parentIsInline) {
const span = document.createElement('span');
// MOVE children instead of copying (prevents orphaning nested divs)
while (div.firstChild) {
span.appendChild(div.firstChild);
}
if (div.className) span.className = div.className;
if (div.getAttribute('style')) span.setAttribute('style', div.getAttribute('style'));
span.style.display = 'inline-flex';
span.style.alignItems = 'center';
span.style.verticalAlign = 'middle';
div.replaceWith(span);
}
} catch(e) {}
}
} catch(e) {}
const html = clone.outerHTML;
const rules = [];
for (const sheet of document.styleSheets) {
try {
for (const rule of sheet.cssRules) {
rules.push(rule.cssText);
}
} catch (e) { }
}
const allCSS = rules.join('\\n');
return {
html: html,
css: allCSS,
backgroundColor: cascadeStyles.backgroundColor,
color: cascadeStyles.color,
fontFamily: cascadeStyles.fontFamily,
scrollInfo: scrollInfo,
stats: {
nodes: clone.getElementsByTagName('*').length,
htmlSize: html.length,
cssSize: allCSS.length
}
};
})()`;
for (const ctx of cdp.contexts) {
try {
// console.log(`Trying context ${ctx.id} (${ctx.name || ctx.origin})...`);
const result = await cdp.call("Runtime.evaluate", {
expression: CAPTURE_SCRIPT,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (result.exceptionDetails) {
// console.log(`Context ${ctx.id} exception:`, result.exceptionDetails);
continue;
}
if (result.result && result.result.value) {
const val = result.result.value;
if (val.error) {
// console.log(`Context ${ctx.id} script error:`, val.error);
// if (val.debug) console.log(` Debug info:`, JSON.stringify(val.debug));
} else {
return val;
}
}
} catch (e) {
console.log(`Context ${ctx.id} connection error:`, e.message);
}
}
return null;
}
// Inject message into Antigravity
async function injectMessage(cdp, text) {
// Use JSON.stringify for robust escaping (handles ", \, newlines, backticks, unicode, etc.)
const safeText = JSON.stringify(text);
const EXPRESSION = `(async () => {
const cancel = document.querySelector('[data-tooltip-id="input-send-button-cancel-tooltip"]');
if (cancel && cancel.offsetParent !== null) return { ok:false, reason:"busy" };
const editors = [...document.querySelectorAll('#conversation [contenteditable="true"], #chat [contenteditable="true"], #cascade [contenteditable="true"]')]
.filter(el => el.offsetParent !== null);
const editor = editors.at(-1);
if (!editor) return { ok:false, error:"editor_not_found" };
const textToInsert = ${safeText};
editor.focus();
document.execCommand?.("selectAll", false, null);
document.execCommand?.("delete", false, null);
let inserted = false;
try { inserted = !!document.execCommand?.("insertText", false, textToInsert); } catch {}
if (!inserted) {
editor.textContent = textToInsert;
editor.dispatchEvent(new InputEvent("beforeinput", { bubbles:true, inputType:"insertText", data: textToInsert }));
editor.dispatchEvent(new InputEvent("input", { bubbles:true, inputType:"insertText", data: textToInsert }));
}
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
const submit = document.querySelector("svg.lucide-arrow-right")?.closest("button");
if (submit && !submit.disabled) {
submit.click();
return { ok:true, method:"click_submit" };
}
// Submit button not found, but text is inserted - trigger Enter key
editor.dispatchEvent(new KeyboardEvent("keydown", { bubbles:true, key:"Enter", code:"Enter" }));
editor.dispatchEvent(new KeyboardEvent("keyup", { bubbles:true, key:"Enter", code:"Enter" }));
return { ok:true, method:"enter_keypress" };
})()`;
for (const ctx of cdp.contexts) {
try {
const result = await cdp.call("Runtime.evaluate", {
expression: EXPRESSION,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (result.result && result.result.value) {
return result.result.value;
}
} catch (e) { }
}
return { ok: false, reason: "no_context" };
}
// Set functionality mode (Fast vs Planning)
async function setMode(cdp, mode) {
if (!['Fast', 'Planning'].includes(mode)) return { error: 'Invalid mode' };
const EXP = `(async () => {
try {
// STRATEGY: Find the element that IS the current mode indicator.
// It will have text 'Fast' or 'Planning'.
// It might not be a <button>, could be a <div> with cursor-pointer.
// 1. Get all elements with text 'Fast' or 'Planning'
const allEls = Array.from(document.querySelectorAll('*'));
const candidates = allEls.filter(el => {
// Must have single text node child to avoid parents
if (el.children.length > 0) return false;
const txt = el.textContent.trim();
return txt === 'Fast' || txt === 'Planning';
});
// 2. Find the one that looks interactive (cursor-pointer)
// Traverse up from text node to find clickable container
let modeBtn = null;
for (const el of candidates) {
let current = el;
// Go up max 4 levels
for (let i = 0; i < 4; i++) {
if (!current) break;
const style = window.getComputedStyle(current);
if (style.cursor === 'pointer' || current.tagName === 'BUTTON') {
modeBtn = current;
break;
}
current = current.parentElement;
}
if (modeBtn) break;
}
if (!modeBtn) return { error: 'Mode indicator/button not found' };
// Check if already set
if (modeBtn.innerText.includes('${mode}')) return { success: true, alreadySet: true };
// 3. Click to open menu
modeBtn.click();
await new Promise(r => setTimeout(r, 600));
// 4. Find the dialog
let visibleDialog = Array.from(document.querySelectorAll('[role="dialog"]'))
.find(d => d.offsetHeight > 0 && d.innerText.includes('${mode}'));
// Fallback: Just look for any new visible container if role=dialog is missing
if (!visibleDialog) {
// Maybe it's not role=dialog? Look for a popover-like div
visibleDialog = Array.from(document.querySelectorAll('div'))
.find(d => {
const style = window.getComputedStyle(d);
return d.offsetHeight > 0 &&
(style.position === 'absolute' || style.position === 'fixed') &&
d.innerText.includes('${mode}') &&
!d.innerText.includes('Files With Changes'); // Anti-context menu
});
}
if (!visibleDialog) return { error: 'Dropdown not opened or options not visible' };
// 5. Click the option
const allDialogEls = Array.from(visibleDialog.querySelectorAll('*'));
const target = allDialogEls.find(el =>
el.children.length === 0 && el.textContent.trim() === '${mode}'
);
if (target) {
target.click();
await new Promise(r => setTimeout(r, 200));
return { success: true };
}
return { error: 'Mode option text not found in dialog. Dialog text: ' + visibleDialog.innerText.substring(0, 50) };
} catch(err) {
return { error: 'JS Error: ' + err.toString() };
}
})()`;
for (const ctx of cdp.contexts) {
try {
const res = await cdp.call("Runtime.evaluate", {
expression: EXP,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (res.result?.value) return res.result.value;
} catch (e) { }
}
return { error: 'Context failed' };
}
// Stop Generation
async function stopGeneration(cdp) {
const EXP = `(async () => {
// Look for the cancel button
const cancel = document.querySelector('[data-tooltip-id="input-send-button-cancel-tooltip"]');
if (cancel && cancel.offsetParent !== null) {
cancel.click();
return { success: true };
}
// Fallback: Look for a square icon in the send button area
const stopBtn = document.querySelector('button svg.lucide-square')?.closest('button');
if (stopBtn && stopBtn.offsetParent !== null) {
stopBtn.click();
return { success: true, method: 'fallback_square' };
}
return { error: 'No active generation found to stop' };
})()`;
for (const ctx of cdp.contexts) {
try {
const res = await cdp.call("Runtime.evaluate", {
expression: EXP,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (res.result?.value) return res.result.value;
} catch (e) { }
}
return { error: 'Context failed' };
}
// Click Element (Remote)
async function clickElement(cdp, { selector, index, textContent }) {
const safeText = JSON.stringify(textContent || '');
const EXP = `(async () => {
try {
// Priority: Search inside the chat container first for better accuracy
const root = document.getElementById('conversation') || document.getElementById('chat') || document.getElementById('cascade') || document;
// Strategy: Find all elements matching the selector
let elements = Array.from(root.querySelectorAll('${selector}'));
const filterText = ${safeText};
if (filterText) {
elements = elements.filter(el => {
const txt = (el.innerText || el.textContent || '').trim();
const firstLine = txt.split('\\n')[0].trim();
// Match if first line matches (thought blocks) or if it contains the label (buttons)
return firstLine === filterText || txt.includes(filterText);
});
// CRITICAL: If elements are nested (e.g. <div><span>Text</span></div>),
// both will match. We only want the most specific (inner-most) one.
elements = elements.filter(el => {
return !elements.some(other => other !== el && el.contains(other));
});
}
const target = elements[${index}];
if (target) {
// Focus and Click
if (target.focus) target.focus();
target.click();
return { success: true, found: elements.length, indexUsed: ${index} };
}
return { error: 'Element not found at index ' + ${index} + ' among ' + elements.length + ' matches' };
} catch(e) {
return { error: e.toString() };
}
})()`;
for (const ctx of cdp.contexts) {
try {
const res = await cdp.call("Runtime.evaluate", {
expression: EXP,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (res.result?.value?.success) return res.result.value;
// If we found it but click didn't return success (unlikely with this script), continue to next context
} catch (e) { }
}
return { error: 'Click failed in all contexts or element not found at index' };
}
// Remote scroll - sync phone scroll to desktop
async function remoteScroll(cdp, { scrollTop, scrollPercent }) {
// Try to scroll the chat container in Antigravity
const EXPRESSION = `(async () => {
try {
// Find the main scrollable chat container
const scrollables = [...document.querySelectorAll('#conversation [class*="scroll"], #chat [class*="scroll"], #cascade [class*="scroll"], #conversation [style*="overflow"], #chat [style*="overflow"], #cascade [style*="overflow"]')]
.filter(el => el.scrollHeight > el.clientHeight);
// Also check for the main chat area
const chatArea = document.querySelector('#conversation .overflow-y-auto, #chat .overflow-y-auto, #cascade .overflow-y-auto, #conversation [data-scroll-area], #chat [data-scroll-area], #cascade [data-scroll-area]');
if (chatArea) scrollables.unshift(chatArea);
if (scrollables.length === 0) {
// Fallback: scroll the main container element
const cascade = document.getElementById('conversation') || document.getElementById('chat') || document.getElementById('cascade');
if (cascade && cascade.scrollHeight > cascade.clientHeight) {
scrollables.push(cascade);
}
}
if (scrollables.length === 0) return { error: 'No scrollable element found' };
const target = scrollables[0];
// Use percentage-based scrolling for better sync
if (${scrollPercent} !== undefined) {
const maxScroll = target.scrollHeight - target.clientHeight;
target.scrollTop = maxScroll * ${scrollPercent};
} else {
target.scrollTop = ${scrollTop || 0};
}
return { success: true, scrolled: target.scrollTop };
} catch(e) {
return { error: e.toString() };
}
})()`;
for (const ctx of cdp.contexts) {
try {
const res = await cdp.call("Runtime.evaluate", {
expression: EXPRESSION,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (res.result?.value?.success) return res.result.value;
} catch (e) { }
}
return { error: 'Scroll failed in all contexts' };
}
// Set AI Model
async function setModel(cdp, modelName) {
const EXP = `(async () => {
try {
// STRATEGY: Multi-layered approach to find and click the model selector
const KNOWN_KEYWORDS = ["Gemini", "Claude", "GPT", "Model"];
let modelBtn = null;
// Strategy 1: Look for data-tooltip-id patterns (most reliable)
modelBtn = document.querySelector('[data-tooltip-id*="model"], [data-tooltip-id*="provider"]');
// Strategy 2: Look for buttons/elements containing model keywords with SVG icons
if (!modelBtn) {
const candidates = Array.from(document.querySelectorAll('button, [role="button"], div, span'))
.filter(el => {
const txt = el.innerText?.trim() || '';
return KNOWN_KEYWORDS.some(k => txt.includes(k)) && el.offsetParent !== null;
});
// Find the best one (has chevron icon or cursor pointer)
modelBtn = candidates.find(el => {
const style = window.getComputedStyle(el);
const hasSvg = el.querySelector('svg.lucide-chevron-up') ||
el.querySelector('svg.lucide-chevron-down') ||
el.querySelector('svg[class*="chevron"]') ||
el.querySelector('svg');
return (style.cursor === 'pointer' || el.tagName === 'BUTTON') && hasSvg;
}) || candidates[0];
}
// Strategy 3: Traverse from text nodes up to clickable parents
if (!modelBtn) {
const allEls = Array.from(document.querySelectorAll('*'));
const textNodes = allEls.filter(el => {
if (el.children.length > 0) return false;
const txt = el.textContent;
return KNOWN_KEYWORDS.some(k => txt.includes(k));
});
for (const el of textNodes) {
let current = el;
for (let i = 0; i < 5; i++) {
if (!current) break;
if (current.tagName === 'BUTTON' || window.getComputedStyle(current).cursor === 'pointer') {
modelBtn = current;
break;
}
current = current.parentElement;
}
if (modelBtn) break;
}
}
if (!modelBtn) return { error: 'Model selector button not found' };
// Click to open menu
modelBtn.click();
await new Promise(r => setTimeout(r, 600));
// Find the dialog/dropdown - search globally (React portals render at body level)
let visibleDialog = null;
// Try specific dialog patterns first
const dialogs = Array.from(document.querySelectorAll('[role="dialog"], [role="listbox"], [role="menu"], [data-radix-popper-content-wrapper]'));
visibleDialog = dialogs.find(d => d.offsetHeight > 0 && d.innerText?.includes('${modelName}'));
// Fallback: look for positioned divs
if (!visibleDialog) {
visibleDialog = Array.from(document.querySelectorAll('div'))
.find(d => {
const style = window.getComputedStyle(d);
return d.offsetHeight > 0 &&
(style.position === 'absolute' || style.position === 'fixed') &&
d.innerText?.includes('${modelName}') &&
!d.innerText?.includes('Files With Changes');
});
}
if (!visibleDialog) {
// Blind search across entire document as last resort
const allElements = Array.from(document.querySelectorAll('[role="menuitem"], [role="option"]'));
const target = allElements.find(el =>
el.offsetParent !== null &&
(el.innerText?.trim() === '${modelName}' || el.innerText?.includes('${modelName}'))
);
if (target) {
target.click();
return { success: true, method: 'blind_search' };
}
return { error: 'Model list not opened' };
}
// Select specific model inside the dialog
const allDialogEls = Array.from(visibleDialog.querySelectorAll('*'));
const validEls = allDialogEls.filter(el => el.children.length === 0 && el.textContent?.trim().length > 0);
// A. Exact Match (Best)
let target = validEls.find(el => el.textContent.trim() === '${modelName}');
// B. Page contains Model
if (!target) {
target = validEls.find(el => el.textContent.includes('${modelName}'));
}
// C. Closest partial match
if (!target) {
const partialMatches = validEls.filter(el => '${modelName}'.includes(el.textContent.trim()));
if (partialMatches.length > 0) {
partialMatches.sort((a, b) => b.textContent.trim().length - a.textContent.trim().length);
target = partialMatches[0];
}
}
if (target) {
target.scrollIntoView({block: 'center'});
target.click();
await new Promise(r => setTimeout(r, 200));
return { success: true };
}
return { error: 'Model "${modelName}" not found in list. Visible: ' + visibleDialog.innerText.substring(0, 100) };
} catch(err) {
return { error: 'JS Error: ' + err.toString() };
}
})()`;
for (const ctx of cdp.contexts) {
try {
const res = await cdp.call("Runtime.evaluate", {
expression: EXP,
returnByValue: true,
awaitPromise: true,
contextId: ctx.id
});
if (res.result?.value) return res.result.value;
} catch (e) { }
}
return { error: 'Context failed' };
}
// Start New Chat - Click the + button at the TOP of the chat window (NOT the context/media + button)
async function startNewChat(cdp) {
const EXP = `(async () => {
try {
// Priority 1: Exact selector from user (data-tooltip-id="new-conversation-tooltip")
const exactBtn = document.querySelector('[data-tooltip-id="new-conversation-tooltip"]');
if (exactBtn) {
exactBtn.click();