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(
22        &self,
23        _params: CloseTabParams,
24        context: &mut ToolContext,
25    ) -> Result<ToolResult> {
26        // Get the current tab info before closing
27        let active_tab = context.session.tab()?;
28        let tab_title = active_tab.get_title().unwrap_or_default();
29        let tab_url = active_tab.get_url();
30
31        // Get the current tab index
32        let tabs = context.session.get_tabs()?;
33        let current_index = tabs
34            .iter()
35            .position(|tab| std::sync::Arc::ptr_eq(tab, &active_tab))
36            .unwrap_or(0);
37
38        // Close the active tab
39        active_tab.close(true).map_err(|e| {
40            crate::error::BrowserError::TabOperationFailed(format!("Failed to close tab: {}", e))
41        })?;
42
43        let message = format!(
44            "Closed tab [{}]: {} ({})",
45            current_index, tab_title, tab_url
46        );
47
48        Ok(ToolResult::success_with(serde_json::json!({
49            "index": current_index,
50            "title": tab_title,
51            "url": tab_url,
52            "message": message
53        })))
54    }
55}