agentchrome 1.51.3

A CLI tool for browser automation via the Chrome DevTools Protocol
Documentation
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
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

#[cfg(unix)]
use std::os::unix::process::CommandExt;
#[cfg(windows)]
use std::os::windows::process::CommandExt;

use super::ChromeError;
use super::discovery::query_version;

/// Configuration for launching a Chrome process.
pub struct LaunchConfig {
    /// Path to the Chrome executable.
    pub executable: PathBuf,
    /// Port for Chrome's remote debugging protocol.
    pub port: u16,
    /// Whether to launch in headless mode.
    pub headless: bool,
    /// Additional command-line arguments for Chrome.
    pub extra_args: Vec<String>,
    /// User data directory. If `None`, a temporary directory is created.
    pub user_data_dir: Option<PathBuf>,
}

/// A handle to a running Chrome process.
pub struct ChromeProcess {
    child: Option<std::process::Child>,
    port: u16,
    temp_dir: Option<TempDir>,
}

/// A temporary directory that is removed on drop.
struct TempDir {
    path: PathBuf,
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

impl ChromeProcess {
    /// Returns the PID of the Chrome process.
    #[must_use]
    pub fn pid(&self) -> u32 {
        self.child.as_ref().map_or(0, std::process::Child::id)
    }

    /// Returns the remote debugging port.
    #[must_use]
    #[allow(dead_code)]
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Kill the Chrome process and clean up.
    pub fn kill(&mut self) {
        if let Some(child) = self.child.as_mut() {
            let _ = child.kill();
            let _ = child.wait();
        }
    }

    /// Detach the Chrome process so it keeps running after this handle is dropped.
    ///
    /// Returns `(pid, port)`. The caller is responsible for the process lifetime.
    #[must_use]
    pub fn detach(mut self) -> (u32, u16) {
        let pid = self.pid();
        let port = self.port;
        // Prevent process cleanup: the launched browser must outlive this
        // ChromeProcess handle after a successful connect --launch.
        if let Some(child) = self.child.take() {
            std::mem::forget(child);
        }
        // Prevent temp dir cleanup: Chrome still needs the profile directory
        // after the launching process exits.
        if let Some(temp_dir) = self.temp_dir.take() {
            std::mem::forget(temp_dir);
        }
        (pid, port)
    }
}

impl Drop for ChromeProcess {
    fn drop(&mut self) {
        self.kill();
    }
}

/// Generate a random hex suffix for temporary directory names.
///
/// Reads 8 bytes from `/dev/urandom` on Unix, falling back to a PID + address
/// combination when that is not available.
fn random_suffix() -> String {
    use std::io::Read;
    let mut buf = [0u8; 8];
    if let Ok(mut f) = std::fs::File::open("/dev/urandom")
        && f.read_exact(&mut buf).is_ok()
    {
        return hex_encode(&buf);
    }
    // Fallback: combine PID and a stack address for uniqueness
    let pid = std::process::id();
    let addr = &raw const buf as usize;
    format!("{pid:x}-{addr:x}")
}

fn hex_encode(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        use std::fmt::Write;
        let _ = write!(s, "{b:02x}");
    }
    s
}

/// Find an available TCP port on localhost.
///
/// # Errors
///
/// Returns `ChromeError::LaunchFailed` if binding fails.
pub fn find_available_port() -> Result<u16, ChromeError> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| {
        ChromeError::LaunchFailed(format!("could not bind to find a free port: {e}"))
    })?;
    let port = listener
        .local_addr()
        .map_err(|e| ChromeError::LaunchFailed(format!("could not get local address: {e}")))?
        .port();
    drop(listener);
    Ok(port)
}

/// Build the Chrome command-line arguments from a launch configuration.
fn build_chrome_args(config: &LaunchConfig, data_dir: &Path) -> Vec<String> {
    let mut args = vec![
        format!("--remote-debugging-port={}", config.port),
        format!("--user-data-dir={}", data_dir.display()),
        "--no-first-run".to_string(),
        "--no-default-browser-check".to_string(),
        "--enable-automation".to_string(),
    ];

    append_platform_launch_defaults(&mut args);

    if config.headless {
        args.push("--headless=new".to_string());
    }

    for arg in &config.extra_args {
        args.push(arg.clone());
    }

    args
}

fn append_platform_launch_defaults(args: &mut Vec<String>) {
    append_macos_launch_defaults(args);
}

#[cfg(target_os = "macos")]
fn append_macos_launch_defaults(args: &mut Vec<String>) {
    args.push("--use-mock-keychain".to_string());
    args.push("--password-store=basic".to_string());
}

#[cfg(not(target_os = "macos"))]
fn append_macos_launch_defaults(_args: &mut Vec<String>) {}

/// Configure Chrome so it is not tied to the launcher process group.
///
/// `connect --launch` is a cross-invocation command: Chrome must survive after
/// the short-lived `AgentChrome` process exits, including under harnesses that
/// clean up the launcher's process group.
fn configure_detached_process(cmd: &mut Command) {
    #[cfg(unix)]
    {
        // SAFETY: `pre_exec` runs in the child after fork and before exec.
        // The closure only calls `setsid`, an async-signal-safe libc function,
        // and returns an OS error if it fails.
        unsafe {
            cmd.pre_exec(|| {
                if libc::setsid() == -1 {
                    return Err(std::io::Error::last_os_error());
                }
                Ok(())
            });
        }
    }

    #[cfg(windows)]
    {
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
        const DETACHED_PROCESS: u32 = 0x0000_0008;
        cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);
    }

    #[cfg(not(any(unix, windows)))]
    {
        let _ = cmd;
    }
}

/// Launch a Chrome process with the given configuration.
///
/// Polls the Chrome debug endpoint until it responds or the timeout expires.
///
/// # Errors
///
/// Returns `ChromeError::LaunchFailed` if the process cannot be spawned,
/// or `ChromeError::StartupTimeout` if Chrome does not become ready in time.
pub async fn launch_chrome(
    config: LaunchConfig,
    timeout: Duration,
) -> Result<ChromeProcess, ChromeError> {
    let (data_dir, temp_dir) = if let Some(ref dir) = config.user_data_dir {
        (dir.clone(), None)
    } else {
        let dir = std::env::temp_dir().join(format!("agentchrome-{}", random_suffix()));
        std::fs::create_dir_all(&dir)?;
        let td = TempDir { path: dir.clone() };
        (dir, Some(td))
    };

    let args = build_chrome_args(&config, &data_dir);

    let mut cmd = Command::new(&config.executable);
    for arg in &args {
        cmd.arg(arg);
    }

    configure_detached_process(&mut cmd);
    cmd.stdout(Stdio::null()).stderr(Stdio::null());

    let child = cmd.spawn().map_err(|e| {
        ChromeError::LaunchFailed(format!(
            "failed to spawn {}: {e}",
            config.executable.display()
        ))
    })?;

    let mut process = ChromeProcess {
        child: Some(child),
        port: config.port,
        temp_dir,
    };

    // Poll until Chrome is ready or timeout
    let start = tokio::time::Instant::now();
    let poll_interval = Duration::from_millis(100);

    loop {
        if start.elapsed() > timeout {
            // Kill the process since we're giving up
            process.kill();
            return Err(ChromeError::StartupTimeout { port: config.port });
        }

        // Check if the child has exited unexpectedly
        if let Some(child) = process.child.as_mut()
            && let Ok(Some(status)) = child.try_wait()
        {
            return Err(ChromeError::LaunchFailed(format!(
                "Chrome exited with status {status} before becoming ready"
            )));
        }

        if query_version("127.0.0.1", config.port).await.is_ok() {
            return Ok(process);
        }

        tokio::time::sleep(poll_interval).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn find_available_port_returns_valid_port() {
        let port = find_available_port().unwrap();
        assert!(port > 0, "Expected a positive port number, got {port}");
    }

    fn default_launch_config(port: u16) -> LaunchConfig {
        LaunchConfig {
            executable: PathBuf::from("/usr/bin/chrome"),
            port,
            headless: false,
            extra_args: vec![],
            user_data_dir: None,
        }
    }

    #[test]
    fn automation_flag_is_included_on_launch() {
        let config = default_launch_config(9222);
        let data_dir = PathBuf::from("/tmp/test-data");
        let args = build_chrome_args(&config, &data_dir);
        assert!(
            args.iter().any(|a| a == "--enable-automation"),
            "Expected --enable-automation in args: {args:?}"
        );
    }

    #[test]
    fn headless_mode_includes_automation_flag() {
        let mut config = default_launch_config(9222);
        config.headless = true;
        let data_dir = PathBuf::from("/tmp/test-data");
        let args = build_chrome_args(&config, &data_dir);
        assert!(
            args.iter().any(|a| a == "--enable-automation"),
            "Expected --enable-automation in args: {args:?}"
        );
        assert!(
            args.iter().any(|a| a == "--headless=new"),
            "Expected --headless=new in args: {args:?}"
        );
    }

    #[test]
    fn extra_args_do_not_conflict_with_automation_flag() {
        let mut config = default_launch_config(9222);
        config.extra_args = vec!["--enable-automation".to_string()];
        let data_dir = PathBuf::from("/tmp/test-data");
        let args = build_chrome_args(&config, &data_dir);
        // Should contain --enable-automation (at least once) without error
        assert!(
            args.iter().any(|a| a == "--enable-automation"),
            "Expected --enable-automation in args: {args:?}"
        );
    }

    #[test]
    fn explicit_extra_args_are_preserved_after_defaults() {
        let mut config = default_launch_config(9222);
        config.extra_args = vec!["--disable-gpu".to_string()];
        let data_dir = PathBuf::from("/tmp/test-data");
        let args = build_chrome_args(&config, &data_dir);
        assert_eq!(
            args.last().map(String::as_str),
            Some("--disable-gpu"),
            "Expected explicit extra arg to remain last in args: {args:?}"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_launch_defaults_avoid_keychain_prompts() {
        let config = default_launch_config(9222);
        let data_dir = PathBuf::from("/tmp/test-data");
        let args = build_chrome_args(&config, &data_dir);
        assert!(
            args.iter().any(|a| a == "--use-mock-keychain"),
            "Expected --use-mock-keychain in args: {args:?}"
        );
        assert!(
            args.iter().any(|a| a == "--password-store=basic"),
            "Expected --password-store=basic in args: {args:?}"
        );
    }

    #[cfg(not(target_os = "macos"))]
    #[test]
    fn non_macos_launch_defaults_do_not_add_keychain_flags() {
        let config = default_launch_config(9222);
        let data_dir = PathBuf::from("/tmp/test-data");
        let args = build_chrome_args(&config, &data_dir);
        assert!(
            !args.iter().any(|a| a == "--use-mock-keychain"),
            "Did not expect --use-mock-keychain in args: {args:?}"
        );
        assert!(
            !args.iter().any(|a| a == "--password-store=basic"),
            "Did not expect --password-store=basic in args: {args:?}"
        );
    }

    #[test]
    fn detach_preserves_temp_user_data_dir() {
        let path =
            std::env::temp_dir().join(format!("agentchrome-detach-test-{}", random_suffix()));
        std::fs::create_dir_all(&path).unwrap();

        let process = ChromeProcess {
            child: None,
            port: 9222,
            temp_dir: Some(TempDir { path: path.clone() }),
        };

        let (_pid, port) = process.detach();

        assert_eq!(port, 9222);
        assert!(
            path.exists(),
            "detach must not delete Chrome's temporary user data directory"
        );

        std::fs::remove_dir_all(path).unwrap();
    }

    #[test]
    fn temp_dir_cleanup_on_drop() {
        let path = std::env::temp_dir().join("agentchrome-test-cleanup");
        std::fs::create_dir_all(&path).unwrap();
        assert!(path.exists());

        let td = TempDir { path: path.clone() };
        drop(td);

        assert!(!path.exists(), "TempDir should have been cleaned up");
    }
}