browser_use/tools/
close_tab.rs

1use crate::error::Result;
2use crate::tools::{Tool, ToolContext, ToolResult};
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6/// Parameters for the close_tab tool (no parameters needed)
7#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
8pub struct CloseTabParams {}
9
10/// Tool for closing the current active tab
11#[derive(Default)]
12pub struct CloseTabTool;
13
14impl Tool for CloseTabTool {
15    type Params = CloseTabParams;
16
17    fn name(&self) -> &str {
18        "close_tab"
19    }
20
21    fn execute_typed(&self, _params: CloseTabParams, context: &mut ToolContext) -> Result<ToolResult> {
22        // Get the current tab info before closing
23        let active_tab = context.session.tab();
24        let tab_title = active_tab.get_title().unwrap_or_default();
25        let tab_url = active_tab.get_url();
26        
27        // Get the current tab index
28        let tabs = context.session.get_tabs()?;
29        let current_index = tabs
30            .iter()
31            .position(|tab| std::sync::Arc::ptr_eq(tab, active_tab))
32            .unwrap_or(0);
33
34        // Close the active tab
35        active_tab.close(true).map_err(|e| {
36            crate::error::BrowserError::TabOperationFailed(format!(
37                "Failed to close tab: {}",
38                e
39            ))
40        })?;
41
42        let message = format!(
43            "Closed tab [{}]: {} ({})",
44            current_index, tab_title, tab_url
45        );
46
47        Ok(ToolResult::success_with(serde_json::json!({
48            "index": current_index,
49            "title": tab_title,
50            "url": tab_url,
51            "message": message
52        })))
53    }
54}