Skip to main content

oxi_agent/tools/browse/
browse_tool.rs

1//! Browse tool — render a web page and return its content.
2//!
3//! Opens exactly **one** tab per request and extracts all content from it.
4//! Never calls engine-level methods that would open additional tabs.
5
6use super::config::BrowseConfig;
7use super::engine::BrowserEngine;
8use super::helpers;
9use super::tab_guard::TabGuard;
10use crate::tools::{AgentTool, AgentToolResult, ToolContext, ToolError, ToolExecutionMode};
11use async_trait::async_trait;
12use parking_lot::Mutex;
13use serde_json::{json, Value};
14use std::sync::Arc;
15use tokio::sync::oneshot;
16
17/// Render a web page using the built-in headless browser.
18///
19/// Returns page content as markdown, html, text, or a list of links.
20pub struct BrowseTool {
21    engine: Arc<dyn BrowserEngine>,
22    config: BrowseConfig,
23    /// Shared callback management (progress + browse progress).
24    callbacks: super::callback_mixin::BrowseCallbacks,
25    /// Shared slot for the current tab's ID. The agent loop creates the slot
26    /// and passes it via `set_tab_id_slot`; BrowseTool writes `Some(tab_id)`
27    /// when it opens a tab and `None` on close.
28    tab_id_slot: Mutex<Arc<parking_lot::Mutex<Option<uuid::Uuid>>>>,
29}
30
31impl BrowseTool {
32    /// Create with the given engine and default config.
33    pub fn new(engine: Arc<dyn BrowserEngine>) -> Self {
34        Self {
35            engine,
36            config: BrowseConfig::default(),
37            callbacks: super::callback_mixin::BrowseCallbacks::new(),
38            tab_id_slot: Mutex::new(Arc::new(parking_lot::Mutex::new(None))),
39        }
40    }
41
42    /// Create with custom configuration.
43    pub fn with_config(engine: Arc<dyn BrowserEngine>, config: BrowseConfig) -> Self {
44        Self {
45            engine,
46            config,
47            callbacks: super::callback_mixin::BrowseCallbacks::new(),
48            tab_id_slot: Mutex::new(Arc::new(parking_lot::Mutex::new(None))),
49        }
50    }
51}
52
53#[async_trait]
54impl AgentTool for BrowseTool {
55    fn name(&self) -> &str {
56        "browse"
57    }
58
59    fn label(&self) -> &str {
60        "Browse"
61    }
62
63    fn description(&self) -> &str {
64        "Browse a web page with a built-in headless browser. Renders JavaScript-powered \
65         pages and returns content as markdown (default), html, or links. Use when \
66         web_search results are insufficient and you need to read the actual page content. \
67         Supports waiting for dynamic content via CSS selectors."
68    }
69
70    fn parameters_schema(&self) -> Value {
71        json!({
72            "type": "object",
73            "properties": {
74                "url": {
75                    "type": "string",
76                    "description": "URL to browse"
77                },
78                "format": {
79                    "type": "string",
80                    "enum": ["markdown", "html", "text", "links"],
81                    "default": "markdown",
82                    "description": "Output format: markdown (default), html, plain text, or list of links"
83                },
84                "selector": {
85                    "type": "string",
86                    "description": "CSS selector to extract only matching elements"
87                },
88                "wait_for": {
89                    "type": "string",
90                    "description": "CSS selector to wait for before extracting (for JS-rendered content)"
91                },
92                "screenshot": {
93                    "type": "boolean",
94                    "default": false,
95                    "description": "Include a PNG screenshot as an image block"
96                }
97            },
98            "required": ["url"]
99        })
100    }
101
102    fn on_progress(&self, callback: crate::tools::ProgressCallback) {
103        self.callbacks.store_progress(callback);
104    }
105
106    fn on_browse_progress(&self, callback: Arc<dyn Fn(super::BrowseProgress) + Send + Sync>) {
107        self.callbacks.store_browse(callback);
108    }
109
110    /// Sequential execution preserved for stability.
111    ///
112    /// Per-tab routing via `TabCallbackRegistry` now correctly routes
113    /// progress events by `tab_id`, making parallel execution safe.
114    /// However, `SequentialOnly` is kept for now unless a concrete
115    /// multi-tab use case requires parallel browse calls.
116    fn execution_mode(&self) -> ToolExecutionMode {
117        ToolExecutionMode::SequentialOnly
118    }
119
120    fn current_tab_id(&self) -> Option<uuid::Uuid> {
121        *self.tab_id_slot.lock().lock()
122    }
123
124    fn set_tab_id_slot(&self, slot: Arc<parking_lot::Mutex<Option<uuid::Uuid>>>) {
125        *self.tab_id_slot.lock() = slot;
126    }
127
128    async fn execute(
129        &self,
130        _tool_call_id: &str,
131        params: Value,
132        _signal: Option<oneshot::Receiver<()>>,
133        _ctx: &ToolContext,
134    ) -> Result<AgentToolResult, ToolError> {
135        let url = params["url"]
136            .as_str()
137            .ok_or_else(|| "Missing required parameter: url".to_string())?;
138
139        let format = params["format"].as_str().unwrap_or("markdown");
140        let selector = params["selector"].as_str();
141        let wait_for = params["wait_for"].as_str();
142        let want_screenshot = params["screenshot"].as_bool().unwrap_or(false);
143
144        tracing::info!(url = %url, format = %format, "browsing page");
145
146        // Open exactly one tab for this request
147        let raw_tab = self
148            .engine
149            .new_tab()
150            .await
151            .map_err(|e| format!("Failed to open browser tab: {}", e))?;
152
153        // Store the tab_id so the agent loop's progress callback can
154        // include it in `ToolExecutionUpdate` events.
155        let tab_id = raw_tab.tab_id();
156        *self.tab_id_slot.lock().lock() = Some(tab_id);
157
158        // Register the pending callbacks on this tab.
159        self.callbacks.register_on_tab(raw_tab.as_ref());
160
161        let guard = TabGuard::new(raw_tab);
162        let tab = guard.tab();
163
164        // Navigate
165        let page = tab
166            .goto(url)
167            .await
168            .map_err(|e| format!("Navigation failed: {}", e))?;
169
170        // Wait for dynamic content if requested
171        if let Some(sel) = wait_for {
172            tab.wait_for(sel, self.config.default_wait_timeout_ms)
173                .await
174                .map_err(|e| format!("wait_for '{}' failed: {}", sel, e))?;
175        }
176
177        // Build output — all from the same tab
178        let output = match format {
179            "html" => {
180                if let Some(sel) = selector {
181                    tab.query_all(sel)
182                        .await
183                        .map_err(|e| e.to_string())?
184                        .join("\n\n")
185                } else {
186                    page.html.clone()
187                }
188            }
189            "links" => {
190                let links = helpers::extract_links(tab).await?;
191                helpers::format_links(&links)
192            }
193            "text" => {
194                if let Some(sel) = selector {
195                    tab.query_all(sel)
196                        .await
197                        .map_err(|e| e.to_string())?
198                        .join("\n")
199                } else {
200                    page.markdown.clone()
201                }
202            }
203            _ => {
204                // "markdown" (default)
205                if let Some(sel) = selector {
206                    tab.query_all(sel)
207                        .await
208                        .map_err(|e| e.to_string())?
209                        .join("\n\n")
210                } else {
211                    page.markdown.clone()
212                }
213            }
214        };
215
216        let title = page.title.clone();
217        let final_url = page.url.clone();
218        let status = page.status;
219
220        // Screenshot from the same tab (no re-render)
221        let screenshot_blocks = if want_screenshot {
222            match tab.screenshot(self.config.screenshot_width).await {
223                Ok(png) => {
224                    let b64 =
225                        base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &png);
226                    let img =
227                        oxi_ai::ContentBlock::Image(oxi_ai::ImageContent::new(b64, "image/png"));
228                    Some(vec![img])
229                }
230                Err(e) => {
231                    tracing::warn!("screenshot failed for {}: {}", final_url, e);
232                    None
233                }
234            }
235        } else {
236            None
237        };
238
239        // Explicitly close the tab and clear the tab_id slot
240        guard.close().await;
241        *self.tab_id_slot.lock().lock() = None;
242
243        let mut result = AgentToolResult::success(output).with_metadata(json!({
244            "url": final_url,
245            "title": title,
246            "status": status,
247        }));
248
249        if let Some(blocks) = screenshot_blocks {
250            result = result.with_content_blocks(blocks);
251        }
252
253        Ok(result)
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use crate::tools::browse::engine::{BrowserError, BrowserTab};
261    use async_trait::async_trait;
262
263    /// Minimal `BrowserEngine` stub. We never call `new_tab` in the test,
264    /// so the trait methods are allowed to return `Err` — the goal is just
265    /// to be able to construct a `BrowseTool` and read `execution_mode()`.
266    struct MockEngine;
267
268    #[async_trait]
269    impl BrowserEngine for MockEngine {
270        async fn new_tab(&self) -> Result<Box<dyn BrowserTab>, BrowserError> {
271            Err(BrowserError::Backend("MockEngine: no real browser".into()))
272        }
273
274        async fn close(&self) -> Result<(), BrowserError> {
275            Ok(())
276        }
277
278        async fn is_alive(&self) -> bool {
279            false
280        }
281    }
282
283    #[test]
284    fn browse_tool_is_sequential_only() {
285        let tool = BrowseTool::new(std::sync::Arc::new(MockEngine));
286        assert!(matches!(
287            tool.execution_mode(),
288            crate::tools::ToolExecutionMode::SequentialOnly
289        ));
290    }
291
292    #[test]
293    fn browse_tool_tab_id_slot_receives_id_from_agent_loop() {
294        // Simulate the agent loop's flow: set_tab_id_slot → write tab_id →
295        // read current_tab_id → clear.
296        let tool = BrowseTool::new(std::sync::Arc::new(MockEngine));
297
298        // Initially no tab_id
299        assert!(tool.current_tab_id().is_none());
300
301        // Agent loop creates a slot and passes it
302        let slot: Arc<parking_lot::Mutex<Option<uuid::Uuid>>> =
303            Arc::new(parking_lot::Mutex::new(None));
304        tool.set_tab_id_slot(Arc::clone(&slot));
305
306        // Simulate BrowseTool::execute opening a tab
307        let tab_id = uuid::Uuid::new_v4();
308        *slot.lock() = Some(tab_id);
309
310        // Agent loop's progress callback reads the slot
311        assert_eq!(tool.current_tab_id(), Some(tab_id));
312
313        // BrowseTool::execute closes the tab
314        *slot.lock() = None;
315        assert!(tool.current_tab_id().is_none());
316    }
317}