-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathchrome.rs
More file actions
1900 lines (1699 loc) · 63.5 KB
/
chrome.rs
File metadata and controls
1900 lines (1699 loc) · 63.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
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use super::discovery::discover_cdp_url;
pub struct ChromeProcess {
child: Child,
pub ws_url: String,
temp_user_data_dir: Option<PathBuf>,
/// On Unix, the process group ID used to kill the entire Chrome process tree.
#[cfg(unix)]
pgid: Option<i32>,
}
impl ChromeProcess {
pub fn kill(&mut self) {
let _ = self.child.kill();
// On Unix, kill the entire process group to ensure Chrome helper
// processes (GPU, renderer, utility, crashpad) are also terminated.
// This prevents orphaned Chrome processes from blocking the user's
// normal Chrome (issue #1113).
#[cfg(unix)]
if let Some(pgid) = self.pgid {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
let _ = self.child.wait();
}
/// Returns the OS process ID of the Chrome child process.
pub fn id(&self) -> u32 {
self.child.id()
}
/// Non-blocking check whether Chrome has exited.
/// Returns `true` if the process has exited (and reaps it), `false` if still running.
pub fn has_exited(&mut self) -> bool {
matches!(self.child.try_wait(), Ok(Some(_)) | Err(_))
}
/// Wait for Chrome to exit on its own (after Browser.close CDP command),
/// falling back to kill() if it doesn't exit within the timeout.
/// This allows Chrome to flush cookies and other state to the user-data-dir.
pub fn wait_or_kill(&mut self, timeout: Duration) {
let start = std::time::Instant::now();
let poll_interval = Duration::from_millis(50);
while start.elapsed() < timeout {
match self.child.try_wait() {
Ok(Some(_)) => return,
Ok(None) => std::thread::sleep(poll_interval),
Err(_) => break,
}
}
self.kill();
}
}
impl Drop for ChromeProcess {
fn drop(&mut self) {
self.kill();
if let Some(ref dir) = self.temp_user_data_dir {
for attempt in 0..3 {
match std::fs::remove_dir_all(dir) {
Ok(()) => break,
Err(_) if attempt < 2 => {
std::thread::sleep(Duration::from_millis(100));
}
Err(e) => {
// Use write! instead of eprintln! to avoid panicking
// if the daemon's stderr pipe is broken (parent dropped it).
let _ = writeln!(
std::io::stderr(),
"Warning: failed to clean up temp profile {}: {}",
dir.display(),
e
);
}
}
}
}
}
}
#[derive(Clone)]
pub struct LaunchOptions {
pub headless: bool,
pub executable_path: Option<String>,
pub proxy: Option<String>,
pub proxy_bypass: Option<String>,
pub proxy_username: Option<String>,
pub proxy_password: Option<String>,
pub profile: Option<String>,
pub args: Vec<String>,
pub ignore_default_args: Vec<String>,
pub allow_file_access: bool,
pub extensions: Option<Vec<String>>,
pub storage_state: Option<String>,
pub user_agent: Option<String>,
pub ignore_https_errors: bool,
pub color_scheme: Option<String>,
pub download_path: Option<String>,
/// When true, omit `--password-store=basic` and `--use-mock-keychain` so
/// Chrome uses the real system keychain. Set automatically when launching
/// with a copied Chrome profile.
pub use_real_keychain: bool,
}
impl Default for LaunchOptions {
fn default() -> Self {
Self {
headless: true,
executable_path: None,
proxy: None,
proxy_bypass: None,
proxy_username: None,
proxy_password: None,
profile: None,
args: Vec::new(),
ignore_default_args: Vec::new(),
allow_file_access: false,
extensions: None,
storage_state: None,
user_agent: None,
ignore_https_errors: false,
color_scheme: None,
download_path: None,
use_real_keychain: false,
}
}
}
struct ChromeArgs {
args: Vec<String>,
user_data_dir: PathBuf,
temp_user_data_dir: Option<PathBuf>,
}
fn build_chrome_args(options: &LaunchOptions) -> Result<ChromeArgs, String> {
let mut args = vec![
"--remote-debugging-port=0".to_string(),
"--no-first-run".to_string(),
"--no-default-browser-check".to_string(),
"--disable-background-networking".to_string(),
"--disable-backgrounding-occluded-windows".to_string(),
"--disable-component-update".to_string(),
"--disable-default-apps".to_string(),
"--disable-hang-monitor".to_string(),
"--disable-popup-blocking".to_string(),
"--disable-prompt-on-repost".to_string(),
"--disable-sync".to_string(),
"--disable-features=Translate".to_string(),
"--enable-features=NetworkService,NetworkServiceInProcess".to_string(),
"--metrics-recording-only".to_string(),
];
if !options.ignore_default_args.is_empty() {
args.retain(|arg| !options.ignore_default_args.contains(arg));
}
if !options.use_real_keychain {
args.push("--password-store=basic".to_string());
args.push("--use-mock-keychain".to_string());
}
let has_extensions = options
.extensions
.as_ref()
.is_some_and(|exts| !exts.is_empty());
// Extensions require headed mode in native Chrome (content scripts are not
// injected in headless mode). Skip --headless when extensions are loaded.
if options.headless && !has_extensions {
args.push("--headless=new".to_string());
// Enable SwiftShader software rendering in headless mode. This
// prevents silent crashes in environments where GPU drivers are
// missing or restricted (VMs, containers, some cloud machines)
// while preserving WebGL support. Playwright uses the same flag.
args.push("--enable-unsafe-swiftshader".to_string());
}
if let Some(ref proxy) = options.proxy {
args.push(format!("--proxy-server={}", proxy));
}
if let Some(ref bypass) = options.proxy_bypass {
args.push(format!("--proxy-bypass-list={}", bypass));
}
let (user_data_dir, temp_user_data_dir) = if let Some(ref profile) = options.profile {
let expanded = expand_tilde(profile);
let dir = PathBuf::from(&expanded);
args.push(format!("--user-data-dir={}", expanded));
(dir, None)
} else {
let dir =
std::env::temp_dir().join(format!("agent-browser-chrome-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir)
.map_err(|e| format!("Failed to create temp profile dir: {}", e))?;
args.push(format!("--user-data-dir={}", dir.display()));
(dir.clone(), Some(dir))
};
if options.ignore_https_errors {
args.push("--ignore-certificate-errors".to_string());
}
if options.allow_file_access {
args.push("--allow-file-access-from-files".to_string());
args.push("--allow-file-access".to_string());
}
if let Some(ref exts) = options.extensions {
if !exts.is_empty() {
let ext_list = exts.join(",");
args.push(format!("--load-extension={}", ext_list));
args.push(format!("--disable-extensions-except={}", ext_list));
}
}
let has_window_size = options
.args
.iter()
.any(|a| a.starts_with("--start-maximized") || a.starts_with("--window-size="));
if !has_window_size && options.headless && !has_extensions {
args.push("--window-size=1280,720".to_string());
}
args.extend(options.args.iter().cloned());
if should_disable_sandbox(&args) {
args.push("--no-sandbox".to_string());
}
if should_disable_dev_shm(&args) {
args.push("--disable-dev-shm-usage".to_string());
}
Ok(ChromeArgs {
args,
user_data_dir,
temp_user_data_dir,
})
}
pub fn launch_chrome(options: &LaunchOptions) -> Result<ChromeProcess, String> {
let chrome_path = match &options.executable_path {
Some(p) => PathBuf::from(p),
None => find_chrome().ok_or_else(|| {
let cache_dir = crate::install::get_browsers_dir();
format!(
"Chrome not found. Checked:\n \
- agent-browser cache: {}\n \
- System Chrome installations\n \
- Puppeteer browser cache\n \
- Playwright browser cache\n\
Run `agent-browser install` to download Chrome, or use --executable-path.",
cache_dir.display()
)
})?,
};
// Profile name preprocessing: if --profile is a Chrome profile name (not a
// path), resolve it to a directory, copy the profile to a temp dir, and
// rewrite options so the retry loop uses the copied profile.
let mut resolved_options: Option<LaunchOptions> = None;
let mut profile_temp_dir: Option<PathBuf> = None;
if let Some(ref profile) = options.profile {
if is_chrome_profile_name(profile) {
let user_data_dir = find_chrome_user_data_dir().ok_or_else(|| {
"No Chrome user data directory found. Cannot resolve profile name.\n\
If you meant a directory path, use a full path (e.g., /path/to/profile)."
.to_string()
})?;
let resolved = resolve_chrome_profile(&user_data_dir, profile)?;
let temp_path = copy_chrome_profile(&user_data_dir, &resolved)?;
let mut opts = options.clone();
opts.profile = Some(temp_path.display().to_string());
opts.use_real_keychain = true;
opts.args.push(format!("--profile-directory={}", resolved));
profile_temp_dir = Some(temp_path);
resolved_options = Some(opts);
}
}
let effective_options = resolved_options.as_ref().unwrap_or(options);
let max_attempts = 3;
let mut last_err = String::new();
for attempt in 1..=max_attempts {
match try_launch_chrome(&chrome_path, effective_options) {
Ok(mut process) => {
// Transfer profile temp dir ownership to ChromeProcess for cleanup on Drop.
// The try_launch_chrome temp_user_data_dir is None here because we set profile
// to the temp path (treated as a user-supplied path, no second temp dir).
if let Some(ref dir) = profile_temp_dir {
process.temp_user_data_dir = Some(dir.clone());
}
return Ok(process);
}
Err(e) => {
last_err = e;
if attempt < max_attempts {
// Use write! instead of eprintln! to avoid panicking
// if the daemon's stderr pipe is broken (parent dropped it).
let _ = writeln!(
std::io::stderr(),
"[chrome] Launch attempt {}/{} failed, retrying in 500ms...",
attempt,
max_attempts
);
std::thread::sleep(Duration::from_millis(500));
}
}
}
}
// All retries failed: clean up profile temp dir if we created one
if let Some(ref dir) = profile_temp_dir {
let _ = std::fs::remove_dir_all(dir);
}
Err(last_err)
}
fn try_launch_chrome(chrome_path: &Path, options: &LaunchOptions) -> Result<ChromeProcess, String> {
let ChromeArgs {
args,
user_data_dir,
temp_user_data_dir,
} = build_chrome_args(options)?;
// Mitigate stale DevToolsActivePort risk (e.g., previous crash left it behind).
// Puppeteer does similar cleanup before spawning.
let _ = std::fs::remove_file(user_data_dir.join("DevToolsActivePort"));
let cleanup_temp_dir = |dir: &Option<PathBuf>| {
if let Some(ref d) = dir {
let _ = std::fs::remove_dir_all(d);
}
};
let mut cmd = Command::new(chrome_path);
cmd.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
// Place Chrome in its own process group so we can kill the entire tree
// (main process + GPU/renderer/utility/crashpad helpers) with a single
// killpg(), preventing orphaned processes (issue #1113).
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: pre_exec runs between fork() and exec() in the child.
// Both prctl and setpgid are async-signal-safe.
unsafe {
cmd.pre_exec(|| {
// On Linux, ask the kernel to send SIGKILL to this process
// when the parent (daemon) dies for any reason, including
// SIGKILL. This is the most robust orphan prevention
// available and has no macOS equivalent.
#[cfg(target_os = "linux")]
{
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL);
}
// Create a new process group (PGID = own PID) so the
// daemon can kill the entire Chrome tree in one call.
libc::setpgid(0, 0);
Ok(())
});
}
}
let mut child = cmd.spawn().map_err(|e| {
cleanup_temp_dir(&temp_user_data_dir);
format!("Failed to launch Chrome at {:?}: {}", chrome_path, e)
})?;
// Shared overall deadline so we don't double-wait (poll + stderr fallback).
let deadline = std::time::Instant::now() + Duration::from_secs(30);
// Primary path: use DevToolsActivePort written into user-data-dir.
// This is more reliable on Windows than scraping stderr for "DevTools listening on ...",
// which can be missing/empty depending on how Chrome is launched.
let ws_url = match wait_for_devtools_active_port(&mut child, &user_data_dir, deadline) {
Ok(url) => url,
Err(primary_err) => {
// Fallback: scrape stderr (legacy behavior) for better diagnostics.
let stderr = child.stderr.take().ok_or_else(|| {
let _ = child.kill();
cleanup_temp_dir(&temp_user_data_dir);
"Failed to capture Chrome stderr".to_string()
})?;
let reader = BufReader::new(stderr);
match wait_for_ws_url_until(reader, deadline) {
Ok(url) => url,
Err(fallback_err) => {
let _ = child.kill();
cleanup_temp_dir(&temp_user_data_dir);
return Err(format!(
"{}\n(also tried parsing stderr) {}",
primary_err, fallback_err
));
}
}
}
};
#[cfg(unix)]
let pgid = {
let pid = child.id() as i32;
// The child called setpgid(0,0) via process_group(0), so its PGID
// equals its own PID.
Some(pid)
};
Ok(ChromeProcess {
child,
ws_url,
temp_user_data_dir,
#[cfg(unix)]
pgid,
})
}
fn wait_for_devtools_active_port(
child: &mut Child,
user_data_dir: &Path,
deadline: std::time::Instant,
) -> Result<String, String> {
let poll_interval = Duration::from_millis(50);
while std::time::Instant::now() <= deadline {
if let Ok(Some(status)) = child.try_wait() {
// Chrome exited before writing DevToolsActivePort -- report the
// exit code so the caller can surface it alongside stderr output.
let code = status
.code()
.map(|c| format!("{}", c))
.unwrap_or_else(|| "unknown".to_string());
return Err(format!(
"Chrome exited early (exit code: {}) without writing DevToolsActivePort",
code
));
}
if let Some((port, ws_path)) = read_devtools_active_port(user_data_dir) {
let ws_url = format!("ws://127.0.0.1:{}{}", port, ws_path);
return Ok(ws_url);
}
std::thread::sleep(poll_interval);
}
Err("Timeout waiting for DevToolsActivePort".to_string())
}
fn wait_for_ws_url_until(
reader: BufReader<std::process::ChildStderr>,
deadline: std::time::Instant,
) -> Result<String, String> {
let prefix = "DevTools listening on ";
let mut stderr_lines: Vec<String> = Vec::new();
for line in reader.lines() {
if std::time::Instant::now() > deadline {
return Err(chrome_launch_error(
"Timeout waiting for Chrome DevTools URL",
&stderr_lines,
));
}
let line = line.map_err(|e| format!("Failed to read Chrome stderr: {}", e))?;
if let Some(url) = line.strip_prefix(prefix) {
return Ok(url.trim().to_string());
}
stderr_lines.push(line);
}
Err(chrome_launch_error(
"Chrome exited before providing DevTools URL",
&stderr_lines,
))
}
fn chrome_launch_error(message: &str, stderr_lines: &[String]) -> String {
let relevant: Vec<&String> = stderr_lines
.iter()
.filter(|l| {
let lower = l.to_lowercase();
lower.contains("error")
|| lower.contains("fatal")
|| lower.contains("sandbox")
|| lower.contains("namespace")
|| lower.contains("permission")
|| lower.contains("cannot")
|| lower.contains("failed")
|| lower.contains("abort")
})
.collect();
if relevant.is_empty() {
if stderr_lines.is_empty() {
return format!(
"{} (no stderr output from Chrome)\nHint: try passing --args \"--no-sandbox\" if Chrome crashes silently in your environment",
message
);
}
let last_lines: Vec<&String> = stderr_lines.iter().rev().take(5).collect();
return format!(
"{}\nChrome stderr (last {} lines):\n {}",
message,
last_lines.len(),
last_lines
.into_iter()
.rev()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join("\n ")
);
}
let hint = if relevant.iter().any(|l| {
let lower = l.to_lowercase();
lower.contains("sandbox") || lower.contains("namespace")
}) {
"\nHint: try --args \"--no-sandbox\" (required in containers, VMs, and some Linux setups)"
} else {
""
};
format!(
"{}\nChrome stderr:\n {}{}",
message,
relevant
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join("\n "),
hint
)
}
pub fn find_chrome() -> Option<PathBuf> {
// 1. Check Chrome downloaded by `agent-browser install`
if let Some(p) = crate::install::find_installed_chrome() {
return Some(p);
}
// If the cache directory exists but no Chrome was found, warn -- this
// likely means the cache is corrupted or the directory layout is unexpected.
let cache_dir = crate::install::get_browsers_dir();
if cache_dir.exists() {
let _ = writeln!(
std::io::stderr(),
"Warning: Chrome cache directory exists ({}) but no Chrome binary found inside. \
Falling back to system Chrome. Run `agent-browser install` to re-download.",
cache_dir.display()
);
}
// 2. Check system-installed Chrome
#[cfg(target_os = "macos")]
{
let candidates = [
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
];
for c in &candidates {
let p = PathBuf::from(c);
if p.exists() {
return Some(p);
}
}
}
#[cfg(target_os = "linux")]
{
let candidates = [
"google-chrome",
"google-chrome-stable",
"chromium-browser",
"chromium",
"brave-browser",
"brave-browser-stable",
];
for name in &candidates {
if let Ok(output) = Command::new("which").arg(name).output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}
}
}
}
#[cfg(target_os = "windows")]
{
let candidates = [
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
];
if let Ok(local) = std::env::var("LOCALAPPDATA") {
let chrome = PathBuf::from(&local).join(r"Google\Chrome\Application\chrome.exe");
if chrome.exists() {
return Some(chrome);
}
let brave =
PathBuf::from(&local).join(r"BraveSoftware\Brave-Browser\Application\brave.exe");
if brave.exists() {
return Some(brave);
}
}
for c in &candidates {
let p = PathBuf::from(c);
if p.exists() {
return Some(p);
}
}
}
// 3. Fallback: check Puppeteer / Playwright browser caches
if let Some(p) = find_puppeteer_chrome() {
return Some(p);
}
if let Some(p) = find_playwright_chromium() {
return Some(p);
}
None
}
pub fn read_devtools_active_port(user_data_dir: &Path) -> Option<(u16, String)> {
let path = user_data_dir.join("DevToolsActivePort");
let content = std::fs::read_to_string(&path).ok()?;
let mut lines = content.lines();
let port: u16 = lines.next()?.trim().parse().ok()?;
let ws_path = lines
.next()
.unwrap_or("/devtools/browser")
.trim()
.to_string();
Some((port, ws_path))
}
pub async fn auto_connect_cdp() -> Result<String, String> {
let user_data_dirs = get_chrome_user_data_dirs();
for dir in &user_data_dirs {
if let Some((port, ws_path)) = read_devtools_active_port(dir) {
// Try HTTP endpoint first (pre-M144)
if let Ok(ws_url) = discover_cdp_url("127.0.0.1", port, None).await {
return Ok(ws_url);
}
// M144+: direct WebSocket — verify the port is actually listening
// before returning, otherwise a stale DevToolsActivePort file
// (left behind after Chrome exits/crashes) produces a confusing
// "connection refused" error instead of falling through.
if is_port_reachable(port) {
let ws_url = format!("ws://127.0.0.1:{}{}", port, ws_path);
return Ok(ws_url);
}
// Port is dead — remove the stale file so future runs skip it.
let stale = dir.join("DevToolsActivePort");
let _ = std::fs::remove_file(&stale);
}
}
// Fallback: probe common ports
for port in [9222u16, 9229] {
if let Ok(ws_url) = discover_cdp_url("127.0.0.1", port, None).await {
return Ok(ws_url);
}
}
Err("No running Chrome instance found. Launch Chrome with --remote-debugging-port or use --cdp.".to_string())
}
fn is_port_reachable(port: u16) -> bool {
use std::net::TcpStream;
let addr = format!("127.0.0.1:{}", port);
TcpStream::connect_timeout(&addr.parse().unwrap(), Duration::from_millis(500)).is_ok()
}
/// Returns the default Chrome user-data directory paths for the current platform.
/// Includes Chrome, Chrome Canary, Chromium, and Brave.
pub fn get_chrome_user_data_dirs() -> Vec<PathBuf> {
let mut dirs = Vec::new();
#[cfg(target_os = "macos")]
{
if let Some(home) = dirs::home_dir() {
let base = home.join("Library/Application Support");
for name in [
"Google/Chrome",
"Google/Chrome Canary",
"Chromium",
"BraveSoftware/Brave-Browser",
] {
dirs.push(base.join(name));
}
}
}
#[cfg(target_os = "linux")]
{
if let Some(home) = dirs::home_dir() {
let config = home.join(".config");
for name in [
"google-chrome",
"google-chrome-unstable",
"chromium",
"BraveSoftware/Brave-Browser",
] {
dirs.push(config.join(name));
}
}
}
#[cfg(target_os = "windows")]
{
if let Ok(local) = std::env::var("LOCALAPPDATA") {
let base = PathBuf::from(local);
for name in [
r"Google\Chrome\User Data",
r"Google\Chrome SxS\User Data",
r"Chromium\User Data",
r"BraveSoftware\Brave-Browser\User Data",
] {
dirs.push(base.join(name));
}
}
}
dirs
}
/// Returns true if the given string looks like a Chrome profile name rather than
/// a file path. A profile name contains no `/`, `\`, or `~` characters.
pub fn is_chrome_profile_name(s: &str) -> bool {
!s.contains('/') && !s.contains('\\') && !s.contains('~')
}
/// Returns the first existing Chrome user-data directory that contains a
/// `Local State` file.
pub fn find_chrome_user_data_dir() -> Option<PathBuf> {
get_chrome_user_data_dirs()
.into_iter()
.find(|dir| dir.join("Local State").is_file())
}
/// A Chrome profile entry parsed from `Local State`.
#[derive(Debug, Clone)]
pub struct ChromeProfile {
/// The directory name (e.g., "Default", "Profile 1").
pub directory: String,
/// The user-visible display name (e.g., "Person 1").
pub name: String,
}
/// Lists all Chrome profiles found in the given user-data directory by reading
/// the `Local State` JSON file. Returns an empty vec if the file is missing,
/// malformed, or lacks the expected `profile.info_cache` key.
pub fn list_chrome_profiles(user_data_dir: &Path) -> Vec<ChromeProfile> {
let local_state_path = user_data_dir.join("Local State");
let content = match std::fs::read_to_string(&local_state_path) {
Ok(c) => c,
Err(_) => return Vec::new(),
};
let json: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(_) => return Vec::new(),
};
let info_cache = match json.get("profile").and_then(|p| p.get("info_cache")) {
Some(obj) if obj.is_object() => obj.as_object().unwrap(),
_ => return Vec::new(),
};
let mut profiles: Vec<ChromeProfile> = info_cache
.iter()
.map(|(dir_name, info)| {
let display_name = info
.get("name")
.and_then(|n| n.as_str())
.unwrap_or(dir_name)
.to_string();
ChromeProfile {
directory: dir_name.clone(),
name: display_name,
}
})
.collect();
profiles.sort_by(|a, b| a.directory.cmp(&b.directory));
profiles
}
/// Resolves a profile input string to a Chrome profile directory name using
/// three-tier matching:
/// 1. Exact directory name match
/// 2. Case-insensitive display name match (error if ambiguous)
/// 3. Case-insensitive directory name match
///
/// Returns the resolved directory name, or an error with available profiles.
pub fn resolve_chrome_profile(user_data_dir: &Path, input: &str) -> Result<String, String> {
let profiles = list_chrome_profiles(user_data_dir);
if profiles.is_empty() {
return Err(format!(
"No Chrome profiles found in {}.\n\
If you meant a directory path, use a full path (e.g., /path/to/profile).",
user_data_dir.display()
));
}
// Tier 1: exact directory name match
if let Some(p) = profiles.iter().find(|p| p.directory == input) {
return Ok(p.directory.clone());
}
// Tier 2: case-insensitive display name match
let input_lower = input.to_lowercase();
let display_matches: Vec<&ChromeProfile> = profiles
.iter()
.filter(|p| p.name.to_lowercase() == input_lower)
.collect();
match display_matches.len() {
1 => return Ok(display_matches[0].directory.clone()),
n if n > 1 => {
return Err(format!(
"Ambiguous profile name \"{}\". Multiple profiles match:\n{}\n\
Use the directory name instead.",
input,
format_profile_list(&display_matches)
));
}
_ => {}
}
// Tier 3: case-insensitive directory name match
if let Some(p) = profiles
.iter()
.find(|p| p.directory.to_lowercase() == input_lower)
{
return Ok(p.directory.clone());
}
let all_profiles: Vec<&ChromeProfile> = profiles.iter().collect();
Err(format!(
"Chrome profile \"{}\" not found. Available profiles:\n{}\n\
If you meant a directory path, use a full path (e.g., /path/to/profile).",
input,
format_profile_list(&all_profiles)
))
}
fn format_profile_list(profiles: &[&ChromeProfile]) -> String {
profiles
.iter()
.map(|p| format!(" {} ({})", p.directory, p.name))
.collect::<Vec<_>>()
.join("\n")
}
/// Directories to exclude when copying a Chrome profile. These are large
/// non-auth directories that are not needed for reusing login state.
const PROFILE_COPY_EXCLUDE_DIRS: &[&str] = &[
"Cache",
"Code Cache",
"GPUCache",
"Service Worker",
"blob_storage",
"File System",
"GCM Store",
"optimization_guide",
"ShaderCache",
"component_crx_cache",
];
/// Copies a Chrome profile subdirectory and `Local State` to a temp directory
/// with a two-level structure suitable for `--user-data-dir`. Returns the temp
/// directory path on success.
///
/// The copy is best-effort: individual file failures (e.g., `SingletonLock`)
/// are skipped with a warning. If the source profile directory is missing or
/// the temp dir cannot be created, returns an error after cleaning up.
pub fn copy_chrome_profile(
user_data_dir: &Path,
profile_directory: &str,
) -> Result<PathBuf, String> {
let temp_dir =
std::env::temp_dir().join(format!("agent-browser-profile-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&temp_dir)
.map_err(|e| format!("Failed to create temp profile dir: {}", e))?;
// Copy Local State (non-fatal if missing or unreadable)
let local_state_src = user_data_dir.join("Local State");
if let Err(e) = std::fs::copy(&local_state_src, temp_dir.join("Local State")) {
let _ = writeln!(
std::io::stderr(),
"Warning: could not copy Local State from {}: {}",
local_state_src.display(),
e
);
}
// Copy profile subdirectory
let src_profile = user_data_dir.join(profile_directory);
if !src_profile.is_dir() {
let _ = std::fs::remove_dir_all(&temp_dir);
return Err(format!(
"Profile directory not found: {}",
src_profile.display()
));
}
let dst_profile = temp_dir.join(profile_directory);
if let Err(e) = copy_dir_recursive(&src_profile, &dst_profile) {
let _ = std::fs::remove_dir_all(&temp_dir);
return Err(format!("Failed to copy profile: {}", e));
}
Ok(temp_dir)
}
/// Recursively copies a directory, skipping entries in [`PROFILE_COPY_EXCLUDE_DIRS`].
/// Individual file copy failures are logged to stderr but do not fail the operation.
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
std::fs::create_dir_all(dst)
.map_err(|e| format!("Failed to create directory {}: {}", dst.display(), e))?;
let entries = std::fs::read_dir(src)
.map_err(|e| format!("Failed to read directory {}: {}", src.display(), e))?;
for entry in entries {
let entry = match entry {
Ok(e) => e,
Err(e) => {
let _ = writeln!(
std::io::stderr(),
"Warning: failed to read entry in {}: {}",
src.display(),
e
);
continue;
}
};
let name = entry.file_name();
let name_str = name.to_string_lossy();
let src_path = entry.path();
let dst_path = dst.join(&name);
let file_type = match entry.file_type() {
Ok(ft) => ft,
Err(e) => {
let _ = writeln!(
std::io::stderr(),
"Warning: failed to get file type for {}: {}",
src_path.display(),
e
);
continue;
}
};
if file_type.is_dir() {
if PROFILE_COPY_EXCLUDE_DIRS.contains(&name_str.as_ref()) {
continue;
}
copy_dir_recursive(&src_path, &dst_path)?;
} else if let Err(e) = std::fs::copy(&src_path, &dst_path) {
let _ = writeln!(
std::io::stderr(),
"Warning: failed to copy {}: {}",
src_path.display(),
e
);
}
}
Ok(())
}
/// Returns true if Chrome's sandbox should be disabled because the environment
/// doesn't support it (containers, VMs, CI runners, running as root).
fn should_disable_sandbox(existing_args: &[String]) -> bool {
if existing_args.iter().any(|a| a == "--no-sandbox") {
return false; // already set by user
}