-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowserManager.js
More file actions
1456 lines (1382 loc) · 65.5 KB
/
browserManager.js
File metadata and controls
1456 lines (1382 loc) · 65.5 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
/**
* guIDE 2.0 — Browser Manager
*
* Manages the browser preview lifecycle:
* 1. Live server (static file serving with hot-reload) — via liveServer.js
* 2. Playwright browser automation (optional) — if installed
* 3. Preview URL management for BrowserPanel
*
* Used by:
* - mcpToolServer (AI browser tool calls)
* - /api/preview/* REST endpoints in server/main.js
* - BrowserPanel (frontend component)
*/
'use strict';
const EventEmitter = require('events');
const path = require('path');
class BrowserManager extends EventEmitter {
/**
* @param {{ liveServer: object, parentWindow: object }} options
*/
constructor(options = {}) {
super();
console.log('[BrowserManager] constructor START');
this.liveServer = options.liveServer || null;
this.parentWindow = options.parentWindow || null;
this._previewUrl = null;
this._previewPort = null;
this._wsPort = null;
this._playwright = null;
this._browser = null;
this._page = null;
this._navHistory = []; // [{url, title, timestamp, action}] — tracks what the model already did
this._lastSnapshotUrl = null;
this._lastSnapshotTime = 0;
this._refFrameMap = new Map(); // ref number → owning Playwright Frame
this._snapshotGen = 0; // Incremented each getSnapshot() call
this._refGenMap = new Map(); // ref number → snapshot generation it belongs to
console.log('[BrowserManager] constructor DONE');
}
/* ── Live Preview ──────────────────────────────────────── */
/**
* Start the live preview server for a project directory.
* @param {string} rootPath — directory to serve
* @returns {Promise<{ success: boolean, url?: string, port?: number, error?: string }>}
*/
async startPreview(rootPath) {
console.log(`[BrowserManager] startPreview START: rootPath=${rootPath}`);
if (!this.liveServer) {
console.warn('[BrowserManager] startPreview: no liveServer');
return { success: false, error: 'Live server module not available' };
}
const result = await this.liveServer.start(rootPath);
console.log(`[BrowserManager] startPreview: liveServer result success=${result.success}`);
if (result.success) {
this._previewUrl = result.url;
this._previewPort = result.port;
this._wsPort = result.wsPort;
this.emit('preview-started', { url: result.url, port: result.port });
// Notify frontend via mainWindow
if (this.parentWindow?.webContents) {
this.parentWindow.webContents.send('preview-started', {
url: result.url, port: result.port,
});
}
}
console.log('[BrowserManager] startPreview DONE');
return result;
}
/**
* Stop the live preview server.
*/
async stopPreview() {
console.log('[BrowserManager] stopPreview START');
if (!this.liveServer) {
console.warn('[BrowserManager] stopPreview: no liveServer');
return { success: false, error: 'No live server' };
}
await this.liveServer.stop();
this._previewUrl = null;
this._previewPort = null;
this._wsPort = null;
this.emit('preview-stopped');
if (this.parentWindow?.webContents) {
this.parentWindow.webContents.send('preview-stopped');
}
console.log('[BrowserManager] stopPreview DONE');
return { success: true };
}
/**
* Trigger a reload on all connected preview clients.
*/
reloadPreview() {
if (this.liveServer?.notifyReload) {
this.liveServer.notifyReload();
}
}
/**
* Get current preview status.
*/
getPreviewStatus() {
return {
active: !!this._previewUrl,
url: this._previewUrl,
port: this._previewPort,
wsPort: this._wsPort,
};
}
/* ── Navigation (used by browser tool calls) ───────────── */
/**
* Navigate to a URL. Uses Playwright if available, otherwise opens in preview.
*/
async navigate(url) {
console.log(`[BrowserManager] navigate START: url=${url}`);
const ok = await this._ensurePage();
if (!ok) {
console.warn('[BrowserManager] navigate: could not launch browser');
return { success: false, error: 'Could not launch browser' };
}
if (this._page) {
try {
// Use page.goto() return value to get the HTTP response object
console.log(`[BrowserManager] navigate: page.goto ${url}`);
const response = await this._page.goto(url, { waitUntil: 'load', timeout: 90000 });
// Wait for SPAs to render — load event fires after initial render,
// but SPAs need extra time for JS-driven content
try { await this._page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {}); } catch {}
// Brief pause for any post-networkidle JS rendering
try { await this._page.waitForTimeout(500).catch(() => {}); } catch {}
const finalUrl = this._page.url();
const title = await this._page.title().catch(() => '');
this._navHistory.push({ url: finalUrl, title, timestamp: Date.now(), action: 'navigate' });
if (this._navHistory.length > 30) this._navHistory = this._navHistory.slice(-30);
// Check HTTP status code from the navigation response (not title keywords)
const httpStatus = response ? response.status() : 0;
console.log(`[BrowserManager] navigate: httpStatus=${httpStatus}, finalUrl=${finalUrl}`);
if (httpStatus >= 400) {
const snapshot = await this.getSnapshot();
const snapshotText = snapshot.success ? snapshot.text : '';
console.warn(`[BrowserManager] navigate: HTTP error ${httpStatus}`);
return {
success: false,
url: finalUrl,
title,
httpStatus,
error: `HTTP ${httpStatus}: ${response?.statusText() || 'Error'}`,
snapshot: snapshotText || undefined,
};
}
// Auto-snapshot: include page content so the model can see what's on the page
// without needing a separate browser_snapshot call
const snapshot = await this.getSnapshot();
if (snapshot.success) {
console.log(`[BrowserManager] navigate DONE: success, url=${finalUrl}, snapshotLen=${snapshot.text?.length || 0}`);
return { success: true, url: finalUrl, title, httpStatus, snapshot: snapshot.text };
}
console.log(`[BrowserManager] navigate DONE: success, url=${finalUrl}`);
return { success: true, url: finalUrl, title, httpStatus };
} catch (e) {
console.error(`[BrowserManager] navigate ERROR: ${e.message}`);
return { success: false, error: e.message };
}
}
// No Playwright — send URL to frontend for iframe navigation
if (this.parentWindow?.webContents) {
this.parentWindow.webContents.send('preview-navigate', { url });
}
console.log('[BrowserManager] navigate: frontend-iframe fallback');
return { success: true, url, method: 'frontend-iframe' };
}
/* ── Playwright Integration (optional) ─────────────────── */
/**
* Launch Playwright browser. Returns false if Playwright is not installed.
*/
async launchPlaywright() {
console.log('[BrowserManager] launchPlaywright START');
if (this._browser && this._page) {
// Verify the page is actually alive
try { await this._page.evaluate(() => true); console.log('[BrowserManager] launchPlaywright: already alive'); return { success: true, message: 'Already launched' }; } catch {}
// Page is dead — clean up and relaunch
console.log('[BrowserManager] launchPlaywright: page dead, closing');
await this.closePlaywright();
}
try {
this._playwright = require('playwright');
} catch {
console.warn('[BrowserManager] launchPlaywright: Playwright not installed');
return { success: false, error: 'Playwright not installed. Run: npm i playwright' };
}
try {
this._browser = await this._playwright.chromium.launch({ headless: false });
this._page = await this._browser.newPage();
console.log('[BrowserManager] launchPlaywright: Chromium launched, new page created');
// Register disconnect handler so we know when browser dies
this._browser.on('disconnected', () => {
console.log('[BrowserManager] Browser disconnected — clearing references');
this._page = null;
this._browser = null;
});
console.log('[BrowserManager] launchPlaywright DONE');
return { success: true };
} catch (e) {
console.error(`[BrowserManager] launchPlaywright FAILED: ${e.message}`);
return { success: false, error: `Failed to launch browser: ${e.message}` };
}
}
/**
* Ensure a live Playwright page exists. Auto-reconnects if the browser died.
* @returns {Promise<boolean>} true if page is ready
*/
async _ensurePage() {
console.log('[BrowserManager] _ensurePage START');
if (this._page) {
try { await this._page.evaluate(() => true); console.log('[BrowserManager] _ensurePage: page alive'); return true; } catch {}
// Page is dead — but the browser process may still be alive with other pages
// (e.g., SAML redirect killed the current page but created a new one in the same context).
// Check for surviving pages before launching a new browser.
console.log('[BrowserManager] _ensurePage: page dead, checking for surviving pages in context');
this._page = null;
if (this._browser) {
try {
const contexts = this._browser.contexts();
for (const ctx of contexts) {
const pages = ctx.pages();
for (const p of pages) {
try {
await p.evaluate(() => true);
// Found a living page — switch to it instead of relaunching
console.log(`[BrowserManager] _ensurePage: found surviving page at ${p.url()}, switching to it`);
this._page = p;
return true;
} catch {}
}
}
} catch {}
// Browser is alive but no usable pages — close it and relaunch
console.log('[BrowserManager] _ensurePage: browser alive but no usable pages, closing browser');
try { await this._browser.close(); } catch {}
}
this._browser = null;
}
const result = await this.launchPlaywright();
console.log(`[BrowserManager] _ensurePage DONE: success=${result.success}`);
return result.success;
}
/**
* Close Playwright browser.
*/
async closePlaywright() {
console.log('[BrowserManager] closePlaywright START');
if (this._page) { try { await this._page.close(); } catch (e) { console.warn('[BrowserManager] closePlaywright page close failed:', e.message); } }
if (this._browser) { try { await this._browser.close(); } catch (e) { console.warn('[BrowserManager] closePlaywright browser close failed:', e.message); } }
this._page = null;
this._browser = null;
this._playwright = null;
console.log('[BrowserManager] closePlaywright DONE');
return { success: true };
}
/**
* Take a screenshot of the current page.
* @returns {Promise<{ success: boolean, screenshot?: string, error?: string }>}
*/
async screenshot() {
console.log('[BrowserManager] screenshot START');
if (!(await this._ensurePage())) {
console.warn('[BrowserManager] screenshot: no page');
return { success: false, error: 'No browser page open' };
}
try {
const buffer = await this._page.screenshot({ type: 'png' });
const base64 = buffer.toString('base64');
console.log(`[BrowserManager] screenshot DONE: ${base64.length} chars`);
return { success: true, screenshot: base64 };
} catch (e) {
console.error(`[BrowserManager] screenshot ERROR: ${e.message}`);
return { success: false, error: e.message };
}
}
/**
* Inject data-ref attributes into all interactive elements on the current page.
* Returns the array of element descriptions. Called by getSnapshot and by
* click/type before resolving a ref selector (data-ref attrs are lost on
* page navigation/reload, causing [data-ref="N"] selectors to fail).
*/
async _ensureRefs() {
if (!this._page) return null;
return this._page.evaluate(() => {
const selectors = [
'input', 'button', 'a', 'select', 'textarea',
'[role="button"]', '[role="link"]', '[role="textbox"]',
'[role="combobox"]', '[role="checkbox"]', '[role="radio"]',
'[role="tab"]', '[role="menuitem"]', '[role="option"]',
'[contenteditable]', 'summary', 'details',
'iframe', 'form',
];
const all = [...document.querySelectorAll(selectors.join(','))]
.filter(el => {
if (el.offsetParent !== null) return true;
if (el.type === 'hidden') return false;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
if (style.position === 'fixed' || style.position === 'sticky') return true;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
const lines = [];
for (let i = 0; i < all.length; i++) {
const el = all[i];
el.setAttribute('data-ref', String(i));
const tag = el.tagName.toLowerCase();
const type = el.type || '';
const name = el.name || el.id || '';
const placeholder = el.placeholder || '';
const value = el.value || '';
// PL8: Links need more text (course names, long descriptions) — 200 chars.
// Other elements (buttons, inputs) are typically shorter — 120 chars.
const textLimit = (tag === 'a' || role === 'link') ? 200 : 120;
const text = (el.textContent || '').trim().substring(0, textLimit);
const href = el.href || '';
const role = el.getAttribute('role') || '';
const ariaLabel = el.getAttribute('aria-label') || '';
const titleAttr = el.getAttribute('title') || '';
const imgAlt = (!text && el.querySelector)
? (el.querySelector('img')?.getAttribute('alt') || '') : '';
const isSubmit = (type === 'submit' && tag === 'input') || (tag === 'button' && el.form !== null && type !== 'button' && type !== 'reset');
let desc = `[ref=${i}] <${tag}`;
if (type) desc += ` type="${type}"`;
if (name) desc += ` name="${name}"`;
if (role) desc += ` role="${role}"`;
if (ariaLabel) desc += ` aria-label="${ariaLabel}"`;
if (titleAttr) desc += ` title="${titleAttr.substring(0, 80)}"`;
if (placeholder) desc += ` placeholder="${placeholder}"`;
if (value && type !== 'password') desc += ` value="${value.substring(0, 50)}"`;
if (href) desc += ` href="${href.substring(0, 150)}"`;
desc += '>';
if (text && type !== 'password' && tag !== 'input') {
// PL8: General-purpose cleanup for link text: strip trailing registration codes
// (patterns like NNNN.XXXX-XX.NNNNN.N) and trailing date suffixes.
// These are common in LMS and portal sites and add noise without helping identify the link.
let cleanText = text;
if (tag === 'a' || role === 'link') {
cleanText = cleanText.replace(/,?\s+\d{4}\.\w+-\w+\.\d+\.\d+$/g, '');
cleanText = cleanText.replace(/,?\s+Ends\s+\w+\s+\d{1,2},?\s+\d{4}\s+at\s+\d{1,2}:\d{2}\s*[AP]M$/i, '');
}
desc += ` ${cleanText}`;
} else if (imgAlt) desc += ` [img: ${imgAlt.substring(0, 120)}]`;
if (isSubmit) desc += ' [SUBMIT]';
if (tag === 'select') desc += ' [SELECT]';
lines.push(desc);
}
const pageText = (document.body?.innerText || '').substring(0, 50000);
// Extract visible text from same-origin iframes.
// Many web apps render their main content inside iframes.
// Without this, the snapshot only shows "<iframe>" elements and the model
// cannot see or interact with the content.
const iframeTexts = [];
try {
const iframes = document.querySelectorAll('iframe');
for (const iframe of iframes) {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
if (iframeDoc && iframeDoc.body) {
const src = iframe.src || iframe.getAttribute('src') || '';
const iframeText = (iframeDoc.body.innerText || '').trim();
if (iframeText.length > 0) {
const iframeInteractive = iframeDoc.querySelectorAll('a, button, input, select, textarea, [role="button"], [role="link"]');
const iframeElCount = iframeInteractive.length;
// PL3: Check if iframe content is scrollable — tell the model if more content exists
const scrollH = iframeDoc.body.scrollHeight || 0;
const clientH = iframeDoc.body.clientHeight || 0;
const scrollable = scrollH > clientH;
const scrollPct = clientH > 0 ? Math.round((clientH / scrollH) * 100) : 100;
const scrollNote = scrollable ? `, scrollable: ${scrollPct}% visible — use browser_scroll to see more` : '';
iframeTexts.push(`--- iframe content (${iframeElCount} interactive elements, src="${src.substring(0, 120)}"${scrollNote}) ---\n${iframeText.substring(0, 20000)}`);
}
}
} catch (e) {
// Cross-origin iframe — cannot access content (CORS)
const src = iframe.src || iframe.getAttribute('src') || '';
if (src) iframeTexts.push(`--- iframe (cross-origin, cannot access content, src="${src.substring(0, 120)}") ---`);
}
}
} catch {}
const fullPageText = iframeTexts.length > 0
? pageText + '\n\n' + iframeTexts.join('\n\n')
: pageText;
return { elementList: lines.join('\n'), pageText: fullPageText };
});
}
async getSnapshot() {
console.log('[BrowserManager] getSnapshot START');
if (!(await this._ensurePage())) {
console.warn('[BrowserManager] getSnapshot: no page');
return { success: false, error: 'No browser page open' };
}
try {
const title = await this._page.title();
const url = this._page.url();
console.log(`[BrowserManager] getSnapshot: title=${title}, url=${url}`);
// Inject data-ref attributes and build a numbered element list
const snapshotData = await this._ensureRefs();
// Build ref→frame map. Main frame refs are already numbered by _ensureRefs.
// Now inject data-ref into child frames with CONTINUING ref numbers so the model
// sees a single unified [ref=N] namespace across all frames.
this._refFrameMap.clear();
this._refGenMap.clear();
this._snapshotGen++; // PL7: New generation for this snapshot
const mainFrameElementCount = snapshotData.elementList ? snapshotData.elementList.split('\n').length : 0;
// All main frame refs map to the main frame AND belong to current generation
const mainFrame = this._page.mainFrame();
for (let i = 0; i < mainFrameElementCount; i++) {
this._refFrameMap.set(i, mainFrame);
this._refGenMap.set(i, this._snapshotGen);
}
// Extract content from ALL frames (including cross-origin iframes).
// Playwright's page.frames() bypasses CORS — it can read cross-origin frame content
// that the DOM-level iframe extraction in _ensureRefs() cannot access.
// This is critical for sites that render content in cross-origin iframes.
let frameTexts = [];
let iframeElementLines = []; // [ref=N] lines for iframe elements
let nextRef = mainFrameElementCount; // continuing ref counter for iframe elements
try {
const frames = this._page.frames();
for (const frame of frames) {
if (frame === this._page.mainFrame()) continue; // skip main frame (already in snapshotData)
const frameUrl = frame.url();
try {
const frameBody = await frame.evaluate((startRef) => {
const body = document.body;
if (!body) return { text: '', interactive: [], refLines: [], nextRef: startRef };
const text = (body.innerText || '').trim();
const interactive = [...document.querySelectorAll('a, button, input, select, textarea, [role="button"], [role="link"], [role="textbox"], [role="combobox"]')].map(el => {
const tag = el.tagName.toLowerCase();
const text = (el.textContent || '').trim().substring(0, 60);
const href = el.href || '';
const type = el.type || '';
const name = el.name || el.id || '';
const placeholder = el.placeholder || '';
return `[${tag}${type ? ` type="${type}"` : ''}${name ? ` name="${name}"` : ''}${placeholder ? ` placeholder="${placeholder}"` : ''}${href ? ` href="${href.substring(0, 80)}"` : ''}] ${text}`;
});
// Inject data-ref attributes into iframe interactive elements with continuing refs
const refLines = [];
const allInteractive = [...document.querySelectorAll('a, button, input, select, textarea, [role="button"], [role="link"], [role="textbox"], [role="combobox"], [role="checkbox"], [role="radio"], [role="tab"], [role="menuitem"], [role="option"], [contenteditable]')].filter(el => {
if (el.offsetParent !== null) return true;
if (el.type === 'hidden') return false;
const s = window.getComputedStyle(el);
if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false;
if (s.position === 'fixed' || s.position === 'sticky') return true;
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
let refIdx = startRef;
for (const el of allInteractive) {
el.setAttribute('data-ref', String(refIdx));
const tag = el.tagName.toLowerCase();
const type = el.type || '';
const name = el.name || el.id || '';
const placeholder = el.placeholder || '';
const value = el.value || '';
const text2 = (el.textContent || '').trim().substring(0, 80);
const href = el.href || '';
const role = el.getAttribute('role') || '';
const ariaLabel = el.getAttribute('aria-label') || '';
let desc = `[ref=${refIdx}] <${tag}`;
if (type) desc += ` type="${type}"`;
if (name) desc += ` name="${name}"`;
if (role) desc += ` role="${role}"`;
if (ariaLabel) desc += ` aria-label="${ariaLabel}"`;
if (placeholder) desc += ` placeholder="${placeholder}"`;
if (value && type !== 'password') desc += ` value="${value.substring(0, 50)}"`;
if (href) desc += ` href="${href.substring(0, 150)}"`;
desc += '>';
if (text2 && type !== 'password' && tag !== 'input') desc += ` ${text2}`;
if (tag === 'select') desc += ' [SELECT]';
refLines.push(desc);
refIdx++;
}
return { text, interactive, refLines, nextRef: refIdx };
}, nextRef);
// Store ref→frame mapping for each iframe element
for (let r = nextRef; r < frameBody.nextRef; r++) {
this._refFrameMap.set(r, frame);
this._refGenMap.set(r, this._snapshotGen);
}
nextRef = frameBody.nextRef;
if (frameBody.refLines.length > 0) {
iframeElementLines.push(...frameBody.refLines);
}
if (frameBody.text.length > 0 || frameBody.interactive.length > 0) {
const parts = [];
if (frameBody.interactive.length > 0) {
parts.push(`Interactive elements in this frame:\n${frameBody.interactive.join('\n')}`);
}
if (frameBody.text.length > 0) {
parts.push(`Frame text:\n${frameBody.text.substring(0, 15000)}`);
}
// PL3: Check if cross-origin frame content is scrollable
let scrollNote = '';
try {
const scrollH = await frame.evaluate(() => document.body?.scrollHeight || 0);
const clientH = await frame.evaluate(() => document.body?.clientHeight || 0);
if (scrollH > clientH) {
const pct = Math.round((clientH / scrollH) * 100);
scrollNote = `, scrollable: ${pct}% visible — use browser_scroll to see more`;
}
} catch {}
frameTexts.push(`--- iframe content (src="${frameUrl.substring(0, 120)}"${scrollNote}) ---\n${parts.join('\n\n')}`);
}
} catch (e) {
// Frame may be detached or inaccessible
if (frameUrl) frameTexts.push(`--- iframe (could not access content, src="${frameUrl.substring(0, 120)}") ---`);
}
}
} catch {}
// Merge iframe element lines into the main element list
const fullElementList = iframeElementLines.length > 0
? snapshotData.elementList + '\n' + iframeElementLines.join('\n')
: snapshotData.elementList;
const fullPageText = frameTexts.length > 0
? snapshotData.pageText + '\n\n' + frameTexts.join('\n\n')
: snapshotData.pageText;
// Navigation history at TOP of snapshot — model reads top-down and needs
// to see what it already did BEFORE choosing the next element to click.
let historySection = '';
if (this._navHistory.length > 0) {
const recentHistory = this._navHistory.slice(-8);
historySection = `Navigation history (DO NOT repeat these — move to NEXT step):\n`
+ recentHistory.map((h, i) => `${i + 1}. ${h.action}: ${h.url}${h.title ? ` (${h.title})` : ''}`).join('\n')
+ '\n\n';
}
// PL1: Compress page text — deduplicate, trim line width, collapse blanks.
// Preserves ALL unique content (assignments, due dates, etc.) while removing
// visual noise that wastes context (repeated progress indicators, decorative spacing).
const _compressPageText = (text) => {
if (!text) return '';
const seen = new Set();
const lines = text.split('\n');
const out = [];
let prevBlank = false;
for (const raw of lines) {
const line = raw.trim();
if (!line) { if (!prevBlank) { out.push(''); prevBlank = true; } continue; }
prevBlank = false;
if (seen.has(line)) continue;
seen.add(line);
out.push(line.length > 200 ? line.substring(0, 200) + '…' : line);
}
return out.join('\n');
};
const compressedPageText = _compressPageText(fullPageText);
const result = `${historySection}Page: ${title}\nURL: ${url}\n\nInteractive elements (use the [ref=N] number as the "ref" param, e.g. {"ref":"2"} or {"ref":"[ref=2]"}):\n${fullElementList}\n\nPage text:\n${compressedPageText}`;
this._lastSnapshotUrl = url;
this._lastSnapshotTime = Date.now();
// No total cap — the model needs the full snapshot to make correct decisions.
// Truncation was the root cause of repeated wrong clicks (elements below the fold invisible).
console.log(`[BrowserManager] getSnapshot DONE: elementCount=${fullElementList?.split('\n')?.length || 0}, textLen=${fullPageText?.length || 0}`);
return { success: true, title, url, text: result };
} catch (e) {
console.error(`[BrowserManager] getSnapshot ERROR: ${e.message}`);
return { success: false, error: e.message };
}
}
/**
* Resolve a ref string (e.g. "[ref=1]", "1", or CSS selector) to a valid Playwright selector.
* Accessibility snapshots use [ref=N] format — we convert to [aria-ref="N"] or
* fall back to nth-child indexing.
*/
_resolveRef(ref) {
if (!ref || typeof ref !== 'string' || !ref.trim()) {
return null;
}
const trimmed = ref.trim();
// ─── All known ref formats that models output after seeing [ref=N] in snapshots ───
// Every format resolves to [data-ref="N"] or [aria-ref="N"] which maps to the
// data-ref attribute injected by _ensureRefs(). If a format isn't recognized,
// it falls through to CSS selector validation below.
// [ref=N] — exact format from snapshot output
let m = trimmed.match(/^\[ref\s*=\s*(\d+)\]$/);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
// [ref="N"] or [ref='N'] — quoted value variant
m = trimmed.match(/^\[ref\s*=\s*["'](\d+)["']\]$/);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
// [N] — bare bracket number (most common model drift from [ref=N])
m = trimmed.match(/^\[(\d+)\]$/);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
// ref=N — without brackets
m = trimmed.match(/^ref=(\d+)$/);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
// element[N] — some models wrap in "element"
m = trimmed.match(/^element\[(\d+)\]$/i);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
// #ref-N or #N — hash-prefixed
m = trimmed.match(/^#ref-(\d+)$/i);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
m = trimmed.match(/^#(\d+)$/);
if (m) return `[data-ref="${m[1]}"], [aria-ref="${m[1]}"]`;
// Bare number like "2"
if (/^\d+$/.test(trimmed)) {
return `[data-ref="${trimmed}"], [aria-ref="${trimmed}"]`;
}
// Non-numeric identifier like "username" — resolve as name/id/placeholder
if (/^[a-zA-Z_][a-zA-Z0-9_\-]*$/.test(trimmed)) {
return `[name="${trimmed}"], [id="${trimmed}"], [data-ref="${trimmed}"], [placeholder="${trimmed}"]`;
}
// ─── Fallback: treat as CSS selector, but validate first ───
// If the selector is not valid CSS, returning it as-is causes querySelectorAll
// syntax errors that the model cannot recover from, creating infinite loops.
// We can't use document.querySelector in Node.js, so check for known-invalid patterns.
// Valid CSS selectors: .class, #id, tag, [attr=val], :pseudo, tag.class, tag > child, etc.
// Invalid: //xpath, >>> combinator, bare [N] (handled above), unbalanced brackets, etc.
if (trimmed.startsWith('//') || trimmed.startsWith('..')) {
// XPath — not supported by Playwright's CSS selector engine
return null;
}
if (trimmed.includes('>>>')) {
// Deprecated deep pierce combinator — not valid
return null;
}
// Check for unbalanced brackets (e.g. "[2" or "ref=2]" without matching pair)
const opens = (trimmed.match(/\[/g) || []).length;
const closes = (trimmed.match(/\]/g) || []).length;
if (opens !== closes) {
return null;
}
// Check for unbalanced quotes
const singleQuotes = (trimmed.match(/'/g) || []).length;
const doubleQuotes = (trimmed.match(/"/g) || []).length;
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
return null;
}
// Looks like a valid CSS selector — pass through.
// Playwright's try/catch in the calling method will handle any remaining edge cases
// and the error message will be caught and returned to the model.
return ref;
}
/**
* PL7: Check if a ref string belongs to a previous snapshot generation (stale ref).
* Returns an error string if stale, null if fresh or untrackable.
* Prevents the model from clicking elements that no longer exist after navigation.
*/
_isStaleRef(ref) {
if (!ref || typeof ref !== 'string') return null;
const trimmed = ref.trim();
// Extract numeric ref from any known format
const m = trimmed.match(/(?:ref\s*=\s*|\[|^)(\d+)(?:\]|$)/) || (/^(\d+)$/.test(trimmed) && [null, trimmed]);
if (!m) return null; // Non-numeric ref (e.g., CSS selector) — can't track
const numRef = parseInt(m[1]);
if (!this._refGenMap.has(numRef)) return null; // Ref not in map — might be from a page without snapshot
if (this._refGenMap.get(numRef) !== this._snapshotGen) {
return `Stale ref [ref=${numRef}] — this element was from a previous page. The page has changed since then. Call browser_snapshot to get fresh element refs before clicking.`;
}
return null; // Fresh ref
}
/**
* Extract the numeric ref from a selector string (e.g. "[ref=5]" → 5, "3" → 3).
* Returns null if the selector is not a ref-based selector.
*/
_extractRefNumber(selector) {
if (!selector || typeof selector !== 'string') return null;
const trimmed = selector.trim();
let m = trimmed.match(/^\[ref\s*=\s*(\d+)\]$/);
if (m) return parseInt(m[1]);
m = trimmed.match(/^\[(\d+)\]$/);
if (m) return parseInt(m[1]);
m = trimmed.match(/^ref=(\d+)$/);
if (m) return parseInt(m[1]);
if (/^\d+$/.test(trimmed)) return parseInt(trimmed);
return null;
}
async click(selector) {
console.log(`[BrowserManager] click START: selector=${selector}`);
if (!(await this._ensurePage())) {
console.warn('[BrowserManager] click: no page');
return { success: false, error: 'No browser page open' };
}
// Re-inject data-ref attrs before resolving — they're lost on page navigation/reload
await this._ensureRefs();
// If this ref maps to a child frame, click directly in that frame.
// This replaces the blind frame iteration fallback that mismatched element indices.
const refNum = this._extractRefNumber(selector);
if (refNum !== null && this._refFrameMap.has(refNum)) {
// PL7: Stale-ref check for iframe refs too
const staleErr = this._isStaleRef(selector);
if (staleErr) return { success: false, error: staleErr };
const targetFrame = this._refFrameMap.get(refNum);
// Verify the frame is still attached — after navigation, child frames
// may be detached and using a stale frame reference throws.
const currentFrames = this._page.frames();
if (!currentFrames.includes(targetFrame)) {
this._refFrameMap.delete(refNum);
// Fall through to main page click logic
} else {
const refSelector = `[data-ref="${refNum}"]`;
if (targetFrame !== this._page.mainFrame()) {
// Element is in a child frame — click directly there
try {
const urlBefore = this._page.url();
let clickedText = '';
try {
clickedText = await targetFrame.evaluate((sel) => {
const el = document.querySelector(sel);
return el ? (el.textContent || '').trim().substring(0, 60) : '';
}, refSelector);
} catch {}
await targetFrame.click(refSelector, { timeout: 5000 });
try { await this._page.waitForTimeout(800); } catch {}
const urlAfter = this._page.url();
const navigated = urlAfter !== urlBefore;
const snapshot = await this.getSnapshot();
const pageState = navigated
? 'PAGE NAVIGATED — you are now on a new page. Call browser_snapshot to see the new page before taking any action.'
: 'SAME PAGE — the click succeeded but the URL did not change. The page may have updated (dialog opened, content changed, etc.). Use the snapshot below to see what changed.';
console.log(`[BrowserManager] Clicked ref=${refNum} in child frame directly`);
if (snapshot.success) {
return { success: true, url: urlAfter, clicked: clickedText || selector, navigated, pageState, snapshot: snapshot.text };
}
return { success: true, url: urlAfter, clicked: clickedText || selector, navigated, pageState };
} catch (frameErr) {
console.warn(`[BrowserManager] Direct frame click failed for ref=${refNum}: ${frameErr.message}`);
// Fall through to main page click logic below
}
}
}
}
// PL7: Stale-ref detection — reject refs from previous page snapshots
const staleErr = this._isStaleRef(selector);
if (staleErr) return { success: false, error: staleErr };
const resolved = this._resolveRef(selector);
if (!resolved) {
return { success: false, error: `Invalid element ref "${selector}". Use the [ref=N] number from the snapshot, e.g. browser_click({"ref":"5"}). Call browser_snapshot first if you need fresh refs.` };
}
try {
const urlBefore = this._page.url();
// PL5: Lightweight DOM fingerprint before click — detects same-URL content changes
let fingerprintBefore = '';
try { fingerprintBefore = await this._page.evaluate(() => {
const els = document.querySelectorAll('a, button, [role="tab"], [role="menuitem"]');
return `${els.length}:${(document.body?.innerText || '').substring(0, 200)}`;
}); } catch {}
// Get the element text before clicking — include title/alt for image-only links
let clickedText = '';
try {
const loc = this._page.locator(resolved).first();
clickedText = await loc.textContent({ timeout: 2000 }).then(t => t?.trim()?.substring(0, 60) || '');
if (!clickedText) {
// Image-only link — get title attribute or child img alt
clickedText = await loc.getAttribute('title', { timeout: 1000 }).then(t => t || '') ||
await loc.locator('img').first().getAttribute('alt', { timeout: 1000 }).then(t => t || '') || '';
}
} catch {}
// Listen for new tab/popup BEFORE clicking — target=_blank links open new tabs
// which don't change the current page URL, causing the model to think the click failed
const popupPromise = this._page.waitForEvent('popup', { timeout: 5000 }).catch(() => null);
await this._page.click(resolved, { timeout: 5000 });
const newPage = await popupPromise;
if (newPage) {
// A popup event fired — but it may be a false positive from SAML redirects
// or JavaScript that briefly opens/closes a window. Wait for the popup to
// settle, then decide which page to keep based on which one has a real URL.
try {
await newPage.waitForURL(url => url !== 'about:blank' && url !== '', { timeout: 10000 }).catch(() => {});
await newPage.waitForLoadState('domcontentloaded', { timeout: 8000 }).catch(() => {});
} catch {}
// Check popup state: is it alive AND does it have a real URL?
// B15: Use isClosed() instead of evaluate(() => true) — evaluate() throws
// during navigation when the execution context is being destroyed/recreated
// (e.g., SAML redirects), falsely marking a live page as dead.
let popupAlive = !newPage.isClosed();
let popupUrl = '';
try {
popupUrl = newPage.url();
} catch {
popupAlive = false;
}
if (!popupAlive) {
console.warn('[BrowserManager] Popup closed unexpectedly, keeping original page');
}
// Also check if the original page navigated (SAML redirects may complete
// in the original tab even though a popup event fired).
let originalAlive = !this._page.isClosed();
let originalUrl = '';
try {
originalUrl = this._page.url();
} catch {
originalAlive = false;
}
const popupHasRealUrl = popupAlive && popupUrl && popupUrl !== 'about:blank' && popupUrl !== '';
const originalHasRealUrl = originalAlive && originalUrl && originalUrl !== 'about:blank' && originalUrl !== '' && originalUrl !== urlBefore;
// Decision logic: prefer the page that actually navigated to a real URL.
// If both have real URLs, prefer the popup (intentional new tab).
// If neither has a real URL, keep the original (avoids about:blank death spiral).
let activePage;
let switchedToPopup = false;
if (popupHasRealUrl && originalHasRealUrl) {
// Both navigated — prefer popup (likely intentional target=_blank)
activePage = newPage;
switchedToPopup = true;
} else if (popupHasRealUrl && !originalHasRealUrl) {
// Only popup has real URL — use it
activePage = newPage;
switchedToPopup = true;
} else if (!popupHasRealUrl && originalHasRealUrl) {
// Only original navigated — popup was a false positive (SAML redirect artifact)
console.warn('[BrowserManager] Popup has no real URL but original page navigated — keeping original page (popup was false positive)');
activePage = this._page;
try { await newPage.close(); } catch {} // close the useless popup
} else {
// Neither has a real URL — keep original, close popup
console.warn('[BrowserManager] Neither popup nor original page has a real URL — keeping original page');
activePage = this._page;
try { await newPage.close(); } catch {}
}
// Close the page we're NOT keeping
if (switchedToPopup && originalAlive) {
try { await this._page.close(); } catch {}
}
this._page = activePage;
// Wait for the active page to fully load before snapshotting.
try { await this._page.waitForLoadState('networkidle', { timeout: 8000 }).catch(() => {}); } catch {}
try { await this._page.waitForTimeout(1000); } catch {}
const snapshot = await this.getSnapshot();
// B13: navigated must reflect actual URL change, not just popup event.
// When neither popup nor original has a real URL, the page didn't navigate.
const navigated = this._page.url() !== urlBefore;
// PL6: Include previous URL in popup result so model knows where it came from
const pageState = navigated
? `PAGE NAVIGATED — you switched to a new tab/page. Previous page was: ${urlBefore}. You are now on: ${this._page.url()}. The snapshot below shows the new page.`
: 'SAME PAGE — the click triggered a popup that failed to navigate. The URL did not change. Try a different approach (e.g., navigate directly to the target URL instead of clicking this element).';
if (snapshot.success) {
return { success: true, url: this._page.url(), clicked: clickedText || selector, navigated, newTab: switchedToPopup, previousUrl: urlBefore, pageState, snapshot: snapshot.text };
}
return { success: true, url: this._page.url(), clicked: clickedText || selector, navigated, newTab: switchedToPopup, previousUrl: urlBefore, pageState };
}
// No new tab — check if same-page navigation happened
// PL4: Extra wait for dropdown menus that animate open
try { await this._page.waitForTimeout(800); } catch {}
try { await this._page.waitForTimeout(500); } catch {}
const urlAfter = this._page.url();
const navigated = urlAfter !== urlBefore;
if (navigated) {
try { await this._page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {}); } catch {}
}
// Always snapshot so model sees DOM changes
const snapshot = await this.getSnapshot();
// PL4+PL5: Clear page state messaging — tell the model exactly what happened
// so it doesn't guess or retry the same action blindly
let pageState;
if (navigated) {
pageState = 'PAGE NAVIGATED — you are now on a new page. Call browser_snapshot to see the new page before taking any action.';
} else {
// PL5: Compare DOM fingerprints to detect same-URL content changes
let contentChanged = false;
try {
const fingerprintAfter = await this._page.evaluate(() => {
const els = document.querySelectorAll('a, button, [role="tab"], [role="menuitem"]');
return `${els.length}:${(document.body?.innerText || '').substring(0, 200)}`;
});
contentChanged = fingerprintBefore !== fingerprintAfter;
} catch {}
// PL4: Check if dropdown menuitems appeared
const hasMenuItems = snapshot.success && snapshot.text?.includes('role="menuitem"');
if (hasMenuItems) {
pageState = 'SAME PAGE — a dropdown menu opened. Menu items are visible in the snapshot below. Click one directly using its ref number.';
} else if (contentChanged) {
pageState = 'SAME URL but page content changed (tab switch, content update). The snapshot below shows the updated page.';
} else {
pageState = 'SAME PAGE — the click succeeded but the URL and content did not change. The click may not have had the intended effect. Try a different element or action.';
}
}
if (snapshot.success) {
console.log(`[BrowserManager] click DONE: success, url=${urlAfter}, navigated=${navigated}`);
return { success: true, url: urlAfter, clicked: clickedText || selector, navigated, pageState, snapshot: snapshot.text };
}
console.log(`[BrowserManager] click DONE: success (no snapshot), url=${urlAfter}, navigated=${navigated}`);
return { success: true, url: urlAfter, clicked: clickedText || selector, navigated, pageState };
} catch (e) {
console.error(`[BrowserManager] click ERROR: ${e.message}`);
// If ref-based selector failed on main page, try finding the element in child frames.
// Some sites render interactive content inside cross-origin iframes.
// Playwright's page.frames() can access all frames regardless of origin.
const refMatch = selector?.match?.(/^\[ref\s*=\s*(\d+)\]$/) || selector?.match?.(/^\[(\d+)\]$/) || (typeof selector === 'string' && /^\d+$/.test(selector.trim()) && [null, selector.trim()]);
if (refMatch) {
// First try JS click fallback on main page (existing logic)
try {
const idx = parseInt(refMatch[1]);
const result = await this._page.evaluate((i) => {
const selectors = [
'input', 'button', 'a', 'select', 'textarea',
'[role="button"]', '[role="link"]', '[role="textbox"]',
'[role="combobox"]', '[role="checkbox"]', '[role="radio"]',
'[role="tab"]', '[role="menuitem"]', '[role="option"]',
'[contenteditable]', 'summary', 'details',
'iframe', 'form',
];
const all = [...document.querySelectorAll(selectors.join(','))].filter(el => {
if (el.offsetParent !== null) return true;
if (el.type === 'hidden') return false;
const s = window.getComputedStyle(el);
if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false;
if (s.position === 'fixed' || s.position === 'sticky') return true;
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (all[i]) { const txt = (all[i].textContent || '').trim().substring(0, 60); all[i].click(); return { success: true, clicked: txt || `element[${i}]` }; }
return { success: false, error: `No interactive element at index ${i} (found ${all.length} visible elements)` };
}, idx);
if (result.success) {
try { await this._page.waitForTimeout(800); } catch {}
const snapshot = await this.getSnapshot();
if (snapshot.success) return { success: true, url: this._page.url(), snapshot: snapshot.text };
}
if (result.success) return result;
} catch (_) {}
// Main page click failed — try clicking in child frames
try {
const frames = this._page.frames();
for (const frame of frames) {
if (frame === this._page.mainFrame()) continue; // already tried
try {
const frameResult = await frame.evaluate((i) => {
const selectors = [
'input', 'button', 'a', 'select', 'textarea',
'[role="button"]', '[role="link"]', '[role="textbox"]',
'[role="combobox"]', '[role="checkbox"]', '[role="radio"]',
'[role="tab"]', '[role="menuitem"]', '[role="option"]',
'[contenteditable]', 'summary', 'details',
];
const all = [...document.querySelectorAll(selectors.join(','))].filter(el => {
if (el.offsetParent !== null) return true;
if (el.type === 'hidden') return false;
const s = window.getComputedStyle(el);
if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false;
if (s.position === 'fixed' || s.position === 'sticky') return true;
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
if (all[i]) { const txt = (all[i].textContent || '').trim().substring(0, 60); all[i].click(); return { success: true, clicked: txt || `frame-element[${i}]`, frameUrl: location.href }; }
return null;
}, parseInt(refMatch[1]));
if (frameResult?.success) {
console.log(`[BrowserManager] Clicked element in frame: ${frameResult.frameUrl}`);
try { await this._page.waitForTimeout(800); } catch {}
const snapshot = await this.getSnapshot();
return { success: true, url: this._page.url(), clicked: frameResult.clicked, navigated: false, snapshot: snapshot.success ? snapshot.text : undefined };
}
} catch (_) { /* frame not accessible */ }
}
} catch (_) {}
}
return { success: false, error: e.message };
}
}