Skip to main content

adk_browser/
session.rs

1//! Browser session management wrapping thirtyfour WebDriver.
2
3use crate::config::{BrowserConfig, BrowserType};
4use crate::escape::escape_js_string;
5use adk_core::{AdkError, Result};
6use std::sync::Arc;
7use std::time::Duration;
8use thirtyfour::common::print::{PrintOrientation, PrintParameters};
9use thirtyfour::prelude::*;
10use tokio::sync::RwLock;
11
12/// State information about an element.
13#[derive(Debug, Clone)]
14pub struct ElementState {
15    /// Whether the element is displayed (visible).
16    pub is_displayed: bool,
17    /// Whether the element is enabled (not disabled).
18    pub is_enabled: bool,
19    /// Whether the element is selected (for checkboxes, radio buttons, options).
20    pub is_selected: bool,
21    /// Whether the element is clickable (displayed and enabled).
22    pub is_clickable: bool,
23}
24
25/// A browser session that wraps thirtyfour's WebDriver.
26///
27/// This is the core abstraction for browser automation in ADK.
28/// It can be shared across multiple tools via `Arc<BrowserSession>`.
29pub struct BrowserSession {
30    driver: RwLock<Option<WebDriver>>,
31    config: BrowserConfig,
32}
33
34impl BrowserSession {
35    /// Create a new browser session with the given configuration.
36    ///
37    /// Note: This does not start the browser immediately.
38    /// Call `start()` to initialize the WebDriver connection.
39    pub fn new(config: BrowserConfig) -> Self {
40        Self { driver: RwLock::new(None), config }
41    }
42
43    /// Create a browser session with default configuration.
44    pub fn with_defaults() -> Self {
45        Self::new(BrowserConfig::default())
46    }
47
48    /// Start the browser session, replacing a WebDriver connection that no longer responds.
49    ///
50    /// An existing session that answers a `title` request is kept. One that does not is
51    /// dropped, which quits it, and a new session is created from the configuration.
52    ///
53    /// # Errors
54    ///
55    /// Returns an error when the capabilities cannot be built, the WebDriver server refuses
56    /// the session, or a timeout or viewport setting is rejected.
57    pub async fn start(&self) -> Result<()> {
58        let mut driver_guard = self.driver.write().await;
59
60        if let Some(driver) = driver_guard.as_ref()
61            && driver.title().await.is_ok()
62        {
63            return Ok(());
64        }
65        *driver_guard = None;
66
67        let caps = self.build_capabilities()?;
68        let driver = WebDriver::new(&self.config.webdriver_url, caps)
69            .await
70            .map_err(|e| AdkError::tool(format!("Failed to start browser: {}", e)))?;
71
72        // Set timeouts
73        driver
74            .set_page_load_timeout(Duration::from_secs(self.config.page_load_timeout_secs))
75            .await
76            .map_err(|e| AdkError::tool(format!("Failed to set page load timeout: {}", e)))?;
77
78        driver
79            .set_script_timeout(Duration::from_secs(self.config.script_timeout_secs))
80            .await
81            .map_err(|e| AdkError::tool(format!("Failed to set script timeout: {}", e)))?;
82
83        driver
84            .set_implicit_wait_timeout(Duration::from_secs(self.config.implicit_wait_secs))
85            .await
86            .map_err(|e| AdkError::tool(format!("Failed to set implicit wait: {}", e)))?;
87
88        // Set viewport size
89        driver
90            .set_window_rect(0, 0, self.config.viewport_width, self.config.viewport_height)
91            .await
92            .map_err(|e| AdkError::tool(format!("Failed to set viewport: {}", e)))?;
93
94        *driver_guard = Some(driver);
95        Ok(())
96    }
97
98    /// Stop the browser session.
99    pub async fn stop(&self) -> Result<()> {
100        let mut driver_guard = self.driver.write().await;
101
102        if let Some(driver) = driver_guard.take() {
103            driver
104                .quit()
105                .await
106                .map_err(|e| AdkError::tool(format!("Failed to quit browser: {}", e)))?;
107        }
108
109        Ok(())
110    }
111
112    /// Check if the session is active by verifying the WebDriver connection is alive.
113    pub async fn is_active(&self) -> bool {
114        let driver_guard = self.driver.read().await;
115        if let Some(ref driver) = *driver_guard {
116            // Actually ping the session to verify it's alive
117            driver.title().await.is_ok()
118        } else {
119            false
120        }
121    }
122
123    /// Ensure the browser session is started, reconnecting if the session died.
124    ///
125    /// Call this instead of checking `is_active()` manually. A session that exists but no
126    /// longer responds is recreated, unless [`BrowserConfig::require_explicit_start`] is
127    /// set, in which case the host calls [`start`](Self::start) itself.
128    ///
129    /// # Errors
130    ///
131    /// Returns an error when the session is not running and `require_explicit_start` is
132    /// set, or when starting a session fails.
133    pub async fn ensure_started(&self) -> Result<()> {
134        {
135            let driver_guard = self.driver.read().await;
136            if let Some(ref driver) = *driver_guard
137                && driver.title().await.is_ok()
138            {
139                return Ok(());
140            }
141        }
142        if self.config.require_explicit_start {
143            return Err(AdkError::tool(
144                "browser session is not running and `require_explicit_start` is set; call \
145                 `BrowserSession::start()` to start or replace it",
146            ));
147        }
148        // `start` re-checks liveness under the write lock and replaces the session there, so
149        // two callers recovering at once cannot discard a session the other just created.
150        self.start().await
151    }
152
153    /// Internal: get a live WebDriver handle, auto-starting if needed.
154    /// All public methods that access the WebDriver MUST go through this.
155    ///
156    /// Returns a cloned WebDriver handle (cheap — WebDriver is Arc-based internally).
157    /// The RwLock is NOT held across the caller's WebDriver operations.
158    async fn live_driver(&self) -> Result<WebDriver> {
159        self.ensure_started().await?;
160
161        let guard = self.driver.read().await;
162        guard.clone().ok_or_else(|| {
163            AdkError::tool("Failed to start browser session: driver is None after ensure_started()")
164        })
165    }
166
167    /// A live WebDriver handle, starting the session when needed.
168    pub(crate) async fn driver(&self) -> Result<WebDriver> {
169        self.live_driver().await
170    }
171
172    /// The WebDriver handle of a running session, without starting one or checking it
173    /// responds. Watchers such as [`frames`](Self::frames) use it so that watching never
174    /// starts a browser.
175    pub(crate) async fn running_driver(&self) -> Option<WebDriver> {
176        self.driver.read().await.clone()
177    }
178
179    /// Get a snapshot of the current page context (url, title, truncated body text).
180    ///
181    /// Useful for returning page state after interaction tools.
182    pub async fn page_context(&self) -> Result<serde_json::Value> {
183        let url = self.current_url().await.unwrap_or_default();
184        let title = self.title().await.unwrap_or_default();
185
186        // Get truncated visible text (first 2000 chars of body)
187        let page_text = self
188            .execute_script(
189                "return (document.body && document.body.innerText || '').substring(0, 2000);",
190            )
191            .await
192            .ok()
193            .and_then(|v| v.as_str().map(|s| s.to_string()))
194            .unwrap_or_default();
195
196        Ok(serde_json::json!({
197            "url": url,
198            "title": title,
199            "page_text": page_text
200        }))
201    }
202
203    /// Get the configuration.
204    pub fn config(&self) -> &BrowserConfig {
205        &self.config
206    }
207
208    /// Navigate to a URL.
209    pub async fn navigate(&self, url: &str) -> Result<()> {
210        let driver = self.live_driver().await?;
211
212        driver.goto(url).await.map_err(|e| AdkError::tool(format!("Navigation failed: {}", e)))?;
213
214        Ok(())
215    }
216
217    /// Get the current URL.
218    pub async fn current_url(&self) -> Result<String> {
219        let driver = self.live_driver().await?;
220
221        driver
222            .current_url()
223            .await
224            .map(|u| u.to_string())
225            .map_err(|e| AdkError::tool(format!("Failed to get URL: {}", e)))
226    }
227
228    /// Get the page title.
229    pub async fn title(&self) -> Result<String> {
230        let driver = self.live_driver().await?;
231
232        driver.title().await.map_err(|e| AdkError::tool(format!("Failed to get title: {}", e)))
233    }
234
235    /// Find an element by CSS selector.
236    pub async fn find_element(&self, selector: &str) -> Result<WebElement> {
237        let driver = self.live_driver().await?;
238
239        driver
240            .find(By::Css(selector))
241            .await
242            .map_err(|e| AdkError::tool(format!("Element not found '{}': {}", selector, e)))
243    }
244
245    /// Find multiple elements by CSS selector.
246    pub async fn find_elements(&self, selector: &str) -> Result<Vec<WebElement>> {
247        let driver = self.live_driver().await?;
248
249        driver
250            .find_all(By::Css(selector))
251            .await
252            .map_err(|e| AdkError::tool(format!("Elements query failed '{}': {}", selector, e)))
253    }
254
255    /// Find element by XPath.
256    pub async fn find_by_xpath(&self, xpath: &str) -> Result<WebElement> {
257        let driver = self.live_driver().await?;
258
259        driver
260            .find(By::XPath(xpath))
261            .await
262            .map_err(|e| AdkError::tool(format!("XPath not found '{}': {}", xpath, e)))
263    }
264
265    /// Click an element by selector.
266    pub async fn click(&self, selector: &str) -> Result<()> {
267        let element = self.find_element(selector).await?;
268        element
269            .click()
270            .await
271            .map_err(|e| AdkError::tool(format!("Click failed on '{}': {}", selector, e)))
272    }
273
274    /// Type text into an element.
275    pub async fn type_text(&self, selector: &str, text: &str) -> Result<()> {
276        let element = self.find_element(selector).await?;
277        element
278            .send_keys(text)
279            .await
280            .map_err(|e| AdkError::tool(format!("Type failed on '{}': {}", selector, e)))
281    }
282
283    /// Clear an input field.
284    pub async fn clear(&self, selector: &str) -> Result<()> {
285        let element = self.find_element(selector).await?;
286        element
287            .clear()
288            .await
289            .map_err(|e| AdkError::tool(format!("Clear failed on '{}': {}", selector, e)))
290    }
291
292    /// Get text content of an element.
293    pub async fn get_text(&self, selector: &str) -> Result<String> {
294        let element = self.find_element(selector).await?;
295        element
296            .text()
297            .await
298            .map_err(|e| AdkError::tool(format!("Get text failed on '{}': {}", selector, e)))
299    }
300
301    /// Get an attribute value.
302    pub async fn get_attribute(&self, selector: &str, attribute: &str) -> Result<Option<String>> {
303        let element = self.find_element(selector).await?;
304        element
305            .attr(attribute)
306            .await
307            .map_err(|e| AdkError::tool(format!("Get attribute failed: {}", e)))
308    }
309
310    /// Take a screenshot (returns base64-encoded PNG).
311    pub async fn screenshot(&self) -> Result<String> {
312        let driver = self.live_driver().await?;
313
314        let screenshot = driver
315            .screenshot_as_png_base64()
316            .await
317            .map_err(|e| AdkError::tool(format!("Screenshot failed: {}", e)))?;
318
319        Ok(screenshot)
320    }
321
322    /// Take a screenshot of a specific element.
323    pub async fn screenshot_element(&self, selector: &str) -> Result<String> {
324        let element = self.find_element(selector).await?;
325        let screenshot = element
326            .screenshot_as_png_base64()
327            .await
328            .map_err(|e| AdkError::tool(format!("Element screenshot failed: {}", e)))?;
329
330        Ok(screenshot)
331    }
332
333    /// Execute JavaScript and return result.
334    pub async fn execute_script(&self, script: &str) -> Result<serde_json::Value> {
335        let driver = self.live_driver().await?;
336
337        let result = driver
338            .execute(script, vec![])
339            .await
340            .map_err(|e| AdkError::tool(format!("Script execution failed: {}", e)))?;
341
342        // thirtyfour's ScriptRet provides .json() which returns &Value directly
343        Ok(result.json().clone())
344    }
345
346    /// Execute async JavaScript and return result.
347    pub async fn execute_async_script(&self, script: &str) -> Result<serde_json::Value> {
348        let driver = self.live_driver().await?;
349
350        let result = driver
351            .execute_async(script, vec![])
352            .await
353            .map_err(|e| AdkError::tool(format!("Async script failed: {}", e)))?;
354
355        Ok(result.json().clone())
356    }
357
358    /// Wait for an element to be present.
359    pub async fn wait_for_element(&self, selector: &str, timeout_secs: u64) -> Result<WebElement> {
360        let driver = self.live_driver().await?;
361
362        driver
363            .query(By::Css(selector))
364            .wait(Duration::from_secs(timeout_secs), Duration::from_millis(100))
365            .first()
366            .await
367            .map_err(|e| {
368                AdkError::tool(format!(
369                    "Timeout waiting for '{}' after {}s: {}",
370                    selector, timeout_secs, e
371                ))
372            })
373    }
374
375    /// Wait for an element to be clickable.
376    pub async fn wait_for_clickable(
377        &self,
378        selector: &str,
379        timeout_secs: u64,
380    ) -> Result<WebElement> {
381        let driver = self.live_driver().await?;
382
383        driver
384            .query(By::Css(selector))
385            .wait(Duration::from_secs(timeout_secs), Duration::from_millis(100))
386            .and_clickable()
387            .first()
388            .await
389            .map_err(|e| {
390                AdkError::tool(format!("Timeout waiting for clickable '{}': {}", selector, e))
391            })
392    }
393
394    /// Get page source HTML.
395    pub async fn page_source(&self) -> Result<String> {
396        let driver = self.live_driver().await?;
397
398        driver
399            .source()
400            .await
401            .map_err(|e| AdkError::tool(format!("Failed to get page source: {}", e)))
402    }
403
404    /// Go back in history.
405    pub async fn back(&self) -> Result<()> {
406        let driver = self.live_driver().await?;
407
408        driver.back().await.map_err(|e| AdkError::tool(format!("Back navigation failed: {}", e)))
409    }
410
411    /// Go forward in history.
412    pub async fn forward(&self) -> Result<()> {
413        let driver = self.live_driver().await?;
414
415        driver
416            .forward()
417            .await
418            .map_err(|e| AdkError::tool(format!("Forward navigation failed: {}", e)))
419    }
420
421    /// Refresh the current page.
422    pub async fn refresh(&self) -> Result<()> {
423        let driver = self.live_driver().await?;
424
425        driver.refresh().await.map_err(|e| AdkError::tool(format!("Refresh failed: {}", e)))
426    }
427
428    // =========================================================================
429    // Cookie Management
430    // =========================================================================
431
432    /// Get all cookies.
433    pub async fn get_all_cookies(&self) -> Result<Vec<serde_json::Value>> {
434        let driver = self.live_driver().await?;
435
436        let cookies = driver
437            .get_all_cookies()
438            .await
439            .map_err(|e| AdkError::tool(format!("Failed to get cookies: {}", e)))?;
440
441        Ok(cookies
442            .into_iter()
443            .map(|c| {
444                serde_json::json!({
445                    "name": c.name,
446                    "value": c.value,
447                    "domain": c.domain,
448                    "path": c.path,
449                    "secure": c.secure,
450                })
451            })
452            .collect())
453    }
454
455    /// Get a cookie by name.
456    pub async fn get_cookie(&self, name: &str) -> Result<serde_json::Value> {
457        let driver = self.live_driver().await?;
458
459        let cookie = driver
460            .get_named_cookie(name)
461            .await
462            .map_err(|e| AdkError::tool(format!("Failed to get cookie '{}': {}", name, e)))?;
463
464        Ok(serde_json::json!({
465            "name": cookie.name,
466            "value": cookie.value,
467            "domain": cookie.domain,
468            "path": cookie.path,
469            "secure": cookie.secure,
470        }))
471    }
472
473    /// Add a cookie.
474    #[allow(clippy::too_many_arguments)]
475    pub async fn add_cookie(
476        &self,
477        name: &str,
478        value: &str,
479        domain: Option<&str>,
480        path: Option<&str>,
481        secure: Option<bool>,
482        expiry: Option<i64>,
483    ) -> Result<()> {
484        let driver = self.live_driver().await?;
485
486        let mut cookie = thirtyfour::Cookie::new(name, value);
487        if let Some(d) = domain {
488            cookie.set_domain(d);
489        }
490        if let Some(p) = path {
491            cookie.set_path(p);
492        }
493        if let Some(s) = secure {
494            cookie.set_secure(s);
495        }
496        if let Some(exp) = expiry {
497            // thirtyfour Cookie expiry expects seconds since epoch
498            cookie.set_expiry(exp);
499        }
500
501        driver
502            .add_cookie(cookie)
503            .await
504            .map_err(|e| AdkError::tool(format!("Failed to add cookie: {e}")))
505    }
506
507    /// Delete a cookie.
508    pub async fn delete_cookie(&self, name: &str) -> Result<()> {
509        let driver = self.live_driver().await?;
510
511        driver
512            .delete_cookie(name)
513            .await
514            .map_err(|e| AdkError::tool(format!("Failed to delete cookie: {}", e)))
515    }
516
517    /// Delete all cookies.
518    pub async fn delete_all_cookies(&self) -> Result<()> {
519        let driver = self.live_driver().await?;
520
521        driver
522            .delete_all_cookies()
523            .await
524            .map_err(|e| AdkError::tool(format!("Failed to delete all cookies: {}", e)))
525    }
526
527    // =========================================================================
528    // Window Management
529    // =========================================================================
530
531    /// List all windows/tabs.
532    pub async fn list_windows(&self) -> Result<(Vec<String>, String)> {
533        let driver = self.live_driver().await?;
534
535        let windows = driver
536            .windows()
537            .await
538            .map_err(|e| AdkError::tool(format!("Failed to get windows: {}", e)))?;
539
540        let current = driver
541            .window()
542            .await
543            .map_err(|e| AdkError::tool(format!("Failed to get current window: {}", e)))?;
544
545        Ok((windows.into_iter().map(|w| w.to_string()).collect(), current.to_string()))
546    }
547
548    /// Open a new tab.
549    pub async fn new_tab(&self) -> Result<String> {
550        let driver = self.live_driver().await?;
551
552        let handle = driver
553            .new_tab()
554            .await
555            .map_err(|e| AdkError::tool(format!("Failed to open new tab: {}", e)))?;
556
557        Ok(handle.to_string())
558    }
559
560    /// Open a new window.
561    pub async fn new_window(&self) -> Result<String> {
562        let driver = self.live_driver().await?;
563
564        let handle = driver
565            .new_window()
566            .await
567            .map_err(|e| AdkError::tool(format!("Failed to open new window: {}", e)))?;
568
569        Ok(handle.to_string())
570    }
571
572    /// Switch to a window by handle.
573    pub async fn switch_to_window(&self, handle: &str) -> Result<()> {
574        let driver = self.live_driver().await?;
575
576        let window_handle = thirtyfour::WindowHandle::from(handle.to_string());
577        driver
578            .switch_to_window(window_handle)
579            .await
580            .map_err(|e| AdkError::tool(format!("Failed to switch window: {}", e)))
581    }
582
583    /// Close the current window.
584    pub async fn close_window(&self) -> Result<()> {
585        let driver = self.live_driver().await?;
586
587        driver
588            .close_window()
589            .await
590            .map_err(|e| AdkError::tool(format!("Failed to close window: {}", e)))
591    }
592
593    /// Maximize window.
594    pub async fn maximize_window(&self) -> Result<()> {
595        let driver = self.live_driver().await?;
596
597        driver
598            .maximize_window()
599            .await
600            .map_err(|e| AdkError::tool(format!("Failed to maximize window: {}", e)))
601    }
602
603    /// Minimize window.
604    pub async fn minimize_window(&self) -> Result<()> {
605        let driver = self.live_driver().await?;
606
607        driver
608            .minimize_window()
609            .await
610            .map_err(|e| AdkError::tool(format!("Failed to minimize window: {}", e)))
611    }
612
613    /// Set window size and position.
614    pub async fn set_window_rect(&self, x: i32, y: i32, width: u32, height: u32) -> Result<()> {
615        let driver = self.live_driver().await?;
616
617        driver
618            .set_window_rect(x as i64, y as i64, width, height)
619            .await
620            .map_err(|e| AdkError::tool(format!("Failed to set window rect: {}", e)))
621    }
622
623    // =========================================================================
624    // Frame Management
625    // =========================================================================
626
627    /// Switch to frame by index.
628    pub async fn switch_to_frame_by_index(&self, index: u16) -> Result<()> {
629        let driver = self.live_driver().await?;
630
631        driver
632            .enter_frame(index)
633            .await
634            .map_err(|e| AdkError::tool(format!("Failed to switch to frame {}: {}", index, e)))
635    }
636
637    /// Switch to frame by selector.
638    pub async fn switch_to_frame_by_selector(&self, selector: &str) -> Result<()> {
639        let element = self.find_element(selector).await?;
640
641        element
642            .enter_frame()
643            .await
644            .map_err(|e| AdkError::tool(format!("Failed to switch to frame: {}", e)))
645    }
646
647    /// Switch to parent frame.
648    pub async fn switch_to_parent_frame(&self) -> Result<()> {
649        let driver = self.live_driver().await?;
650
651        driver
652            .enter_parent_frame()
653            .await
654            .map_err(|e| AdkError::tool(format!("Failed to switch to parent frame: {}", e)))
655    }
656
657    /// Switch to default content.
658    pub async fn switch_to_default_content(&self) -> Result<()> {
659        let driver = self.live_driver().await?;
660
661        driver
662            .enter_default_frame()
663            .await
664            .map_err(|e| AdkError::tool(format!("Failed to switch to default content: {}", e)))
665    }
666
667    // =========================================================================
668    // Advanced Actions
669    // =========================================================================
670
671    /// Drag and drop.
672    pub async fn drag_and_drop(&self, source_selector: &str, target_selector: &str) -> Result<()> {
673        let source = self.find_element(source_selector).await?;
674        let target = self.find_element(target_selector).await?;
675
676        // Use JavaScript-based drag and drop for broader compatibility
677        source
678            .js_drag_to(&target)
679            .await
680            .map_err(|e| AdkError::tool(format!("Drag and drop failed: {}", e)))
681    }
682
683    /// Right-click (context click).
684    pub async fn right_click(&self, selector: &str) -> Result<()> {
685        let escaped = escape_js_string(selector);
686        let script = format!(
687            r#"
688            var element = document.querySelector('{escaped}');
689            if (element) {{
690                var event = new MouseEvent('contextmenu', {{
691                    'view': window,
692                    'bubbles': true,
693                    'cancelable': true
694                }});
695                element.dispatchEvent(event);
696                return true;
697            }}
698            return false;
699            "#,
700        );
701
702        let result = self.execute_script(&script).await?;
703        if result.as_bool() != Some(true) {
704            return Err(AdkError::tool(format!("Element not found: {}", selector)));
705        }
706        Ok(())
707    }
708
709    /// Focus an element.
710    pub async fn focus_element(&self, selector: &str) -> Result<()> {
711        let element = self.find_element(selector).await?;
712        element.focus().await.map_err(|e| AdkError::tool(format!("Focus failed: {}", e)))
713    }
714
715    /// Get element state.
716    pub async fn get_element_state(&self, selector: &str) -> Result<ElementState> {
717        let element = self.find_element(selector).await?;
718
719        let is_displayed = element.is_displayed().await.unwrap_or(false);
720        let is_enabled = element.is_enabled().await.unwrap_or(false);
721        let is_selected = element.is_selected().await.unwrap_or(false);
722        let is_clickable = element.is_clickable().await.unwrap_or(false);
723
724        Ok(ElementState { is_displayed, is_enabled, is_selected, is_clickable })
725    }
726
727    /// Press a key, optionally with modifier keys (Ctrl, Alt, Shift, Meta).
728    pub async fn press_key(
729        &self,
730        key: &str,
731        selector: Option<&str>,
732        modifiers: &[&str],
733    ) -> Result<()> {
734        // Map modifier names to WebDriver key codes
735        let modifier_codes: Vec<&str> = modifiers
736            .iter()
737            .filter_map(|m| match m.to_lowercase().as_str() {
738                "ctrl" | "control" => Some("\u{E009}"),
739                "alt" => Some("\u{E00A}"),
740                "shift" => Some("\u{E008}"),
741                "meta" | "command" | "cmd" => Some("\u{E03D}"),
742                _ => None,
743            })
744            .collect();
745
746        let key_str = match key.to_lowercase().as_str() {
747            "enter" => "\u{E007}",
748            "tab" => "\u{E004}",
749            "escape" | "esc" => "\u{E00C}",
750            "backspace" => "\u{E003}",
751            "delete" => "\u{E017}",
752            "arrowup" | "up" => "\u{E013}",
753            "arrowdown" | "down" => "\u{E015}",
754            "arrowleft" | "left" => "\u{E012}",
755            "arrowright" | "right" => "\u{E014}",
756            "home" => "\u{E011}",
757            "end" => "\u{E010}",
758            "pageup" => "\u{E00E}",
759            "pagedown" => "\u{E00F}",
760            "space" => " ",
761            _ => key,
762        };
763
764        // Build the full key sequence: modifiers down + key + modifiers up
765        let mut key_sequence = String::new();
766        for code in &modifier_codes {
767            key_sequence.push_str(code);
768        }
769        key_sequence.push_str(key_str);
770        // Release modifiers in reverse order
771        for code in modifier_codes.iter().rev() {
772            key_sequence.push_str(code);
773        }
774
775        if let Some(sel) = selector {
776            let element = self.find_element(sel).await?;
777            element
778                .send_keys(&key_sequence)
779                .await
780                .map_err(|e| AdkError::tool(format!("Key press failed: {e}")))?;
781        } else {
782            // Send to active element via WebDriver
783            let driver = self.live_driver().await?;
784
785            let active = driver
786                .active_element()
787                .await
788                .map_err(|e| AdkError::tool(format!("No active element: {e}")))?;
789            active
790                .send_keys(&key_sequence)
791                .await
792                .map_err(|e| AdkError::tool(format!("Key press failed: {e}")))?;
793        }
794
795        Ok(())
796    }
797
798    /// Upload a file.
799    pub async fn upload_file(&self, selector: &str, file_path: &str) -> Result<()> {
800        let element = self.find_element(selector).await?;
801        element
802            .send_keys(file_path)
803            .await
804            .map_err(|e| AdkError::tool(format!("File upload failed: {}", e)))
805    }
806
807    /// Print page to PDF.
808    pub async fn print_to_pdf(&self, landscape: bool, scale: f64) -> Result<String> {
809        let driver = self.live_driver().await?;
810
811        let params = PrintParameters {
812            orientation: if landscape {
813                PrintOrientation::Landscape
814            } else {
815                PrintOrientation::Portrait
816            },
817            scale,
818            ..Default::default()
819        };
820
821        driver
822            .print_page_base64(params)
823            .await
824            .map_err(|e| AdkError::tool(format!("Print to PDF failed: {}", e)))
825    }
826
827    /// Build browser capabilities based on configuration.
828    fn build_capabilities(&self) -> Result<Capabilities> {
829        if !self.config.chrome_options.is_empty() && self.config.browser != BrowserType::Chrome {
830            tracing::warn!(
831                browser = ?self.config.browser,
832                "chrome_options apply to Chrome only and are ignored for this browser"
833            );
834        }
835        let caps = match self.config.browser {
836            BrowserType::Chrome => {
837                let mut caps = DesiredCapabilities::chrome();
838                if self.config.headless {
839                    caps.add_arg("--headless=new").map_err(|e| {
840                        AdkError::tool(format!("Failed to add headless arg: {}", e))
841                    })?;
842                }
843                caps.add_arg("--disable-dev-shm-usage")
844                    .map_err(|e| AdkError::tool(format!("Failed to add disable-dev-shm: {}", e)))?;
845
846                if let Some(ref ua) = self.config.user_agent {
847                    caps.add_arg(&format!("--user-agent={}", ua))
848                        .map_err(|e| AdkError::tool(format!("Failed to add user-agent: {}", e)))?;
849                }
850
851                for arg in &self.config.browser_args {
852                    caps.add_arg(arg).map_err(|e| {
853                        AdkError::tool(format!("Failed to add arg '{}': {}", arg, e))
854                    })?;
855                }
856
857                for (name, value) in &self.config.chrome_options {
858                    // `add_experimental_option` replaces the whole key, so an `args` entry
859                    // would silently drop the headless, shm, user-agent and `browser_args`
860                    // flags above and could reintroduce `--no-sandbox` unnoticed.
861                    if name == "args" {
862                        return Err(AdkError::tool(
863                            "chrome_options cannot set `args`; add command-line flags with \
864                             `BrowserConfig::add_arg` or `browser_args` instead",
865                        ));
866                    }
867                    caps.add_experimental_option(name, value.clone()).map_err(|error| {
868                        AdkError::tool(format!("Invalid Chrome option: {error}"))
869                    })?;
870                }
871                caps.into()
872            }
873            BrowserType::Firefox => {
874                let mut caps = DesiredCapabilities::firefox();
875                if self.config.headless {
876                    caps.add_arg("-headless")
877                        .map_err(|e| AdkError::tool(format!("Failed to add headless: {}", e)))?;
878                }
879                caps.into()
880            }
881            BrowserType::Safari => DesiredCapabilities::safari().into(),
882            BrowserType::Edge => {
883                let mut caps = DesiredCapabilities::edge();
884                if self.config.headless {
885                    caps.add_arg("--headless")
886                        .map_err(|e| AdkError::tool(format!("Failed to add headless: {}", e)))?;
887                }
888                caps.into()
889            }
890        };
891
892        Ok(caps)
893    }
894}
895
896impl Drop for BrowserSession {
897    fn drop(&mut self) {
898        // Note: Can't do async cleanup in Drop, but thirtyfour handles this gracefully
899        tracing::debug!("BrowserSession dropped");
900    }
901}
902
903/// Create a shared browser session.
904pub fn shared_session(config: BrowserConfig) -> Arc<BrowserSession> {
905    Arc::new(BrowserSession::new(config))
906}
907
908#[cfg(test)]
909mod tests {
910    use super::*;
911
912    #[test]
913    fn test_session_creation() {
914        let session = BrowserSession::with_defaults();
915        assert!(!session.config().headless || session.config().headless); // Always true, just testing creation
916    }
917
918    #[tokio::test]
919    async fn test_session_not_started() {
920        // Use a bogus WebDriver URL so ensure_started's auto-start attempt fails
921        let config = BrowserConfig::new().webdriver_url("http://127.0.0.1:1");
922        let session = BrowserSession::new(config);
923        assert!(!session.is_active().await);
924
925        // navigate() calls live_driver() → ensure_started() → start(),
926        // which fails because the WebDriver is unreachable.
927        let result = session.navigate("https://example.com").await;
928        assert!(result.is_err());
929    }
930
931    #[test]
932    fn test_build_capabilities_chrome_headless() {
933        let config = BrowserConfig::new().headless(true);
934        let session = BrowserSession::new(config);
935        let caps = session.build_capabilities();
936        assert!(caps.is_ok());
937    }
938
939    #[test]
940    fn test_build_capabilities_firefox() {
941        let config = BrowserConfig::new().browser(BrowserType::Firefox);
942        let session = BrowserSession::new(config);
943        let caps = session.build_capabilities();
944        assert!(caps.is_ok());
945    }
946
947    #[test]
948    fn test_build_capabilities_safari() {
949        let config = BrowserConfig::new().browser(BrowserType::Safari);
950        let session = BrowserSession::new(config);
951        let caps = session.build_capabilities();
952        assert!(caps.is_ok());
953    }
954
955    #[test]
956    fn test_build_capabilities_edge() {
957        let config = BrowserConfig::new().browser(BrowserType::Edge);
958        let session = BrowserSession::new(config);
959        let caps = session.build_capabilities();
960        assert!(caps.is_ok());
961    }
962
963    #[test]
964    fn test_build_capabilities_with_user_agent() {
965        let config = BrowserConfig::new().user_agent("CustomAgent/1.0");
966        let session = BrowserSession::new(config);
967        let caps = session.build_capabilities();
968        assert!(caps.is_ok());
969    }
970
971    #[test]
972    fn test_build_capabilities_with_extra_args() {
973        let config = BrowserConfig::new().add_arg("--disable-gpu").add_arg("--window-size=800,600");
974        let session = BrowserSession::new(config);
975        let caps = session.build_capabilities();
976        assert!(caps.is_ok());
977    }
978    #[tokio::test]
979    async fn explicit_start_does_not_connect_implicitly() {
980        let config = BrowserConfig { require_explicit_start: true, ..Default::default() };
981        let session = BrowserSession::new(config);
982        let error = session.ensure_started().await.unwrap_err();
983        assert!(error.to_string().contains("require_explicit_start"));
984        assert!(!session.is_active().await);
985    }
986
987    #[test]
988    fn chrome_options_cannot_replace_the_argument_list() {
989        let config =
990            BrowserConfig::new().chrome_option("args", serde_json::json!(["--no-sandbox"]));
991        let error = BrowserSession::new(config).build_capabilities().unwrap_err();
992        assert!(error.to_string().contains("add_arg"), "{error}");
993    }
994
995    #[test]
996    fn chrome_options_preserve_binary_and_download_preferences() {
997        let config = BrowserConfig::new()
998            .chrome_option("binary", serde_json::json!("/opt/chromium"))
999            .chrome_option(
1000                "prefs",
1001                serde_json::json!({"download.default_directory":"/tmp/downloads"}),
1002            );
1003        let caps = BrowserSession::new(config).build_capabilities().unwrap();
1004        let options = caps.get("goog:chromeOptions").expect("chrome options are set");
1005        assert_eq!(options["binary"], "/opt/chromium");
1006        assert_eq!(options["prefs"]["download.default_directory"], "/tmp/downloads");
1007        assert!(!options["args"].as_array().unwrap().iter().any(|arg| arg == "--no-sandbox"));
1008    }
1009}