browser_use/tools/
new_tab.rs

1use crate::error::Result;
2use crate::tools::{Tool, ToolContext, ToolResult};
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6/// Parameters for the new_tab tool
7#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
8pub struct NewTabParams {
9    /// URL to open in the new tab
10    pub url: String,
11}
12
13/// Tool for opening a new tab
14#[derive(Default)]
15pub struct NewTabTool;
16
17impl Tool for NewTabTool {
18    type Params = NewTabParams;
19
20    fn name(&self) -> &str {
21        "new_tab"
22    }
23
24    fn execute_typed(&self, params: NewTabParams, context: &mut ToolContext) -> Result<ToolResult> {
25        // Create a new tab (this also sets it as active)
26        // Note: We need mutable access to session, but ToolContext only provides &BrowserSession
27        // The session's new_tab() method requires &mut self, so we'll need to use the underlying browser
28
29        // Since BrowserSession methods like new_tab() require &mut self but we only have &BrowserSession,
30        // we need to work around this by using the browser's new_tab() directly
31        let tab = context.session.browser().new_tab().map_err(|e| {
32            crate::error::BrowserError::TabOperationFailed(format!("Failed to create tab: {}", e))
33        })?;
34
35        // Navigate to the URL
36        tab.navigate_to(&params.url).map_err(|e| {
37            crate::error::BrowserError::NavigationFailed(format!(
38                "Failed to navigate to {}: {}",
39                params.url, e
40            ))
41        })?;
42
43        // Wait for navigation to complete
44        tab.wait_until_navigated().map_err(|e| {
45            crate::error::BrowserError::NavigationFailed(format!(
46                "Navigation to {} did not complete: {}",
47                params.url, e
48            ))
49        })?;
50
51        // Bring the new tab to front
52        tab.activate().map_err(|e| {
53            crate::error::BrowserError::TabOperationFailed(format!("Failed to activate tab: {}", e))
54        })?;
55
56        Ok(ToolResult::success_with(serde_json::json!({
57            "url": params.url,
58            "message": format!("Opened new tab with URL: {}", params.url)
59        })))
60    }
61}