forked from openai/codex
-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathmanager.rs
More file actions
2731 lines (2440 loc) · 113 KB
/
manager.rs
File metadata and controls
2731 lines (2440 loc) · 113 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
use crate::BrowserError;
use crate::Result;
use crate::config::BrowserConfig;
use crate::config::WaitStrategy;
use crate::page::Page;
use chromiumoxide::Browser;
use chromiumoxide::BrowserConfig as CdpConfig;
use chromiumoxide::browser::HeadlessMode;
use chromiumoxide::cdp::browser_protocol::emulation;
use chromiumoxide::cdp::browser_protocol::network;
use fs2::FileExt;
use futures::StreamExt;
use once_cell::sync::Lazy;
use reqwest::Client;
use serde::Deserialize;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::RwLock;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio::time::sleep;
use tracing::debug;
use tracing::info;
use tracing::warn;
use crate::global;
#[derive(Deserialize)]
struct JsonVersion {
#[serde(rename = "webSocketDebuggerUrl")]
web_socket_debugger_url: String,
}
static INTERNAL_BROWSER_LAUNCH_GUARD: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
struct BrowserLaunchLockFile {
file: std::fs::File,
}
impl BrowserLaunchLockFile {
async fn acquire(timeout: Duration) -> Result<Self> {
let lock_path = std::env::temp_dir().join("code-browser-launch.lock");
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open(&lock_path)?;
let start = Instant::now();
loop {
match file.try_lock_exclusive() {
Ok(()) => return Ok(Self { file }),
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
if start.elapsed() >= timeout {
return Err(BrowserError::CdpError(format!(
"Timed out waiting for browser launch lock at {} (another Code instance may be launching a browser).",
lock_path.display()
)));
}
sleep(Duration::from_millis(50)).await;
}
Err(err) => return Err(BrowserError::IoError(err)),
}
}
}
}
impl Drop for BrowserLaunchLockFile {
fn drop(&mut self) {
let _ = self.file.unlock();
}
}
fn is_temporary_internal_launch_error_message(message: &str) -> bool {
let message = message.to_ascii_lowercase();
// macOS: EAGAIN = os error 35
// Linux: ENOMEM = os error 12
// Common: "Too many open files" (EMFILE)
message.contains("resource temporarily unavailable")
|| message.contains("temporarily unavailable")
|| message.contains("os error 35")
|| message.contains("eagain")
|| message.contains("os error 12")
|| message.contains("cannot allocate memory")
|| message.contains("too many open files")
|| message.contains("os error 24")
}
fn chrome_logging_enabled() -> bool {
env_truthy("CODE_SUBAGENT_DEBUG") || env_truthy("CODEX_BROWSER_LOG")
}
fn env_truthy(key: &str) -> bool {
std::env::var(key)
.map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
.unwrap_or(false)
}
fn resolve_chrome_log_path() -> Option<PathBuf> {
if !chrome_logging_enabled() {
return None;
}
if let Ok(path) = std::env::var("CODEX_BROWSER_LOG_PATH") {
let trimmed = path.trim();
if !trimmed.is_empty() {
return Some(PathBuf::from(trimmed));
}
}
let base = if let Ok(home) = std::env::var("CODE_HOME").or_else(|_| std::env::var("CODEX_HOME")) {
PathBuf::from(home).join("debug_logs")
} else if let Ok(home) = std::env::var("HOME") {
PathBuf::from(home).join(".code").join("debug_logs")
} else {
return Some(std::env::temp_dir().join("code-chrome.log"));
};
let path = base.join("code-chrome.log");
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
Some(path)
}
const HANDLER_ERROR_LIMIT: u32 = 3;
fn should_restart_handler(consecutive_errors: u32) -> bool {
consecutive_errors >= HANDLER_ERROR_LIMIT
}
fn should_ignore_handler_error(message_lower: &str) -> bool {
// Chromiumoxide uses oneshot channels internally for CDP request/response.
// When we cancel or time out an in-flight request (dropping its future), the
// CDP runtime may surface this as an error string containing "oneshot".
// These should not be treated as connection failures.
if message_lower.contains("oneshot") {
return true;
}
// Chromium can emit occasional CDP payloads that chromiumoxide fails to
// deserialize into its internal Message enum. These do not necessarily mean
// the browser session is unhealthy; treating them as fatal causes the
// manager to discard a perfectly good page right after navigation.
if message_lower.contains("data did not match any variant of untagged enum message") {
return true;
}
// These can happen for individual targets/tabs while the overall CDP
// connection is still healthy (e.g. tabs closing, navigations, reloads).
const TRANSIENT_SUBSTRINGS: &[&str] = &[
"no such session",
"session closed",
"invalid session",
"target closed",
"target crashed",
"context destroyed",
"execution context was destroyed",
"cannot find context",
];
TRANSIENT_SUBSTRINGS
.iter()
.any(|needle| message_lower.contains(needle))
}
fn should_stop_handler<E: std::fmt::Display>(
label: &'static str,
result: std::result::Result<(), E>,
consecutive_errors: &mut u32,
) -> bool {
match result {
Ok(()) => {
*consecutive_errors = 0;
false
}
Err(err) => {
let message = err.to_string();
let message_lower = message.to_ascii_lowercase();
if should_ignore_handler_error(&message_lower) {
*consecutive_errors = 0;
debug!("{label} event handler error ignored: {message}");
return false;
}
*consecutive_errors = consecutive_errors.saturating_add(1);
let count = *consecutive_errors;
if count <= HANDLER_ERROR_LIMIT {
debug!("{label} event handler error: {err} (count: {count})");
}
if should_restart_handler(count) {
warn!("{label} event handler errors exceeded limit; restarting browser connection");
return true;
}
false
}
}
}
async fn discover_ws_via_host_port(host: &str, port: u16) -> Result<String> {
let url = format!("http://{}:{}/json/version", host, port);
debug!("Requesting Chrome version info from: {}", url);
let client_start = tokio::time::Instant::now();
let client = Client::builder()
.no_proxy()
.timeout(Duration::from_secs(5)) // Allow Chrome time to bring up /json/version on fresh launch
.build()
.map_err(|e| BrowserError::CdpError(format!("Failed to build HTTP client: {}", e)))?;
debug!("HTTP client created in {:?}", client_start.elapsed());
let req_start = tokio::time::Instant::now();
let resp = client.get(&url).send().await.map_err(|e| {
BrowserError::CdpError(format!("Failed to connect to Chrome debug port: {}", e))
})?;
debug!(
"HTTP request completed in {:?}, status: {}",
req_start.elapsed(),
resp.status()
);
if !resp.status().is_success() {
return Err(BrowserError::CdpError(format!(
"Chrome /json/version returned {}",
resp.status()
)));
}
let parse_start = tokio::time::Instant::now();
let body: JsonVersion = resp.json().await.map_err(|e| {
BrowserError::CdpError(format!("Failed to parse Chrome debug response: {}", e))
})?;
debug!("Response parsed in {:?}", parse_start.elapsed());
Ok(body.web_socket_debugger_url)
}
/// Scan for Chrome processes with debug ports and verify accessibility
async fn scan_for_chrome_debug_port() -> Option<u16> {
use std::process::Command;
// Use ps to find Chrome processes with remote-debugging-port
let output = Command::new("ps").args(&["aux"]).output().ok()?;
let ps_output = String::from_utf8_lossy(&output.stdout);
// Find all Chrome processes with debug ports
let mut found_ports = Vec::new();
for line in ps_output.lines() {
// Look for Chrome/Chromium processes with remote-debugging-port
if (line.contains("chrome") || line.contains("Chrome") || line.contains("chromium"))
&& line.contains("--remote-debugging-port=")
{
// Extract the port number
if let Some(port_str) = line.split("--remote-debugging-port=").nth(1) {
// Take everything up to the next space or end of line
let port_str = port_str.split_whitespace().next().unwrap_or(port_str);
// Parse the port number
if let Ok(port) = port_str.parse::<u16>() {
// Skip port 0 (means random port, not accessible)
if port > 0 {
found_ports.push(port);
}
}
}
}
}
// Remove duplicates
found_ports.sort_unstable();
found_ports.dedup();
info!(
"Found {} Chrome process(es) with debug ports: {:?}",
found_ports.len(),
found_ports
);
// Test each found port to see if it's accessible (test in parallel for speed)
if found_ports.is_empty() {
return None;
}
debug!("Testing {} port(s) for accessibility...", found_ports.len());
let test_start = tokio::time::Instant::now();
// Create futures for testing all ports in parallel
let mut port_tests = Vec::new();
for port in found_ports {
let test_future = async move {
let url = format!("http://127.0.0.1:{}/json/version", port);
let client = Client::builder()
.no_proxy()
.timeout(Duration::from_millis(200)) // Shorter timeout for parallel tests
.build()
.ok()?;
match client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => {
debug!("Chrome port {} is accessible", port);
Some(port)
}
Ok(resp) => {
debug!("Chrome port {} returned status: {}", port, resp.status());
None
}
Err(_) => {
debug!("Could not connect to Chrome port {}", port);
None
}
}
};
port_tests.push(test_future);
}
// Test all ports in parallel and return the first accessible one
let results = futures::future::join_all(port_tests).await;
debug!(
"Port accessibility tests completed in {:?}",
test_start.elapsed()
);
for port in results.into_iter().flatten() {
info!("Verified Chrome debug port at {} is accessible", port);
return Some(port);
}
warn!("No accessible Chrome debug ports found");
None
}
pub struct BrowserManager {
pub config: Arc<RwLock<BrowserConfig>>,
browser: Arc<Mutex<Option<Browser>>>,
page: Arc<Mutex<Option<Arc<Page>>>>,
// Dedicated background page for screenshots to prevent focus stealing
background_page: Arc<Mutex<Option<Arc<Page>>>>,
last_activity: Arc<Mutex<Instant>>,
idle_monitor_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
event_task: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
assets: Arc<Mutex<Option<Arc<crate::assets::AssetManager>>>>,
user_data_dir: Arc<Mutex<Option<String>>>,
cleanup_profile_on_drop: Arc<Mutex<bool>>,
navigation_callback: Arc<tokio::sync::RwLock<Option<Box<dyn Fn(String) + Send + Sync>>>>,
navigation_monitor_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
viewport_monitor_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
/// Gate to temporarily disable all automatic viewport corrections (post-initial set)
auto_viewport_correction_enabled: Arc<tokio::sync::RwLock<bool>>,
/// Track last applied device metrics to avoid redundant overrides
last_metrics_applied: Arc<Mutex<Option<(i64, i64, f64, bool, std::time::Instant)>>>,
}
#[derive(Debug)]
struct PageDebugInfo {
target_id: String,
session_id: String,
opener_id: Option<String>,
cached_url: Option<String>,
live_url: Option<String>,
}
#[derive(Debug)]
struct TargetSnapshot {
total: usize,
sample: Vec<String>,
truncated: bool,
}
impl BrowserManager {
const SCREENSHOT_TTL_MS: u64 = 86_400_000; // 24 hours
pub fn new(config: BrowserConfig) -> Self {
Self {
config: Arc::new(RwLock::new(config)),
browser: Arc::new(Mutex::new(None)),
page: Arc::new(Mutex::new(None)),
background_page: Arc::new(Mutex::new(None)),
last_activity: Arc::new(Mutex::new(Instant::now())),
idle_monitor_handle: Arc::new(Mutex::new(None)),
event_task: Arc::new(Mutex::new(None)),
assets: Arc::new(Mutex::new(None)),
user_data_dir: Arc::new(Mutex::new(None)),
cleanup_profile_on_drop: Arc::new(Mutex::new(false)),
navigation_callback: Arc::new(tokio::sync::RwLock::new(None)),
navigation_monitor_handle: Arc::new(Mutex::new(None)),
viewport_monitor_handle: Arc::new(Mutex::new(None)),
auto_viewport_correction_enabled: Arc::new(tokio::sync::RwLock::new(true)),
last_metrics_applied: Arc::new(Mutex::new(None)),
}
}
/// Try to connect to Chrome via CDP only - no fallback to internal browser
pub async fn connect_to_chrome_only(&self) -> Result<()> {
tracing::info!("[cdp/bm] connect_to_chrome_only: begin");
// Quick check without holding the lock during IO
if self.browser.lock().await.is_some() {
tracing::info!("[cdp/bm] already connected; early return");
return Ok(());
}
let config = self.config.read().await.clone();
tracing::info!(
"[cdp/bm] config: connect_host={:?}, connect_port={:?}, connect_ws={:?}",
config.connect_host, config.connect_port, config.connect_ws
);
// If a WebSocket is configured explicitly, try that first
if let Some(ws) = config.connect_ws.clone() {
info!("[cdp/bm] Connecting to Chrome via configured WebSocket: {}", ws);
let attempt_timeout = Duration::from_millis(config.connect_attempt_timeout_ms);
let attempts = std::cmp::max(1, config.connect_attempts as i32);
let mut last_err: Option<String> = None;
for attempt in 1..=attempts {
info!(
"[cdp/bm] WS connect attempt {}/{} (timeout={}ms)",
attempt,
attempts,
attempt_timeout.as_millis()
);
let ws_clone = ws.clone();
let handle = tokio::spawn(async move { Browser::connect(ws_clone).await });
match tokio::time::timeout(attempt_timeout, handle).await {
Ok(Ok(Ok((browser, mut handler)))) => {
info!("[cdp/bm] WS connect attempt {} succeeded", attempt);
// Start event handler loop
let browser_arc = self.browser.clone();
let page_arc = self.page.clone();
let background_page_arc = self.background_page.clone();
let task = tokio::spawn(async move {
let mut consecutive_errors = 0u32;
while let Some(result) = handler.next().await {
if should_stop_handler("[cdp/bm]", result, &mut consecutive_errors) {
break;
}
}
warn!("[cdp/bm] event handler ended; clearing browser state so it can restart");
*browser_arc.lock().await = None;
*page_arc.lock().await = None;
*background_page_arc.lock().await = None;
});
*self.event_task.lock().await = Some(task);
{
let mut guard = self.browser.lock().await;
*guard = Some(browser);
}
*self.cleanup_profile_on_drop.lock().await = false;
// Fire-and-forget targets warmup
{
let browser_arc = self.browser.clone();
tokio::spawn(async move {
if let Some(browser) = browser_arc.lock().await.as_mut() {
let _ = tokio::time::timeout(Duration::from_millis(100), browser.fetch_targets()).await;
}
});
}
self.start_idle_monitor().await;
self.update_activity().await;
// Cache last connection (ws only)
global::set_last_connection(None, Some(ws.clone())).await;
return Ok(());
}
Ok(Ok(Err(e))) => {
let msg = format!("CDP WebSocket connect failed: {}", e);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Ok(Err(join_err)) => {
let msg = format!("Join error during connect attempt: {}", join_err);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Err(_) => {
warn!(
"[cdp/bm] WS connect attempt {} timed out after {}ms; aborting attempt",
attempt,
attempt_timeout.as_millis()
);
}
}
sleep(Duration::from_millis(200)).await;
}
let base = "CDP WebSocket connect failed after all attempts".to_string();
let msg = if let Some(e) = last_err { format!("{}: {}", base, e) } else { base };
return Err(BrowserError::CdpError(msg));
}
// Only try CDP connection via port, no fallback
if let Some(port) = config.connect_port {
let host = config.connect_host.as_deref().unwrap_or("127.0.0.1");
let actual_port = if port == 0 {
info!("Auto-scanning for Chrome debug ports...");
let start = tokio::time::Instant::now();
let result = scan_for_chrome_debug_port().await.unwrap_or(0);
info!(
"Auto-scan completed in {:?}, found port: {}",
start.elapsed(),
result
);
result
} else {
info!("[cdp/bm] Using specified Chrome debug port: {}", port);
port
};
if actual_port > 0 {
info!("[cdp/bm] Discovering Chrome WebSocket URL via {}:{}...", host, actual_port);
// Retry discovery for up to 15s to allow a freshly launched Chrome to initialize
let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
let ws = loop {
let discover_start = tokio::time::Instant::now();
match discover_ws_via_host_port(host, actual_port).await {
Ok(ws) => {
info!("[cdp/bm] WS discovered in {:?}: {}", discover_start.elapsed(), ws);
break ws;
}
Err(e) => {
if tokio::time::Instant::now() >= deadline {
return Err(BrowserError::CdpError(format!(
"Failed to discover Chrome WebSocket on port {} within 15s: {}",
actual_port, e
)));
}
tokio::time::sleep(Duration::from_millis(300)).await;
}
}
};
info!("[cdp/bm] Connecting to Chrome via WebSocket...");
let connect_start = tokio::time::Instant::now();
// Enforce per-attempt timeouts via spawned task to avoid hangs
let attempt_timeout = Duration::from_millis(config.connect_attempt_timeout_ms);
let attempts = std::cmp::max(1, config.connect_attempts as i32);
let mut last_err: Option<String> = None;
for attempt in 1..=attempts {
info!(
"[cdp/bm] WS connect attempt {}/{} (timeout={}ms)",
attempt,
attempts,
attempt_timeout.as_millis()
);
let ws_clone = ws.clone();
let handle = tokio::spawn(async move { Browser::connect(ws_clone).await });
match tokio::time::timeout(attempt_timeout, handle).await {
Ok(Ok(Ok((browser, mut handler)))) => {
info!("[cdp/bm] WS connect attempt {} succeeded", attempt);
info!("[cdp/bm] Connected to Chrome in {:?}", connect_start.elapsed());
// Start event handler loop
let browser_arc = self.browser.clone();
let page_arc = self.page.clone();
let background_page_arc = self.background_page.clone();
let task = tokio::spawn(async move {
let mut consecutive_errors = 0u32;
while let Some(result) = handler.next().await {
if should_stop_handler("[cdp/bm]", result, &mut consecutive_errors) {
break;
}
}
warn!("[cdp/bm] event handler ended; clearing browser state so it can restart");
*browser_arc.lock().await = None;
*page_arc.lock().await = None;
*background_page_arc.lock().await = None;
});
*self.event_task.lock().await = Some(task);
// Install browser
{
let mut guard = self.browser.lock().await;
*guard = Some(browser);
}
*self.cleanup_profile_on_drop.lock().await = false;
// Fire-and-forget targets warmup after browser is installed
{
let browser_arc = self.browser.clone();
tokio::spawn(async move {
if let Some(browser) = browser_arc.lock().await.as_mut() {
let _ = tokio::time::timeout(Duration::from_millis(100), browser.fetch_targets()).await;
}
});
}
self.start_idle_monitor().await;
self.update_activity().await;
// Update last connection cache
global::set_last_connection(Some(actual_port), Some(ws.clone())).await;
return Ok(());
}
Ok(Ok(Err(e))) => {
let msg = format!("CDP WebSocket connect failed: {}", e);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Ok(Err(join_err)) => {
let msg = format!("Join error during connect attempt: {}", join_err);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Err(_) => {
warn!(
"[cdp/bm] WS connect attempt {} timed out after {}ms; aborting attempt",
attempt,
attempt_timeout.as_millis()
);
// Best-effort abort; if connect is internally blocking, it may keep a worker thread busy,
// but our caller remains responsive and we can retry.
// We cannot await the handle here without risking another stall.
}
}
// Small backoff between attempts
sleep(Duration::from_millis(200)).await;
}
let base = "CDP WebSocket connect failed after all attempts".to_string();
let msg = if let Some(e) = last_err { format!("{}: {}", base, e) } else { base };
return Err(BrowserError::CdpError(msg));
} else {
return Err(BrowserError::CdpError(
"No Chrome instance found with debug port".to_string(),
));
}
} else {
return Err(BrowserError::CdpError(
"No CDP port configured for Chrome connection".to_string(),
));
}
}
pub async fn start(&self) -> Result<()> {
if self.browser.lock().await.is_some() {
return Ok(());
}
let config = self.config.read().await.clone();
// 1) Attach to a live Chrome, if requested
if let Some(ws) = config.connect_ws.clone() {
info!("Connecting to Chrome via WebSocket: {}", ws);
// Use the same guarded connect strategy as connect_to_chrome_only
let attempt_timeout = Duration::from_millis(config.connect_attempt_timeout_ms);
let attempts = std::cmp::max(1, config.connect_attempts as i32);
let mut last_err: Option<String> = None;
for attempt in 1..=attempts {
info!(
"[cdp/bm] WS connect attempt {}/{} (timeout={}ms)",
attempt,
attempts,
attempt_timeout.as_millis()
);
let ws_clone = ws.clone();
let handle = tokio::spawn(async move { Browser::connect(ws_clone).await });
match tokio::time::timeout(attempt_timeout, handle).await {
Ok(Ok(Ok((browser, mut handler)))) => {
info!("[cdp/bm] WS connect attempt {} succeeded", attempt);
// Start event handler loop
let browser_arc = self.browser.clone();
let page_arc = self.page.clone();
let background_page_arc = self.background_page.clone();
let task = tokio::spawn(async move {
let mut consecutive_errors = 0u32;
while let Some(result) = handler.next().await {
if should_stop_handler("[cdp/bm]", result, &mut consecutive_errors) {
break;
}
}
warn!("[cdp/bm] event handler ended; clearing browser state so it can restart");
*browser_arc.lock().await = None;
*page_arc.lock().await = None;
*background_page_arc.lock().await = None;
});
*self.event_task.lock().await = Some(task);
{
let mut guard = self.browser.lock().await;
*guard = Some(browser);
}
*self.cleanup_profile_on_drop.lock().await = false;
// Fire-and-forget targets warmup after browser is installed
{
let browser_arc = self.browser.clone();
tokio::spawn(async move {
if let Some(browser) = browser_arc.lock().await.as_mut() {
let _ = tokio::time::timeout(Duration::from_millis(100), browser.fetch_targets()).await;
}
});
}
self.start_idle_monitor().await;
self.update_activity().await;
return Ok(());
}
Ok(Ok(Err(e))) => {
let msg = format!("CDP WebSocket connect failed: {}", e);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Ok(Err(join_err)) => {
let msg = format!("Join error during connect attempt: {}", join_err);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Err(_) => {
warn!(
"[cdp/bm] WS connect attempt {} timed out after {}ms; aborting attempt",
attempt,
attempt_timeout.as_millis()
);
}
}
sleep(Duration::from_millis(200)).await;
}
let base = "CDP WebSocket connect failed after all attempts".to_string();
let msg = if let Some(e) = last_err { format!("{}: {}", base, e) } else { base };
return Err(BrowserError::CdpError(msg));
}
if let Some(port) = config.connect_port {
let host = config.connect_host.as_deref().unwrap_or("127.0.0.1");
let actual_port = if port == 0 {
info!("Auto-scanning for Chrome debug ports...");
let start = tokio::time::Instant::now();
let result = scan_for_chrome_debug_port().await.unwrap_or(0);
info!(
"Auto-scan completed in {:?}, found port: {}",
start.elapsed(),
result
);
result
} else {
info!("Using specified Chrome debug port: {}", port);
port
};
if actual_port > 0 {
info!("Step 1: Discovering Chrome WebSocket URL via {}:{}...", host, actual_port);
let ws = loop {
let discover_start = tokio::time::Instant::now();
match discover_ws_via_host_port(host, actual_port).await {
Ok(ws) => {
info!(
"Step 2: WebSocket URL discovered in {:?}: {}",
discover_start.elapsed(),
ws
);
break ws;
}
Err(e) => {
if tokio::time::Instant::now() - discover_start > Duration::from_secs(15) {
return Err(BrowserError::CdpError(format!(
"Failed to discover Chrome WebSocket on port {} within 15s: {}",
actual_port, e
)));
}
tokio::time::sleep(Duration::from_millis(300)).await;
}
}
};
info!("Step 3: Connecting to Chrome via WebSocket...");
let connect_start = tokio::time::Instant::now();
// Use guarded connect strategy with retries
let attempt_timeout = Duration::from_millis(config.connect_attempt_timeout_ms);
let attempts = std::cmp::max(1, config.connect_attempts as i32);
let mut last_err: Option<String> = None;
for attempt in 1..=attempts {
info!(
"[cdp/bm] WS connect attempt {}/{} (timeout={}ms)",
attempt,
attempts,
attempt_timeout.as_millis()
);
let ws_clone = ws.clone();
let handle = tokio::spawn(async move { Browser::connect(ws_clone).await });
match tokio::time::timeout(attempt_timeout, handle).await {
Ok(Ok(Ok((browser, mut handler)))) => {
info!("[cdp/bm] WS connect attempt {} succeeded", attempt);
info!(
"Step 4: Connected to Chrome in {:?}",
connect_start.elapsed()
);
// Start event handler
let browser_arc = self.browser.clone();
let page_arc = self.page.clone();
let background_page_arc = self.background_page.clone();
let task = tokio::spawn(async move {
let mut consecutive_errors = 0u32;
while let Some(result) = handler.next().await {
if should_stop_handler("[cdp/bm]", result, &mut consecutive_errors) {
break;
}
}
warn!("[cdp/bm] event handler ended; clearing browser state so it can restart");
*browser_arc.lock().await = None;
*page_arc.lock().await = None;
*background_page_arc.lock().await = None;
});
*self.event_task.lock().await = Some(task);
{
let mut guard = self.browser.lock().await;
*guard = Some(browser);
}
*self.cleanup_profile_on_drop.lock().await = false;
// Fire-and-forget targets warmup after browser is installed
{
let browser_arc = self.browser.clone();
tokio::spawn(async move {
if let Some(browser) = browser_arc.lock().await.as_mut() {
let _ = tokio::time::timeout(Duration::from_millis(100), browser.fetch_targets()).await;
}
});
}
info!("Step 5: Starting idle monitor...");
self.start_idle_monitor().await;
self.update_activity().await;
info!("Step 6: Chrome connection complete!");
return Ok(());
}
Ok(Ok(Err(e))) => {
let msg = format!("CDP WebSocket connect failed: {}", e);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Ok(Err(join_err)) => {
let msg = format!("Join error during connect attempt: {}", join_err);
warn!("[cdp/bm] {}", msg);
last_err = Some(msg);
}
Err(_) => {
warn!(
"[cdp/bm] WS connect attempt {} timed out after {}ms; aborting attempt",
attempt,
attempt_timeout.as_millis()
);
}
}
sleep(Duration::from_millis(200)).await;
}
let base = "CDP WebSocket connect failed after all attempts".to_string();
let msg = if let Some(e) = last_err { format!("{}: {}", base, e) } else { base };
return Err(BrowserError::CdpError(msg));
}
}
// 2) Launch a browser
info!("Launching new browser instance");
// Prevent redundant browser launches within the same process.
let _launch_guard = INTERNAL_BROWSER_LAUNCH_GUARD.lock().await;
// Also serialize launches across Code processes; concurrent Chromium spawns
// are a common source of transient EAGAIN/ENOMEM failures on macOS.
let _launch_lock = BrowserLaunchLockFile::acquire(Duration::from_secs(30)).await?;
const INTERNAL_LAUNCH_RETRY_DELAYS_MS: [u64; 5] = [50, 200, 500, 1000, 2000];
let max_attempts = INTERNAL_LAUNCH_RETRY_DELAYS_MS.len() + 1;
// Add browser launch flags (keep minimal set for screenshot functionality)
let log_file = resolve_chrome_log_path();
let (browser, mut handler, user_data_path) = {
let mut attempt = 1usize;
loop {
// Profile dir
let (user_data_path, is_temp_profile) = if let Some(dir) = &config.user_data_dir {
(dir.to_string_lossy().to_string(), false)
} else {
let pid = std::process::id();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
let temp_path = format!("/tmp/code-browser-{pid}-{timestamp}-{attempt}");
if tokio::fs::metadata(&temp_path).await.is_ok() {
let _ = tokio::fs::remove_dir_all(&temp_path).await;
}
(temp_path, true)
};
let mut builder = CdpConfig::builder().user_data_dir(&user_data_path);
// Set headless mode based on config (keep original approach for stability)
if config.headless {
builder = builder.headless_mode(HeadlessMode::New);
}
// Configure viewport (revert to original approach for screenshot stability)
builder = builder.window_size(config.viewport.width, config.viewport.height);
builder = builder
.arg("--disable-blink-features=AutomationControlled")
.arg("--no-first-run")
.arg("--no-default-browser-check")
.arg("--disable-component-extensions-with-background-pages")
.arg("--disable-background-networking")
.arg("--silent-debugger-extension-api")
.arg("--remote-allow-origins=*")
.arg("--disable-features=ChromeWhatsNewUI,TriggerFirstRunUI")
// Disable timeout for slow networks/pages
.arg("--disable-hang-monitor")
.arg("--disable-background-timer-throttling")
// Suppress console output
.arg("--silent-launch")
// Set a longer timeout for CDP requests (60 seconds instead of default 30)
.request_timeout(Duration::from_secs(60));
if let Some(ref log_file) = log_file {
builder = builder
.arg("--enable-logging")
.arg("--log-level=1")
.arg(format!("--log-file={}", log_file.display()));
}
let browser_config = builder
.build()
.map_err(|e| BrowserError::CdpError(e.to_string()))?;
match Browser::launch(browser_config).await {
Ok((browser, handler)) => break (browser, handler, user_data_path),
Err(e) => {
let message = e.to_string();
let is_temporary = is_temporary_internal_launch_error_message(&message);
if is_temp_profile {
let _ = tokio::fs::remove_dir_all(&user_data_path).await;
}
if is_temporary && attempt < max_attempts {
let delay_ms = INTERNAL_LAUNCH_RETRY_DELAYS_MS[attempt - 1];
warn!(
error = %message,
attempt,
delay_ms,
"Internal browser launch failed with transient error; retrying"
);
sleep(Duration::from_millis(delay_ms)).await;
attempt += 1;
continue;
}
#[cfg(target_os = "macos")]
let hint = "Ensure Google Chrome or Chromium is installed and runnable (e.g., /Applications/Google Chrome.app).";
#[cfg(target_os = "linux")]
let hint = "Ensure google-chrome or chromium is installed and available on PATH.";
#[cfg(target_os = "windows")]
let hint = "Ensure Chrome is installed and chrome.exe is available (typically in Program Files).";
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
let hint = "Ensure Chrome/Chromium is installed and available on PATH.";
let log_note = log_file
.as_ref()
.map(|path| format!(" Chrome log: {}", path.display()))
.unwrap_or_default();
return Err(BrowserError::CdpError(format!(
"Failed to launch internal browser: {message}. Hint: {hint}.{log_note}"
)));
}
}
}
};
// Optionally: browser.fetch_targets().await.ok();
let browser_arc = self.browser.clone();
let page_arc = self.page.clone();
let background_page_arc = self.background_page.clone();
let task = tokio::spawn(async move {
let mut consecutive_errors = 0u32;
while let Some(result) = handler.next().await {
if should_stop_handler("[cdp/bm]", result, &mut consecutive_errors) {
break;
}
}
warn!("[cdp/bm] event handler ended; clearing browser state so it can restart");
*browser_arc.lock().await = None;
*page_arc.lock().await = None;
*background_page_arc.lock().await = None;
});
*self.event_task.lock().await = Some(task);
{
let mut guard = self.browser.lock().await;
*guard = Some(browser);
}
*self.user_data_dir.lock().await = Some(user_data_path.clone());
let should_cleanup = config.user_data_dir.is_none() || !config.persist_profile;