chromewright 0.2.3

Browser automation MCP server and Rust library via Chrome DevTools Protocol (CDP)
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
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
use crate::browser::config::{ConnectionOptions, LaunchOptions};
use crate::dom::{DocumentMetadata, DomTree};
use crate::error::{BrowserError, Result};
use crate::tools::{ToolContext, ToolRegistry};
use headless_chrome::{Browser, Tab};
use std::ffi::OsStr;
use std::sync::atomic::{AtomicU16, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use std::time::Instant;

const DEBUG_PORT_START: u16 = 40_000;
const DEBUG_PORT_END: u16 = 59_999;
static DEBUG_PORT_COUNTER: AtomicU16 = AtomicU16::new(DEBUG_PORT_START);

/// Wrapper for Tab and Element to maintain proper lifetime relationships
pub struct TabElement<'a> {
    pub tab: Arc<Tab>,
    pub element: headless_chrome::Element<'a>,
}

#[derive(Debug, Clone)]
pub(crate) struct MarkdownCacheEntry {
    pub document_id: String,
    pub revision: String,
    pub title: String,
    pub url: String,
    pub byline: String,
    pub excerpt: String,
    pub site_name: String,
    pub full_markdown: Arc<str>,
}

/// Browser session that manages a Chrome/Chromium instance
pub struct BrowserSession {
    /// The underlying headless_chrome Browser instance
    browser: Browser,

    /// Tool registry for executing browser automation tools
    tool_registry: ToolRegistry,

    /// Best-effort active-tab hint to avoid repeated cross-tab probing on steady-state calls.
    active_tab_hint: RwLock<Option<Arc<Tab>>>,

    /// Cache the most recent markdown extraction by document revision.
    markdown_cache: Mutex<Option<Arc<MarkdownCacheEntry>>>,
}

impl BrowserSession {
    /// Launch a new browser instance with the given options
    pub fn launch(options: LaunchOptions) -> Result<Self> {
        let launch_opts = build_launch_options(options);

        // Launch browser
        let browser =
            Browser::new(launch_opts).map_err(|e| BrowserError::LaunchFailed(e.to_string()))?;

        let initial_tab = browser
            .new_tab()
            .map_err(|e| BrowserError::LaunchFailed(format!("Failed to create tab: {}", e)))?;

        Ok(Self {
            browser,
            tool_registry: ToolRegistry::with_defaults(),
            active_tab_hint: RwLock::new(Some(initial_tab)),
            markdown_cache: Mutex::new(None),
        })
    }

    /// Connect to an existing browser instance via WebSocket
    pub fn connect(options: ConnectionOptions) -> Result<Self> {
        let browser = Browser::connect(options.ws_url)
            .map_err(|e| BrowserError::ConnectionFailed(e.to_string()))?;

        Ok(Self {
            browser,
            tool_registry: ToolRegistry::with_defaults(),
            active_tab_hint: RwLock::new(None),
            markdown_cache: Mutex::new(None),
        })
    }

    /// Launch a browser with default options
    pub fn new() -> Result<Self> {
        Self::launch(LaunchOptions::default())
    }

    /// Get the active tab
    pub fn tab(&self) -> Result<Arc<Tab>> {
        self.get_active_tab()
    }

    /// Create a new tab and set it as active
    pub fn new_tab(&mut self) -> Result<Arc<Tab>> {
        let tab = self.browser.new_tab().map_err(|e| {
            BrowserError::TabOperationFailed(format!("Failed to create tab: {}", e))
        })?;
        self.set_active_tab_hint(Some(tab.clone()))?;
        Ok(tab)
    }

    /// Get all tabs
    pub fn get_tabs(&self) -> Result<Vec<Arc<Tab>>> {
        let tabs = self
            .browser
            .get_tabs()
            .lock()
            .map_err(|e| BrowserError::TabOperationFailed(format!("Failed to get tabs: {}", e)))?
            .clone();

        Ok(tabs)
    }

    /// Get the currently active tab by checking the document visibility and focus state
    pub fn get_active_tab(&self) -> Result<Arc<Tab>> {
        if let Some(tab) = self.active_tab_hint()? {
            return Ok(tab);
        }

        let tabs = self.get_tabs()?;

        // First pass: check for both visibility and focus (strongest signal)
        for tab in &tabs {
            let result = tab.evaluate(
                "document.visibilityState === 'visible' && document.hasFocus()",
                false,
            );
            match result {
                Ok(remote_object) => {
                    if let Some(value) = remote_object.value {
                        if value.as_bool().unwrap_or(false) {
                            self.set_active_tab_hint(Some(tab.clone()))?;
                            return Ok(tab.clone());
                        }
                    }
                }
                Err(e) => {
                    log::debug!("Failed to check tab status: {}", e);
                    continue;
                }
            }
        }

        // Second pass: check just for visibility (weaker signal, but better than nothing)
        for tab in &tabs {
            let result = tab.evaluate("document.visibilityState === 'visible'", false);
            match result {
                Ok(remote_object) => {
                    if let Some(value) = remote_object.value {
                        if value.as_bool().unwrap_or(false) {
                            self.set_active_tab_hint(Some(tab.clone()))?;
                            return Ok(tab.clone());
                        }
                    }
                }
                Err(_) => continue,
            }
        }

        Err(BrowserError::TabOperationFailed(
            "No active tab found".to_string(),
        ))
    }

    /// Close the active tab
    pub fn close_active_tab(&mut self) -> Result<()> {
        let active_tab = self.tab()?;
        self.clear_active_tab_hint()?;
        active_tab
            .close(true)
            .map_err(|e| BrowserError::TabOperationFailed(format!("Failed to close tab: {}", e)))?;

        Ok(())
    }

    /// Get the underlying Browser instance
    pub fn browser(&self) -> &Browser {
        &self.browser
    }

    /// Activate the provided tab and remember it as the active-tab hint.
    pub fn activate_tab(&self, tab: &Arc<Tab>) -> Result<()> {
        tab.activate().map_err(|e| {
            BrowserError::TabOperationFailed(format!("Failed to activate tab: {}", e))
        })?;
        self.set_active_tab_hint(Some(tab.clone()))?;
        Ok(())
    }

    /// Open a new tab, navigate to the URL, wait for the initial load, and mark it active.
    pub fn open_tab(&self, url: &str) -> Result<Arc<Tab>> {
        let tab = self.browser.new_tab().map_err(|e| {
            BrowserError::TabOperationFailed(format!("Failed to create tab: {}", e))
        })?;

        tab.navigate_to(url).map_err(|e| {
            BrowserError::NavigationFailed(format!("Failed to navigate to {}: {}", url, e))
        })?;

        tab.wait_until_navigated().map_err(|e| {
            BrowserError::NavigationFailed(format!("Navigation to {} did not complete: {}", url, e))
        })?;

        self.activate_tab(&tab)?;
        Ok(tab)
    }

    /// Navigate to a URL using the active tab
    pub fn navigate(&self, url: &str) -> Result<()> {
        self.tab()?.navigate_to(url).map_err(|e| {
            BrowserError::NavigationFailed(format!("Failed to navigate to {}: {}", url, e))
        })?;

        Ok(())
    }

    /// Read document metadata from the active tab without rebuilding the full DOM snapshot.
    pub fn document_metadata(&self) -> Result<DocumentMetadata> {
        let tab = self.tab()?;
        self.document_metadata_for_tab(&tab)
    }

    /// Read document metadata from the provided tab without rebuilding the full DOM snapshot.
    pub(crate) fn document_metadata_for_tab(&self, tab: &Arc<Tab>) -> Result<DocumentMetadata> {
        DocumentMetadata::from_tab(tab)
    }

    /// Wait for navigation to complete
    pub fn wait_for_navigation(&self) -> Result<()> {
        let tab = self.tab()?;
        tab.wait_until_navigated()
            .map_err(|e| BrowserError::NavigationFailed(format!("Navigation timeout: {}", e)))?;

        self.wait_for_document_ready_with_tab(&tab, Duration::from_secs(30))?;

        Ok(())
    }

    /// Read the current document ready state from the active tab.
    pub fn document_ready_state(&self) -> Result<String> {
        let tab = self.tab()?;
        self.document_ready_state_for_tab(&tab)
    }

    fn document_ready_state_for_tab(&self, tab: &Arc<Tab>) -> Result<String> {
        let result = tab.evaluate("document.readyState", false).map_err(|e| {
            BrowserError::NavigationFailed(format!("Failed to read readyState: {}", e))
        })?;

        let ready_state = result
            .value
            .and_then(|value| value.as_str().map(str::to_string))
            .ok_or_else(|| {
                BrowserError::NavigationFailed(
                    "Browser did not return a document.readyState value".to_string(),
                )
            })?;

        Ok(ready_state)
    }

    /// Wait for the current document to reach the `complete` ready state.
    pub fn wait_for_document_ready_with_timeout(&self, timeout: Duration) -> Result<()> {
        let tab = self.tab()?;
        self.wait_for_document_ready_with_tab(&tab, timeout)
    }

    fn wait_for_document_ready_with_tab(&self, tab: &Arc<Tab>, timeout: Duration) -> Result<()> {
        let start = Instant::now();
        loop {
            let ready_state = self.document_ready_state_for_tab(tab)?;
            if ready_state == "complete" {
                return Ok(());
            }

            if start.elapsed() >= timeout {
                return Err(BrowserError::Timeout(format!(
                    "Document did not reach readyState=complete within {} ms",
                    timeout.as_millis()
                )));
            }

            std::thread::sleep(Duration::from_millis(50));
        }
    }

    fn wait_for_history_settle(
        &self,
        tab: &Arc<Tab>,
        previous_url: &str,
        timeout: Duration,
    ) -> Result<()> {
        let start = Instant::now();
        let mut observed_navigation = false;

        loop {
            let current_url = tab.get_url();
            if current_url != previous_url {
                observed_navigation = true;
            }

            let ready_state = self.document_ready_state_for_tab(tab)?;
            let elapsed = start.elapsed();
            let grace_period = Duration::from_millis(500);

            if ready_state == "complete" && (observed_navigation || elapsed >= grace_period) {
                return Ok(());
            }

            if elapsed >= timeout {
                return Err(BrowserError::Timeout(format!(
                    "History navigation did not settle within {} ms",
                    timeout.as_millis()
                )));
            }

            std::thread::sleep(Duration::from_millis(50));
        }
    }

    /// Extract the DOM tree from the active tab
    pub fn extract_dom(&self) -> Result<DomTree> {
        let tab = self.tab()?;
        DomTree::from_tab(&tab)
    }

    /// Extract the DOM tree with a custom ref prefix (for iframe handling)
    pub fn extract_dom_with_prefix(&self, prefix: &str) -> Result<DomTree> {
        let tab = self.tab()?;
        DomTree::from_tab_with_prefix(&tab, prefix)
    }

    /// Find an element by CSS selector using the provided tab
    pub fn find_element<'a>(
        &self,
        tab: &'a Arc<Tab>,
        css_selector: &str,
    ) -> Result<headless_chrome::Element<'a>> {
        tab.find_element(css_selector).map_err(|e| {
            BrowserError::ElementNotFound(format!("Element '{}' not found: {}", css_selector, e))
        })
    }

    /// Get the tool registry
    pub fn tool_registry(&self) -> &ToolRegistry {
        &self.tool_registry
    }

    /// Get mutable tool registry
    pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry {
        &mut self.tool_registry
    }

    /// Execute a tool by name
    pub fn execute_tool(
        &self,
        name: &str,
        params: serde_json::Value,
    ) -> Result<crate::tools::ToolResult> {
        let mut context = ToolContext::new(self);
        self.tool_registry.execute(name, params, &mut context)
    }

    fn active_tab_hint(&self) -> Result<Option<Arc<Tab>>> {
        Ok(self
            .active_tab_hint
            .read()
            .map_err(|e| {
                BrowserError::TabOperationFailed(format!("Failed to read active tab hint: {}", e))
            })?
            .clone())
    }

    pub(crate) fn set_active_tab_hint(&self, tab: Option<Arc<Tab>>) -> Result<()> {
        *self.active_tab_hint.write().map_err(|e| {
            BrowserError::TabOperationFailed(format!("Failed to write active tab hint: {}", e))
        })? = tab;
        Ok(())
    }

    pub(crate) fn clear_active_tab_hint(&self) -> Result<()> {
        self.set_active_tab_hint(None)
    }

    pub(crate) fn markdown_cache_entry(
        &self,
        document: &DocumentMetadata,
    ) -> Result<Option<Arc<MarkdownCacheEntry>>> {
        let guard = self
            .markdown_cache
            .lock()
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "get_markdown".to_string(),
                reason: format!("Failed to read markdown cache: {}", e),
            })?;

        Ok(guard.as_ref().and_then(|entry| {
            (entry.document_id == document.document_id && entry.revision == document.revision)
                .then_some(Arc::clone(entry))
        }))
    }

    pub(crate) fn store_markdown_cache(&self, entry: Arc<MarkdownCacheEntry>) -> Result<()> {
        *self
            .markdown_cache
            .lock()
            .map_err(|e| BrowserError::ToolExecutionFailed {
                tool: "get_markdown".to_string(),
                reason: format!("Failed to write markdown cache: {}", e),
            })? = Some(entry);
        Ok(())
    }

    /// Navigate back in browser history
    pub fn go_back(&self) -> Result<()> {
        let tab = self.tab()?;
        let previous_url = tab.get_url();
        let go_back_js = r#"
            (function() {
                window.history.back();
                return true;
            })()
        "#;

        tab.evaluate(go_back_js, false)
            .map_err(|e| BrowserError::NavigationFailed(format!("Failed to go back: {}", e)))?;
        self.wait_for_history_settle(&tab, &previous_url, Duration::from_secs(5))?;

        Ok(())
    }

    /// Navigate forward in browser history
    pub fn go_forward(&self) -> Result<()> {
        let tab = self.tab()?;
        let previous_url = tab.get_url();
        let go_forward_js = r#"
            (function() {
                window.history.forward();
                return true;
            })()
        "#;

        tab.evaluate(go_forward_js, false)
            .map_err(|e| BrowserError::NavigationFailed(format!("Failed to go forward: {}", e)))?;
        self.wait_for_history_settle(&tab, &previous_url, Duration::from_secs(5))?;

        Ok(())
    }

    /// Close the browser
    pub fn close(&self) -> Result<()> {
        // Note: The Browser struct doesn't have a public close method in headless_chrome
        // The browser will be closed when the Browser instance is dropped
        // We can close all tabs to effectively shut down
        let tabs = self.get_tabs()?;
        for tab in tabs {
            let _ = tab.close(false); // Ignore errors on individual tab closes
        }
        Ok(())
    }
}

impl Default for BrowserSession {
    fn default() -> Self {
        Self::new().expect("Failed to create default browser session")
    }
}

fn choose_debug_port() -> u16 {
    let span = DEBUG_PORT_END - DEBUG_PORT_START + 1;
    let offset = DEBUG_PORT_COUNTER.fetch_add(1, Ordering::Relaxed) % span;
    DEBUG_PORT_START + offset
}

fn build_launch_options(options: LaunchOptions) -> headless_chrome::LaunchOptions<'static> {
    let mut launch_opts = headless_chrome::LaunchOptions::default();

    // Ignore default arguments to prevent detection by anti-bot services
    launch_opts
        .ignore_default_args
        .push(OsStr::new("--enable-automation"));
    launch_opts
        .args
        .push(OsStr::new("--disable-blink-features=AutomationControlled"));

    // Keep the browser alive long enough for agent-driven sessions.
    launch_opts.idle_browser_timeout = Duration::from_secs(60 * 60);
    launch_opts.headless = options.headless;
    launch_opts.window_size = Some((options.window_width, options.window_height));
    launch_opts.port = Some(options.debug_port.unwrap_or_else(choose_debug_port));
    launch_opts.sandbox = options.sandbox;

    if let Some(path) = options.chrome_path {
        launch_opts.path = Some(path);
    }

    if let Some(dir) = options.user_data_dir {
        launch_opts.user_data_dir = Some(dir);
    }

    launch_opts
}

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

    fn launch_or_skip(result: Result<BrowserSession>) -> Option<BrowserSession> {
        match result {
            Ok(session) => Some(session),
            Err(err) if launch_error_is_environmental(&err) => {
                eprintln!("Skipping browser launch test due to environment: {}", err);
                None
            }
            Err(err) => panic!("Unexpected launch failure: {}", err),
        }
    }

    #[test]
    fn test_launch_options_builder() {
        let opts = LaunchOptions::new().headless(true).window_size(800, 600);

        assert!(opts.headless);
        assert_eq!(opts.window_width, 800);
        assert_eq!(opts.window_height, 600);
    }

    #[test]
    fn test_connection_options() {
        let opts = ConnectionOptions::new("ws://localhost:9222").timeout(5000);

        assert_eq!(opts.ws_url, "ws://localhost:9222");
        assert_eq!(opts.timeout, 5000);
    }

    #[test]
    fn test_choose_debug_port_advances_within_expected_range() {
        let first = choose_debug_port();
        let second = choose_debug_port();

        assert!((DEBUG_PORT_START..=DEBUG_PORT_END).contains(&first));
        assert!((DEBUG_PORT_START..=DEBUG_PORT_END).contains(&second));
        assert_ne!(first, second);
    }

    #[test]
    fn test_build_launch_options_maps_browser_settings() {
        let options = LaunchOptions::new()
            .headless(false)
            .window_size(1024, 768)
            .sandbox(false)
            .debug_port(45555)
            .chrome_path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into())
            .user_data_dir("/tmp/chromewright-test".into());

        let launch_opts = build_launch_options(options);

        assert!(!launch_opts.headless);
        assert_eq!(launch_opts.window_size, Some((1024, 768)));
        assert_eq!(launch_opts.port, Some(45555));
        assert!(!launch_opts.sandbox);
        assert_eq!(
            launch_opts.path.as_deref(),
            Some(std::path::Path::new(
                "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
            ))
        );
        assert_eq!(
            launch_opts.user_data_dir.as_deref(),
            Some(std::path::Path::new("/tmp/chromewright-test"))
        );
        assert_eq!(
            launch_opts.idle_browser_timeout,
            Duration::from_secs(60 * 60)
        );
        assert!(
            launch_opts
                .ignore_default_args
                .iter()
                .any(|arg| *arg == OsStr::new("--enable-automation"))
        );
        assert!(
            launch_opts
                .args
                .iter()
                .any(|arg| { *arg == OsStr::new("--disable-blink-features=AutomationControlled") })
        );
    }

    #[test]
    fn test_build_launch_options_chooses_debug_port_when_missing() {
        let launch_opts = build_launch_options(LaunchOptions::new());
        let port = launch_opts.port.expect("port should be assigned");

        assert!((DEBUG_PORT_START..=DEBUG_PORT_END).contains(&port));
    }

    #[test]
    #[ignore]
    fn test_get_active_tab() {
        let Some(session) =
            launch_or_skip(BrowserSession::launch(LaunchOptions::new().headless(true)))
        else {
            return;
        };

        let tab = session.get_active_tab();
        assert!(tab.is_ok());
    }

    // Integration tests (require Chrome to be installed)
    #[test]
    #[ignore] // Ignore by default, run with: cargo test -- --ignored
    fn test_launch_browser() {
        let Some(_session) =
            launch_or_skip(BrowserSession::launch(LaunchOptions::new().headless(true)))
        else {
            return;
        };
    }

    #[test]
    #[ignore]
    fn test_navigate() {
        let Some(session) =
            launch_or_skip(BrowserSession::launch(LaunchOptions::new().headless(true)))
        else {
            return;
        };

        let result = session.navigate("about:blank");
        assert!(result.is_ok());
    }

    #[test]
    #[ignore]
    fn test_new_tab() {
        let Some(mut session) =
            launch_or_skip(BrowserSession::launch(LaunchOptions::new().headless(true)))
        else {
            return;
        };

        let result = session.new_tab();
        assert!(result.is_ok());

        let tabs = session.get_tabs().expect("Failed to get tabs");
        assert!(tabs.len() >= 2);
    }
}