Repository navigation
Expand file tree
/
Copy pathbrowser-server.js
More file actions
1479 lines (1273 loc) · 47.9 KB
/
Copy pathbrowser-server.js
File metadata and controls
1479 lines (1273 loc) · 47.9 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
/**
* Browser Manager Server - Runs on Node.js to manage Chromium profiles
* Spawned by main OpenCode (Bun) process
*/
import { chromium } from "playwright"
import http from "http"
import { URL } from "url"
let browser = null
let context = null
let currentPage = null
let pages = [] // Track all pages for tab management
let consoleMessages = []
let networkRequests = []
let fileChooserPromise = null
let dialogPromise = null
let cursorPosition = { x: 0, y: 0 }
const PORT = process.env.BROWSER_MANAGER_PORT || 9999
/**
* Inject cursor overlay script into the page
*/
const CURSOR_OVERLAY_SCRIPT = `
(function() {
if (window.__opencodeCursorInitialized) return;
window.__opencodeCursorInitialized = true;
// Create cursor element with high visibility
const cursor = document.createElement('div');
cursor.id = '__opencode-cursor';
cursor.style.cssText = \`
position: fixed;
width: 20px;
height: 20px;
border-radius: 50%;
background: radial-gradient(circle, #ff0000 0%, #cc0000 40%, #ff0000 70%, transparent 100%);
border: 3px solid #0000ff;
box-shadow: 0 0 10px #ff0000, 0 0 20px #ff0000, inset 0 0 5px rgba(255,255,255,0.6);
pointer-events: none;
z-index: 2147483647;
transform: translate(-50%, -50%);
transition: none;
display: block;
opacity: 1;
\`;
// Create click effect element
const clickEffect = document.createElement('div');
clickEffect.id = '__opencode-click-effect';
clickEffect.style.cssText = \`
position: fixed;
width: 40px;
height: 40px;
border-radius: 50%;
border: 2px solid rgba(59, 130, 246, 0.8);
pointer-events: none;
z-index: 2147483646;
transform: translate(-50%, -50%) scale(0);
opacity: 0;
display: none;
\`;
document.body.appendChild(cursor);
document.body.appendChild(clickEffect);
// Store in window for access
window.__opencodeCursor = {
element: cursor,
clickEffect: clickEffect,
position: { x: 0, y: 0 },
visible: true,
moveTo(x, y, animate = false) {
this.position = { x, y };
if (animate) {
cursor.style.transition = 'left 0.3s ease-out, top 0.3s ease-out';
} else {
cursor.style.transition = 'none';
}
cursor.style.left = x + 'px';
cursor.style.top = y + 'px';
},
animateTo(fromX, fromY, toX, toY, duration = 300) {
return new Promise((resolve) => {
const steps = 20;
const dx = (toX - fromX) / steps;
const dy = (toY - fromY) / steps;
let step = 0;
const interval = setInterval(() => {
step++;
const x = fromX + dx * step;
const y = fromY + dy * step;
cursor.style.left = x + 'px';
cursor.style.top = y + 'px';
this.position = { x, y };
if (step >= steps) {
clearInterval(interval);
resolve();
}
}, duration / steps);
});
},
showClickEffect(x, y) {
clickEffect.style.display = 'block';
clickEffect.style.left = x + 'px';
clickEffect.style.top = y + 'px';
clickEffect.style.transform = 'translate(-50%, -50%) scale(0)';
clickEffect.style.opacity = '1';
// Animate
requestAnimationFrame(() => {
clickEffect.style.transition = 'transform 0.3s ease-out, opacity 0.3s ease-out';
clickEffect.style.transform = 'translate(-50%, -50%) scale(1.5)';
clickEffect.style.opacity = '0';
});
setTimeout(() => {
clickEffect.style.display = 'none';
}, 300);
},
show() {
cursor.style.display = 'block';
this.visible = true;
},
hide() {
cursor.style.display = 'none';
this.visible = false;
},
setDragging(isDragging) {
if (isDragging) {
cursor.style.background = 'radial-gradient(circle, rgba(239, 68, 68, 0.9) 0%, rgba(239, 68, 68, 0.4) 50%, transparent 70%)';
cursor.style.boxShadow = '0 0 10px rgba(239, 68, 68, 0.8), 0 0 20px rgba(239, 68, 68, 0.4)';
} else {
cursor.style.background = 'radial-gradient(circle, rgba(59, 130, 246, 0.9) 0%, rgba(59, 130, 246, 0.4) 50%, transparent 70%)';
cursor.style.boxShadow = '0 0 10px rgba(59, 130, 246, 0.8), 0 0 20px rgba(59, 130, 246, 0.4)';
}
}
};
// Position cursor initially off-screen
cursor.style.left = '-100px';
cursor.style.top = '-100px';
})();
`
// Simple HTTP server for browser commands
const server = http.createServer(async (req, res) => {
res.setHeader("Content-Type", "application/json")
try {
const url = new URL(req.url, `http://localhost:${PORT}`)
const pathname = url.pathname
// Health check
if (pathname === "/health") {
res.writeHead(200)
res.end(JSON.stringify({ status: "ok" }))
return
}
if (pathname === "/init") {
const headed = url.searchParams.get("headed") === "true"
if (!browser) {
console.log("[browser-server] Launching Chromium...")
browser = await chromium.launch({
headless: !headed,
timeout: 30000,
})
console.log("[browser-server] Chromium launched")
}
if (!context) {
context = await browser.newContext({
viewport: { width: 1280, height: 720 },
})
console.log("[browser-server] Context created")
}
if (!currentPage) {
currentPage = await context.newPage()
pages.push(currentPage)
console.log("[browser-server] Page created")
// Set up console message listener
currentPage.on("console", (msg) => {
consoleMessages.push({
level: msg.type(),
text: msg.text(),
timestamp: Date.now(),
})
// Keep only last 100 messages
if (consoleMessages.length > 100) {
consoleMessages.shift()
}
})
// Set up network request listener
currentPage.on("response", (response) => {
const request = response.request()
networkRequests.push({
url: request.url(),
method: request.method(),
status: response.status(),
type: request.resourceType(),
})
// Keep only last 200 requests
if (networkRequests.length > 200) {
networkRequests.shift()
}
})
// Set up dialog handler
currentPage.on("dialog", async (dialog) => {
if (dialogPromise) {
const { accept, promptText, resolve } = dialogPromise
if (accept) {
await dialog.accept(promptText || undefined)
} else {
await dialog.dismiss()
}
resolve({ success: true })
dialogPromise = null
} else {
// Auto-dismiss if no handler waiting
await dialog.dismiss()
}
})
// Set up file chooser handler
currentPage.on("filechooser", async (chooser) => {
if (fileChooserPromise) {
const { paths, resolve } = fileChooserPromise
if (paths && paths.length > 0) {
await chooser.setFiles(paths)
}
resolve({ success: true })
fileChooserPromise = null
}
})
// Inject cursor overlay
await currentPage.addInitScript(CURSOR_OVERLAY_SCRIPT)
}
res.writeHead(200)
res.end(JSON.stringify({ success: true, message: "Browser initialized" }))
return
}
if (!currentPage) {
res.writeHead(400)
res.end(JSON.stringify({ error: "Browser not initialized" }))
return
}
if (pathname === "/navigate") {
const urlStr = url.searchParams.get("url")
const waitUntil = url.searchParams.get("waitUntil") || "domcontentloaded"
if (!urlStr) {
res.writeHead(400)
res.end(JSON.stringify({ error: "URL is required" }))
return
}
console.log("[browser-server] Navigating to:", urlStr)
try {
await currentPage.goto(urlStr, { waitUntil, timeout: 60000 })
} catch (navError) {
console.error("[browser-server] Navigation error:", navError.message)
// Continue even if navigation fails - page might be partially loaded
}
const pageInfo = await getPageInfo()
res.writeHead(200)
res.end(JSON.stringify(pageInfo))
return
}
if (pathname === "/pageInfo") {
try {
const pageInfo = await getPageInfo()
res.writeHead(200)
res.end(JSON.stringify(pageInfo))
} catch (err) {
console.error("[browser-server] pageInfo error:", err.message)
res.writeHead(200)
res.end(JSON.stringify({ url: "", title: "", viewport: { width: 1280, height: 720 }, scroll: { x: 0, y: 0 } }))
}
return
}
if (pathname === "/screenshot") {
const fullPage = url.searchParams.get("fullPage") === "true"
console.log("[browser-server] Taking screenshot")
const buffer = await currentPage.screenshot({ fullPage })
res.writeHead(200, { "Content-Type": "image/png" })
res.end(buffer)
return
}
if (pathname === "/click") {
const selector = (url.searchParams.get("selector") || "").trim()
const rawX = url.searchParams.get("x")
const rawY = url.searchParams.get("y")
const button = url.searchParams.get("button") || "left"
const clickCount = parseInt(url.searchParams.get("clickCount") || "1", 10)
const timeout = parseInt(url.searchParams.get("timeout") || "30000", 10)
try {
if (selector) {
const locator = currentPage.locator(selector).first()
try {
// Scroll element into view first if not visible
await locator.scrollIntoViewIfNeeded()
await locator.waitFor({ state: "visible", timeout })
} catch (waitErr) {
throw new Error("Element not found or not visible")
}
await locator.click({ button, clickCount, timeout })
} else {
if (rawX === null || rawY === null) {
throw new Error("Selector or coordinates required")
}
const x = Number(rawX)
const y = Number(rawY)
if (!Number.isFinite(x) || !Number.isFinite(y)) {
throw new Error("Invalid coordinates")
}
await currentPage.mouse.click(x, y, { button, clickCount })
}
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (clickError) {
console.error("[browser-server] Click error:", clickError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: clickError.message }))
}
return
}
if (pathname === "/type") {
const selector = url.searchParams.get("selector")
const text = url.searchParams.get("text") || ""
const clear = url.searchParams.get("clear") === "true"
const pressEnter = url.searchParams.get("pressEnter") === "true"
const delay = parseInt(url.searchParams.get("delay") || "50", 10)
const timeout = parseInt(url.searchParams.get("timeout") || "30000", 10)
console.log("[browser-server] Typing in", selector)
try {
if (!selector) throw new Error("Selector is required")
const locator = currentPage.locator(selector).first()
// Ensure the element is attached/visible
try {
await locator.waitFor({ state: "visible", timeout })
} catch (waitErr) {
throw new Error("Element not found or not visible")
}
if (clear) await locator.fill("")
if (typeof locator.type === "function") {
await locator.type(text, { delay })
} else {
// Fallback to keyboard typing
await locator.focus()
await currentPage.keyboard.type(text, { delay })
}
if (pressEnter) await locator.press("Enter")
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (typeError) {
console.error("[browser-server] Type error:", typeError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: typeError.message }))
}
return
}
if (pathname === "/scroll") {
const direction = url.searchParams.get("direction") || "down"
const amount = parseInt(url.searchParams.get("amount") || "500", 10)
const toElement = url.searchParams.get("toElement")
console.log("[browser-server] Scrolling", direction)
if (toElement) {
await currentPage.locator(toElement).first().scrollIntoViewIfNeeded()
} else {
await currentPage.evaluate(
({ dir, amt }) => {
const scrollAmount = amt
switch (dir) {
case "up":
window.scrollBy(0, -scrollAmount)
break
case "down":
window.scrollBy(0, scrollAmount)
break
case "left":
window.scrollBy(-scrollAmount, 0)
break
case "right":
window.scrollBy(scrollAmount, 0)
break
}
},
{ dir: direction, amt: amount },
)
}
const scrollPos = await currentPage.evaluate(() => ({ x: window.scrollX, y: window.scrollY }))
res.writeHead(200)
res.end(JSON.stringify(scrollPos))
return
}
if (pathname === "/wait") {
const loadState = url.searchParams.get("loadState") || "domcontentloaded"
const selector = url.searchParams.get("selector")
const timeout = parseInt(url.searchParams.get("timeout") || "30000", 10)
console.log("[browser-server] Waiting for", selector || loadState)
if (selector) {
await currentPage.locator(selector).first().waitFor({ timeout })
} else {
await currentPage.waitForLoadState(loadState, { timeout })
}
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
return
}
if (pathname === "/content") {
const format = url.searchParams.get("format") || "text"
const selector = url.searchParams.get("selector")
console.log("[browser-server] Getting content", format)
let text = ""
let html = ""
try {
if (selector) {
const locator = currentPage.locator(selector).first()
text = (await locator.textContent().catch(() => "")) || ""
html = (await locator.innerHTML().catch(() => "")) || ""
} else {
// For full page text, extract only visible, readable content
text = await currentPage
.evaluate(() => {
// Get text only from visible leaf elements (not parents with children)
const textContent = []
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false)
let node
while ((node = walker.nextNode())) {
const text = node.textContent?.trim()
// Only include non-empty text that's not from script/style elements
if (text && text.length > 0 && text.length < 500) {
const parent = node.parentElement
const tag = parent?.tagName.toLowerCase()
// Skip script, style, noscript, and empty containers
if (!["script", "style", "noscript", "meta", "link"].includes(tag)) {
textContent.push(text)
}
}
}
// Deduplicate and clean
return [...new Set(textContent)].join(" ").replace(/\s+/g, " ").slice(0, 5000).trim()
})
.catch(() => "")
html = (await currentPage.content().catch(() => "")) || ""
}
} catch (contentError) {
console.error("[browser-server] Content error:", contentError.message)
}
res.writeHead(200)
res.end(JSON.stringify({ text, html }))
return
}
if (pathname === "/elements") {
const type = url.searchParams.get("type") || "all"
console.log("[browser-server] Getting interactive elements")
const elements = await currentPage.evaluate((elementType) => {
const result = []
let index = 0
const selectors =
elementType === "input"
? "input, textarea, select, [contenteditable=true]"
: elementType === "clickable"
? "a, button, [role=button], [onclick], input[type=submit], input[type=button]"
: "a, button, input, textarea, select, [role=button], [onclick], [contenteditable=true]"
document.querySelectorAll(selectors).forEach((el) => {
const rect = el.getBoundingClientRect()
// Check if visible
const style = window.getComputedStyle(el)
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.opacity === "0" ||
el.offsetParent === null
) {
return
}
// Generate selector
let selector = el.id ? `#${el.id}` : el.tagName.toLowerCase()
try {
selector = el.tagName.toLowerCase()
if (el.id) selector = `#${el.id}`
} catch {}
result.push({
index: index++,
tagName: el.tagName.toLowerCase(),
selector,
text: (el.innerText || el.value || "").slice(0, 50),
type: el.type,
placeholder: el.placeholder,
ariaLabel: el.getAttribute("aria-label") || "",
textContent: (el.innerText || "").slice(0, 100),
bounds: {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
},
isVisible: true,
isClickable: true,
isInput: ["input", "textarea", "select"].includes(el.tagName.toLowerCase()),
})
})
return result
}, type)
res.writeHead(200)
res.end(JSON.stringify(elements))
return
}
// Hover endpoint
if (pathname === "/hover") {
const selector = url.searchParams.get("selector")
const x = url.searchParams.get("x")
const y = url.searchParams.get("y")
const timeout = parseInt(url.searchParams.get("timeout") || "30000", 10)
console.log("[browser-server] Hovering", selector || `(${x}, ${y})`)
try {
if (selector) {
const locator = currentPage.locator(selector).first()
await locator.waitFor({ state: "visible", timeout })
await locator.hover()
// Get element center for cursor animation
const box = await locator.boundingBox()
if (box) {
cursorPosition = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
await currentPage.evaluate(({ x, y }) => {
if (window.__opencodeCursor) {
window.__opencodeCursor.moveTo(x, y, true)
}
}, cursorPosition)
}
} else if (x && y) {
await currentPage.mouse.move(parseFloat(x), parseFloat(y))
cursorPosition = { x: parseFloat(x), y: parseFloat(y) }
await currentPage.evaluate(({ x, y }) => {
if (window.__opencodeCursor) {
window.__opencodeCursor.moveTo(x, y, true)
}
}, cursorPosition)
}
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (hoverError) {
console.error("[browser-server] Hover error:", hoverError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: hoverError.message }))
}
return
}
// Drag endpoint
if (pathname === "/drag") {
const startX = parseFloat(url.searchParams.get("startX") || "0")
const startY = parseFloat(url.searchParams.get("startY") || "0")
const endX = parseFloat(url.searchParams.get("endX") || "0")
const endY = parseFloat(url.searchParams.get("endY") || "0")
console.log("[browser-server] Dragging from", `(${startX}, ${startY})`, "to", `(${endX}, ${endY})`)
try {
// Animate cursor to start position
await currentPage.evaluate(
async ({ fromX, fromY, toX, toY }) => {
if (window.__opencodeCursor) {
window.__opencodeCursor.setDragging(true)
await window.__opencodeCursor.animateTo(fromX, fromY, toX, toY, 500)
window.__opencodeCursor.setDragging(false)
}
},
{ fromX: startX, fromY: startY, toX: endX, toY: endY },
)
// Perform the actual drag
await currentPage.mouse.move(startX, startY)
await currentPage.mouse.down()
await currentPage.mouse.move(endX, endY, { steps: 10 })
await currentPage.mouse.up()
cursorPosition = { x: endX, y: endY }
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (dragError) {
console.error("[browser-server] Drag error:", dragError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: dragError.message }))
}
return
}
// Press key endpoint
if (pathname === "/pressKey") {
const key = url.searchParams.get("key")
const modifiers = (url.searchParams.get("modifiers") || "").split(",").filter(Boolean)
console.log("[browser-server] Pressing key", key, modifiers.length ? `with modifiers: ${modifiers}` : "")
try {
// Hold modifiers
for (const mod of modifiers) {
await currentPage.keyboard.down(mod)
}
await currentPage.keyboard.press(key)
// Release modifiers
for (const mod of modifiers.reverse()) {
await currentPage.keyboard.up(mod)
}
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (keyError) {
console.error("[browser-server] Key error:", keyError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: keyError.message }))
}
return
}
// Select option endpoint
if (pathname === "/select") {
const selector = url.searchParams.get("selector")
const values = (url.searchParams.get("values") || "").split("|||").filter(Boolean)
const timeout = parseInt(url.searchParams.get("timeout") || "30000", 10)
console.log("[browser-server] Selecting", values, "in", selector)
try {
const locator = currentPage.locator(selector).first()
await locator.waitFor({ state: "visible", timeout })
await locator.selectOption(values)
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (selectError) {
console.error("[browser-server] Select error:", selectError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: selectError.message }))
}
return
}
// Fill form endpoint (POST)
if (pathname === "/fillForm" && req.method === "POST") {
let body = ""
req.on("data", (chunk) => (body += chunk))
req.on("end", async () => {
try {
const { fields } = JSON.parse(body)
let filled = 0
for (const field of fields) {
try {
const locator = currentPage.locator(field.selector).first()
await locator.waitFor({ state: "visible", timeout: 5000 })
await locator.fill(field.value)
filled++
} catch (fieldError) {
console.error("[browser-server] Fill field error:", field.selector, fieldError.message)
}
}
res.writeHead(200)
res.end(JSON.stringify({ success: true, filled }))
} catch (formError) {
console.error("[browser-server] Fill form error:", formError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, filled: 0, error: formError.message }))
}
})
return
}
// Evaluate JavaScript endpoint (POST)
if (pathname === "/evaluate" && req.method === "POST") {
let body = ""
req.on("data", (chunk) => (body += chunk))
req.on("end", async () => {
try {
const { code, element, ref } = JSON.parse(body)
let result
if (element || ref) {
const locator = currentPage.locator(ref || element).first()
const elementHandle = await locator.elementHandle()
const fn = new Function("element", `return (${code})(element)`)
result = await currentPage.evaluate(fn, elementHandle)
} else {
const fn = new Function(`return (${code})()`)
result = await currentPage.evaluate(fn)
}
res.writeHead(200)
res.end(JSON.stringify({ success: true, result }))
} catch (evalError) {
console.error("[browser-server] Evaluate error:", evalError.message)
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: evalError.message }))
}
})
return
}
// Console messages endpoint
if (pathname === "/consoleMessages") {
const level = url.searchParams.get("level") || "info"
const levels = {
error: ["error"],
warning: ["error", "warning"],
info: ["error", "warning", "info", "log"],
log: ["error", "warning", "info", "log", "debug"],
}
const allowedLevels = levels[level] || levels.info
const filtered = consoleMessages.filter((msg) => allowedLevels.includes(msg.level))
res.writeHead(200)
res.end(JSON.stringify(filtered))
return
}
// Network requests endpoint
if (pathname === "/networkRequests") {
const includeStatic = url.searchParams.get("includeStatic") === "true"
const staticTypes = ["stylesheet", "image", "font", "media"]
const filtered = includeStatic
? networkRequests
: networkRequests.filter((req) => !staticTypes.includes(req.type))
res.writeHead(200)
res.end(JSON.stringify(filtered))
return
}
// Handle dialog endpoint
if (pathname === "/handleDialog") {
const accept = url.searchParams.get("accept") === "true"
const promptText = url.searchParams.get("promptText")
// Store the handler for the next dialog
dialogPromise = {
accept,
promptText,
resolve: (result) => {
res.writeHead(200)
res.end(JSON.stringify(result))
},
}
// If no dialog appears in 5 seconds, respond anyway
setTimeout(() => {
if (dialogPromise) {
dialogPromise = null
res.writeHead(200)
res.end(JSON.stringify({ success: true, note: "No dialog appeared" }))
}
}, 5000)
return
}
// Upload files endpoint (POST) - supports selector-based file upload
if (pathname === "/uploadFiles" && req.method === "POST") {
let body = ""
req.on("data", (chunk) => (body += chunk))
req.on("end", async () => {
try {
const { paths, selector } = JSON.parse(body)
if (selector) {
// Direct file input selection approach
const fileInput = await currentPage.locator(selector).first()
await fileInput.setInputFiles(paths)
res.writeHead(200)
res.end(JSON.stringify({ success: true, count: paths.length }))
} else {
// Set up the file chooser handler for dialog-based upload
fileChooserPromise = {
paths,
resolve: (result) => {
res.writeHead(200)
res.end(JSON.stringify(result))
},
}
// Wait for file chooser to be triggered
setTimeout(() => {
if (fileChooserPromise) {
fileChooserPromise = null
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: "No file chooser appeared" }))
}
}, 10000)
}
} catch (uploadError) {
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: uploadError.message }))
}
})
return
}
// Resize endpoint
if (pathname === "/resize") {
const width = parseInt(url.searchParams.get("width") || "1280", 10)
const height = parseInt(url.searchParams.get("height") || "720", 10)
console.log("[browser-server] Resizing to", width, "x", height)
try {
await currentPage.setViewportSize({ width, height })
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
} catch (resizeError) {
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: resizeError.message }))
}
return
}
// Tabs management endpoint
if (pathname === "/tabs") {
const action = url.searchParams.get("action") || "list"
const index = parseInt(url.searchParams.get("index") || "-1", 10)
console.log("[browser-server] Tabs action:", action)
try {
switch (action) {
case "list": {
const tabList = await Promise.all(
pages.map(async (page, i) => ({
index: i,
url: page.url(),
title: await page.title().catch(() => ""),
active: page === currentPage,
})),
)
res.writeHead(200)
res.end(JSON.stringify({ success: true, tabs: tabList }))
break
}
case "create": {
const newPage = await context.newPage()
pages.push(newPage)
currentPage = newPage
// Inject cursor overlay
await currentPage.addInitScript(CURSOR_OVERLAY_SCRIPT)
res.writeHead(200)
res.end(JSON.stringify({ success: true, tabs: [{ index: pages.length - 1 }] }))
break
}
case "close": {
const closeIndex = index >= 0 ? index : pages.indexOf(currentPage)
if (closeIndex >= 0 && closeIndex < pages.length) {
await pages[closeIndex].close()
pages.splice(closeIndex, 1)
if (pages.length > 0) {
currentPage = pages[Math.min(closeIndex, pages.length - 1)]
} else {
currentPage = null
}
}
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
break
}
case "select": {
if (index >= 0 && index < pages.length) {
currentPage = pages[index]
await currentPage.bringToFront()
}
res.writeHead(200)
res.end(JSON.stringify({ success: true }))
break
}
default:
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: "Unknown action" }))
}
} catch (tabsError) {
res.writeHead(200)
res.end(JSON.stringify({ success: false, error: tabsError.message }))
}
return
}
// Snapshot endpoint (accessibility tree)
if (pathname === "/snapshot") {
console.log("[browser-server] Taking accessibility snapshot")
try {
const snapshot = await currentPage.accessibility.snapshot()
const elementMap = {}
// Flatten the tree and create element map
function flattenTree(node, path = "") {
if (!node) return ""
const ref = path || "root"
const lines = []
if (node.role && node.name) {
elementMap[ref] = { ref, role: node.role, name: node.name }
lines.push(`- ${node.role} "${node.name}"`)
}
if (node.children) {
node.children.forEach((child, i) => {
lines.push(flattenTree(child, `${ref}.${i}`))
})
}
return lines.filter(Boolean).join("\n")
}
const snapshotText = flattenTree(snapshot)
res.writeHead(200)
res.end(JSON.stringify({ snapshot: snapshotText, elementMap }))
} catch (snapshotError) {
res.writeHead(200)
res.end(JSON.stringify({ snapshot: "", elementMap: {}, error: snapshotError.message }))
}
return
}