Skip to main content

poly_mcp/modules/browser/
mod.rs

1mod cdp;
2
3use anyhow::Context;
4use serde_json::{json, Value};
5use std::process::Command;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8const DEFAULT_PORT: u16 = 9222;
9
10/// Browser control module — headless browser automation via CDP.
11pub struct BrowserModule {
12    /// Cached session keyed by (port). Supports multi-port usage.
13    sessions: tokio::sync::Mutex<std::collections::HashMap<u16, cdp::BrowserSession>>,
14    needs_reconnect: AtomicBool,
15}
16
17impl BrowserModule {
18    pub fn new() -> Self {
19        Self {
20            sessions: tokio::sync::Mutex::new(std::collections::HashMap::new()),
21            needs_reconnect: AtomicBool::new(false),
22        }
23    }
24
25    /// Mark session as potentially dead — next get_session will probe.
26    fn mark_needs_reconnect(&self) {
27        self.needs_reconnect.store(true, Ordering::Relaxed);
28    }
29
30    /// Get or create a persistent browser session for a specific port.
31    /// If a previous call failed, probes the session before reusing it.
32    async fn get_session(&self, port: u16) -> anyhow::Result<tokio::sync::MutexGuard<'_, std::collections::HashMap<u16, cdp::BrowserSession>>> {
33        let mut guard = self.sessions.lock().await;
34
35        // If flagged as potentially dead, probe the existing session for this port
36        if guard.contains_key(&port) && self.needs_reconnect.swap(false, Ordering::Relaxed) {
37            let healthy = if let Some(session) = guard.get_mut(&port) {
38                tokio::time::timeout(
39                    tokio::time::Duration::from_secs(1),
40                    session.evaluate("1"),
41                )
42                .await
43                .map(|r| r.is_ok())
44                .unwrap_or(false)
45            } else {
46                false
47            };
48            if !healthy {
49                guard.remove(&port);
50            }
51        }
52
53        if !guard.contains_key(&port) {
54            let session = cdp::BrowserSession::connect(port).await?;
55            guard.insert(port, session);
56        }
57        Ok(guard)
58    }
59
60    pub fn get_tools(&self) -> Vec<Value> {
61        vec![
62            json!({
63                "name": "browser_launch",
64                "description": "Launch a browser (Firefox or Chrome) with remote debugging enabled. Returns the CDP port for use with other browser tools. The browser stays running until browser_close is called. Note: snap-packaged Firefox cannot bind debugging ports — use a native install or Chrome instead.",
65                "inputSchema": {
66                    "type": "object",
67                    "properties": {
68                        "headless": { "type": "boolean", "description": "Run without visible window (default true)" },
69                        "url": { "type": "string", "description": "Initial URL to open" },
70                        "port": { "type": "number", "description": "CDP debugging port (default 9222)" },
71                        "browser": { "type": "string", "description": "Browser to use: 'firefox' or 'chrome' (auto-detected if omitted)", "enum": ["firefox", "chrome"] }
72                    },
73                    "required": []
74                }
75            }),
76            json!({
77                "name": "browser_navigate",
78                "description": "Navigate to a URL in the browser. Waits for page load to complete.",
79                "inputSchema": {
80                    "type": "object",
81                    "properties": {
82                        "url": { "type": "string", "description": "URL to navigate to" },
83                        "port": { "type": "number", "description": "CDP port (default 9222)" }
84                    },
85                    "required": ["url"]
86                }
87            }),
88            json!({
89                "name": "browser_screenshot",
90                "description": "Take a screenshot of the current page. Returns an image. Much more reliable than screen_capture for web content since it captures the DOM directly.",
91                "inputSchema": {
92                    "type": "object",
93                    "properties": {
94                        "full_page": { "type": "boolean", "description": "Capture full scrollable page, not just viewport (default false)" },
95                        "port": { "type": "number", "description": "CDP port (default 9222)" }
96                    },
97                    "required": []
98                }
99            }),
100            json!({
101                "name": "browser_content",
102                "description": "Get the page content — title, URL, HTML, or extracted text.",
103                "inputSchema": {
104                    "type": "object",
105                    "properties": {
106                        "format": {
107                            "type": "string",
108                            "description": "'text' (visible text), 'html' (full HTML), 'title' (page title), 'url' (current URL)",
109                            "enum": ["text", "html", "title", "url"]
110                        },
111                        "port": { "type": "number", "description": "CDP port (default 9222)" }
112                    },
113                    "required": []
114                }
115            }),
116            json!({
117                "name": "browser_query",
118                "description": "Query DOM elements by CSS selector. Returns matching elements with text, attributes, and bounding boxes. Use this to find buttons, links, inputs — then click or fill them.",
119                "inputSchema": {
120                    "type": "object",
121                    "properties": {
122                        "selector": { "type": "string", "description": "CSS selector (e.g. 'button', '.submit-btn', '#email', 'a[href*=login]')" },
123                        "port": { "type": "number", "description": "CDP port (default 9222)" }
124                    },
125                    "required": ["selector"]
126                }
127            }),
128            json!({
129                "name": "browser_click",
130                "description": "Click a DOM element by CSS selector. More reliable than coordinate clicking — targets the element directly in the DOM.",
131                "inputSchema": {
132                    "type": "object",
133                    "properties": {
134                        "selector": { "type": "string", "description": "CSS selector of element to click" },
135                        "port": { "type": "number", "description": "CDP port (default 9222)" }
136                    },
137                    "required": ["selector"]
138                }
139            }),
140            json!({
141                "name": "browser_fill",
142                "description": "Fill a form input/textarea by CSS selector. Triggers input and change events.",
143                "inputSchema": {
144                    "type": "object",
145                    "properties": {
146                        "selector": { "type": "string", "description": "CSS selector of the input field" },
147                        "value": { "type": "string", "description": "Value to fill" },
148                        "port": { "type": "number", "description": "CDP port (default 9222)" }
149                    },
150                    "required": ["selector", "value"]
151                }
152            }),
153            json!({
154                "name": "browser_eval",
155                "description": "Execute JavaScript in the page context. Returns the result. Can access DOM, make fetch calls, interact with page APIs.",
156                "inputSchema": {
157                    "type": "object",
158                    "properties": {
159                        "expression": { "type": "string", "description": "JavaScript code to execute" },
160                        "port": { "type": "number", "description": "CDP port (default 9222)" }
161                    },
162                    "required": ["expression"]
163                }
164            }),
165            json!({
166                "name": "browser_tabs",
167                "description": "List all open browser tabs with their titles, URLs, and IDs.",
168                "inputSchema": {
169                    "type": "object",
170                    "properties": {
171                        "port": { "type": "number", "description": "CDP port (default 9222)" }
172                    },
173                    "required": []
174                }
175            }),
176            json!({
177                "name": "browser_close",
178                "description": "Close a browser tab or the entire browser.",
179                "inputSchema": {
180                    "type": "object",
181                    "properties": {
182                        "tab_id": { "type": "string", "description": "Tab ID to close. If omitted, closes all tabs and kills the browser." },
183                        "port": { "type": "number", "description": "CDP port (default 9222)" }
184                    },
185                    "required": []
186                }
187            }),
188            json!({
189                "name": "browser_wait",
190                "description": "Wait for a condition in the browser: element by CSS selector, text on page, URL match, or custom JS expression. Polls every 100ms. Essential for SPAs — call this after navigate to ensure content is rendered before interacting.",
191                "inputSchema": {
192                    "type": "object",
193                    "properties": {
194                        "selector": { "type": "string", "description": "CSS selector to wait for (e.g. '.loaded', '#content', 'button[data-action]')" },
195                        "text": { "type": "string", "description": "Text to wait for on the page (substring match)" },
196                        "url": { "type": "string", "description": "URL substring to wait for (e.g. '/dashboard')" },
197                        "expression": { "type": "string", "description": "JS expression that should return truthy when condition is met" },
198                        "visible": { "type": "boolean", "description": "For selector: also require element has non-zero size (default true)" },
199                        "timeout_ms": { "type": "number", "description": "Timeout in ms (default 30000)" },
200                        "port": { "type": "number", "description": "CDP port (default 9222)" }
201                    },
202                    "required": []
203                }
204            }),
205            json!({
206                "name": "browser_scroll",
207                "description": "Scroll the page in a direction, by pixels, or scroll a specific element into view.",
208                "inputSchema": {
209                    "type": "object",
210                    "properties": {
211                        "direction": { "type": "string", "description": "Scroll direction: 'up', 'down', 'left', 'right' (default 'down')", "enum": ["up", "down", "left", "right"] },
212                        "pixels": { "type": "number", "description": "Pixels to scroll (default 300)" },
213                        "selector": { "type": "string", "description": "CSS selector of element to scroll into view (overrides direction/pixels)" },
214                        "port": { "type": "number", "description": "CDP port (default 9222)" }
215                    },
216                    "required": []
217                }
218            }),
219            json!({
220                "name": "browser_hover",
221                "description": "Hover over a DOM element to trigger CSS :hover styles and tooltip display.",
222                "inputSchema": {
223                    "type": "object",
224                    "properties": {
225                        "selector": { "type": "string", "description": "CSS selector of element to hover" },
226                        "port": { "type": "number", "description": "CDP port (default 9222)" }
227                    },
228                    "required": ["selector"]
229                }
230            }),
231            json!({
232                "name": "browser_select",
233                "description": "Select an option from a <select> dropdown by value or visible text.",
234                "inputSchema": {
235                    "type": "object",
236                    "properties": {
237                        "selector": { "type": "string", "description": "CSS selector of the <select> element" },
238                        "value": { "type": "string", "description": "Option value to select" },
239                        "text": { "type": "string", "description": "Option visible text to select (used if value not provided)" },
240                        "port": { "type": "number", "description": "CDP port (default 9222)" }
241                    },
242                    "required": ["selector"]
243                }
244            }),
245        ]
246    }
247
248    // ── Tool dispatch ─────────────────────────────────────────────
249
250    pub async fn launch(&self, args: Value) -> anyhow::Result<Value> {
251        let headless = args["headless"].as_bool().unwrap_or(true);
252        let url = args["url"].as_str().unwrap_or("about:blank");
253        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
254        let browser_pref = args["browser"].as_str();
255
256        let (browser_name, bin_path) = find_browser(browser_pref)?;
257
258        let mut cmd_args: Vec<String> = Vec::new();
259
260        match browser_name {
261            "firefox" => {
262                cmd_args.push(format!("--remote-debugging-port={}", port));
263                if headless {
264                    cmd_args.push("--headless".to_string());
265                }
266                cmd_args.push(url.to_string());
267            }
268            "chrome" => {
269                cmd_args.push(format!("--remote-debugging-port={}", port));
270                if headless {
271                    cmd_args.push("--headless=new".to_string());
272                }
273                cmd_args.push("--no-first-run".to_string());
274                cmd_args.push("--no-default-browser-check".to_string());
275                cmd_args.push("--disable-gpu".to_string());
276                cmd_args.push(url.to_string());
277            }
278            _ => unreachable!(),
279        }
280
281        // Launch browser process
282        let child = Command::new(&bin_path)
283            .args(&cmd_args)
284            .stdin(std::process::Stdio::null())
285            .stdout(std::process::Stdio::null())
286            .stderr(std::process::Stdio::null())
287            .spawn()
288            .context(format!("Failed to launch {}", browser_name))?;
289
290        let pid = child.id();
291
292        // Wait for CDP to become available
293        let start = std::time::Instant::now();
294        let timeout = tokio::time::Duration::from_secs(15);
295
296        loop {
297            if start.elapsed() > timeout {
298                return Err(anyhow::anyhow!(
299                    "Browser launched but CDP port {} not responding after 15s",
300                    port
301                ));
302            }
303
304            // Try connecting — reset any stale session/cache first
305            if let Ok(_) = cdp::BrowserSession::connect(port).await {
306                self.sessions.lock().await.remove(&port);
307                cdp::clear_browser_cache(port);
308                return Ok(json!({
309                    "success": true,
310                    "browser": browser_name,
311                    "pid": pid,
312                    "port": port,
313                    "headless": headless,
314                    "startup_ms": start.elapsed().as_millis()
315                }));
316            }
317
318            tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
319        }
320    }
321
322    /// Check if an error is transient (worth retrying).
323    fn is_transient_error(e: &anyhow::Error) -> bool {
324        let msg = e.to_string();
325        msg.contains("WebSocket") || msg.contains("timeout") || msg.contains("closed")
326    }
327
328    /// Handle a transient error: clear session and wait before retry.
329    async fn handle_transient(&self, port: u16, attempt: usize) {
330        let delays = [200u64, 400, 800];
331        self.sessions.lock().await.remove(&port);
332        self.needs_reconnect.store(false, Ordering::Relaxed);
333        let delay = delays.get(attempt).copied().unwrap_or(800);
334        tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
335    }
336
337    pub async fn navigate(&self, args: Value) -> anyhow::Result<Value> {
338        let url = args["url"].as_str().context("Missing 'url'")?;
339        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
340
341        let result = async {
342            let mut guard = self.get_session(port).await?;
343            let session = guard.get_mut(&port).context("No browser session")?;
344            session.navigate(url).await?;
345            let title = session.get_title().await.unwrap_or_default();
346            Ok(json!({ "success": true, "url": url, "title": title }))
347        }.await;
348
349        if result.is_err() { self.mark_needs_reconnect(); }
350        result
351    }
352
353    pub async fn screenshot(&self, args: Value) -> anyhow::Result<Value> {
354        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
355
356        let result: anyhow::Result<Value> = async {
357            let mut guard = self.get_session(port).await?;
358            let session = guard.get_mut(&port).context("No browser session")?;
359            let b64_data = session.screenshot().await?;
360            let byte_size = b64_data.len() * 3 / 4;
361            Ok(json!({
362                "content": [
363                    { "type": "image", "data": b64_data, "mimeType": "image/png" },
364                    { "type": "text", "text": serde_json::to_string_pretty(&json!({"bytes": byte_size}))? }
365                ]
366            }))
367        }.await;
368
369        if result.is_err() { self.mark_needs_reconnect(); }
370        result
371    }
372
373    pub async fn content(&self, args: Value) -> anyhow::Result<Value> {
374        let format = args["format"].as_str().unwrap_or("text");
375        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
376
377        let result: anyhow::Result<Value> = async {
378            let mut guard = self.get_session(port).await?;
379            let session = guard.get_mut(&port).context("No browser session")?;
380            match format {
381                "html" => {
382                    let html = session.get_content().await?;
383                    Ok(json!({ "format": "html", "length": html.len(), "content": html }))
384                }
385                "title" => {
386                    let title = session.get_title().await?;
387                    Ok(json!({ "format": "title", "title": title }))
388                }
389                "url" => {
390                    let url = session.evaluate("window.location.href").await?;
391                    Ok(json!({ "format": "url", "url": url }))
392                }
393                _ => {
394                    let text = session.evaluate("document.body?.innerText || ''").await?;
395                    let text_str = text.as_str().unwrap_or("");
396                    Ok(json!({ "format": "text", "length": text_str.len(), "content": text_str }))
397                }
398            }
399        }.await;
400
401        if result.is_err() { self.mark_needs_reconnect(); }
402        result
403    }
404
405    pub async fn query(&self, args: Value) -> anyhow::Result<Value> {
406        let selector = args["selector"].as_str().context("Missing 'selector'")?;
407        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
408
409        for attempt in 0..3 {
410            let result: anyhow::Result<Value> = async {
411                let mut guard = self.get_session(port).await?;
412                let session = guard.get_mut(&port).context("No browser session")?;
413                let elements = session.query_selector_all(selector).await?;
414                let count = elements.as_array().map(|a| a.len()).unwrap_or(0);
415                Ok(json!({ "selector": selector, "count": count, "elements": elements }))
416            }.await;
417            match result {
418                Ok(v) => return Ok(v),
419                Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
420                    self.handle_transient(port, attempt).await;
421                }
422                Err(e) => { self.mark_needs_reconnect(); return Err(e); }
423            }
424        }
425        unreachable!()
426    }
427
428    pub async fn click(&self, args: Value) -> anyhow::Result<Value> {
429        let selector = args["selector"].as_str().context("Missing 'selector'")?;
430        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
431
432        for attempt in 0..3 {
433            let result: anyhow::Result<Value> = async {
434                let mut guard = self.get_session(port).await?;
435                let session = guard.get_mut(&port).context("No browser session")?;
436                let r = session.click_selector(selector).await?;
437                Ok(json!({ "selector": selector, "result": r }))
438            }.await;
439            match result {
440                Ok(v) => return Ok(v),
441                Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
442                    self.handle_transient(port, attempt).await;
443                }
444                Err(e) => { self.mark_needs_reconnect(); return Err(e); }
445            }
446        }
447        unreachable!()
448    }
449
450    pub async fn fill(&self, args: Value) -> anyhow::Result<Value> {
451        let selector = args["selector"].as_str().context("Missing 'selector'")?;
452        let value = args["value"].as_str().context("Missing 'value'")?;
453        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
454
455        for attempt in 0..3 {
456            let result: anyhow::Result<Value> = async {
457                let mut guard = self.get_session(port).await?;
458                let session = guard.get_mut(&port).context("No browser session")?;
459                let r = session.fill_selector(selector, value).await?;
460                Ok(json!({ "selector": selector, "result": r }))
461            }.await;
462            match result {
463                Ok(v) => return Ok(v),
464                Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
465                    self.handle_transient(port, attempt).await;
466                }
467                Err(e) => { self.mark_needs_reconnect(); return Err(e); }
468            }
469        }
470        unreachable!()
471    }
472
473    pub async fn eval(&self, args: Value) -> anyhow::Result<Value> {
474        let expression = args["expression"].as_str().context("Missing 'expression'")?;
475        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
476
477        let result: anyhow::Result<Value> = async {
478            let mut guard = self.get_session(port).await?;
479            let session = guard.get_mut(&port).context("No browser session")?;
480            let r = session.evaluate(expression).await?;
481            Ok(json!({ "expression": expression, "result": r }))
482        }.await;
483
484        if result.is_err() { self.mark_needs_reconnect(); }
485        result
486    }
487
488    pub async fn wait(&self, args: Value) -> anyhow::Result<Value> {
489        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
490        let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(30000);
491        let visible = args["visible"].as_bool().unwrap_or(true);
492
493        // Build JS condition from parameters
494        let condition_js = if let Some(selector) = args["selector"].as_str() {
495            let sel = cdp::js_escape(selector);
496            if visible {
497                format!(
498                    "(function(){{ var el = document.querySelector('{}'); if (!el) return false; var r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }})()",
499                    sel
500                )
501            } else {
502                format!("!!document.querySelector('{}')", sel)
503            }
504        } else if let Some(text) = args["text"].as_str() {
505            format!("(document.body?.innerText || '').includes('{}')", cdp::js_escape(text))
506        } else if let Some(url_pat) = args["url"].as_str() {
507            format!("window.location.href.includes('{}')", cdp::js_escape(url_pat))
508        } else if let Some(expr) = args["expression"].as_str() {
509            expr.to_string()
510        } else {
511            return Err(anyhow::anyhow!("Provide 'selector', 'text', 'url', or 'expression'"));
512        };
513
514        let result: anyhow::Result<Value> = async {
515            let mut guard = self.get_session(port).await?;
516            let session = guard.get_mut(&port).context("No browser session")?;
517            session.wait_for(&condition_js, timeout_ms).await
518        }.await;
519
520        if result.is_err() { self.mark_needs_reconnect(); }
521        result
522    }
523
524    pub async fn scroll(&self, args: Value) -> anyhow::Result<Value> {
525        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
526        let direction = args["direction"].as_str().unwrap_or("down");
527        let pixels = args["pixels"].as_i64().unwrap_or(300);
528        let selector = args["selector"].as_str();
529
530        let result: anyhow::Result<Value> = async {
531            let mut guard = self.get_session(port).await?;
532            let session = guard.get_mut(&port).context("No browser session")?;
533            session.scroll_page(direction, pixels, selector).await
534        }.await;
535
536        if result.is_err() { self.mark_needs_reconnect(); }
537        result
538    }
539
540    pub async fn hover(&self, args: Value) -> anyhow::Result<Value> {
541        let selector = args["selector"].as_str().context("Missing 'selector'")?;
542        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
543
544        let result: anyhow::Result<Value> = async {
545            let mut guard = self.get_session(port).await?;
546            let session = guard.get_mut(&port).context("No browser session")?;
547            session.hover_element(selector).await
548        }.await;
549
550        if result.is_err() { self.mark_needs_reconnect(); }
551        result
552    }
553
554    pub async fn select(&self, args: Value) -> anyhow::Result<Value> {
555        let selector = args["selector"].as_str().context("Missing 'selector'")?;
556        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
557        let value = args["value"].as_str();
558        let text = args["text"].as_str();
559
560        let result: anyhow::Result<Value> = async {
561            let mut guard = self.get_session(port).await?;
562            let session = guard.get_mut(&port).context("No browser session")?;
563            session.select_option(selector, value, text).await
564        }.await;
565
566        if result.is_err() { self.mark_needs_reconnect(); }
567        result
568    }
569
570    pub async fn tabs(&self, args: Value) -> anyhow::Result<Value> {
571        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
572
573        // Try using cached session first (avoids opening a second connection that
574        // hits Firefox's "one session" limit)
575        let result: anyhow::Result<Value> = async {
576            let mut guard = self.get_session(port).await?;
577            let session = guard.get_mut(&port).context("No browser session")?;
578
579            if session.browser_kind() == cdp::BrowserKind::Firefox {
580                // Use BiDi browsingContext.getTree via cached session
581                let tree = session.send_raw("browsingContext.getTree", json!({})).await?;
582                let contexts = tree.get("contexts").and_then(|c| c.as_array()).cloned().unwrap_or_default();
583                let tabs: Vec<Value> = contexts.iter().map(|c| json!({
584                    "id": c["context"],
585                    "title": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
586                    "url": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
587                })).collect();
588                Ok(json!({ "count": tabs.len(), "tabs": tabs }))
589            } else {
590                // Chrome: use HTTP endpoint (doesn't require WebSocket session)
591                drop(guard);
592                let tabs = cdp::list_tabs(port).await?;
593                Ok(json!({ "count": tabs.len(), "tabs": tabs }))
594            }
595        }.await;
596
597        if result.is_err() { self.mark_needs_reconnect(); }
598        result
599    }
600
601    pub async fn close(&self, args: Value) -> anyhow::Result<Value> {
602        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
603        let tab_id = args["tab_id"].as_str();
604
605        // Clear cached session and browser kind for this port
606        self.sessions.lock().await.remove(&port);
607        cdp::clear_browser_cache(port);
608
609        if let Some(id) = tab_id {
610            cdp::close_tab(port, id).await?;
611            Ok(json!({ "success": true, "closed": "tab", "tab_id": id }))
612        } else {
613            // Close all tabs and kill browser
614            if let Ok(tabs) = cdp::list_tabs(port).await {
615                for tab in &tabs {
616                    if let Some(id) = tab["id"].as_str() {
617                        let _ = cdp::close_tab(port, id).await;
618                    }
619                }
620            }
621
622            // Kill browser processes listening on this port
623            let _ = Command::new("fuser")
624                .args(["-k", &format!("{}/tcp", port)])
625                .output();
626
627            Ok(json!({ "success": true, "closed": "browser", "port": port }))
628        }
629    }
630}
631
632// ── Helpers ────────────────────────────────────────────────────────
633
634fn find_browser(preference: Option<&str>) -> anyhow::Result<(&'static str, String)> {
635    let firefox_bins = ["firefox", "firefox-esr"];
636    let chrome_bins = [
637        "google-chrome-stable",
638        "google-chrome",
639        "chromium-browser",
640        "chromium",
641    ];
642
643    if let Some(pref) = preference {
644        let (label, bins): (&'static str, &[&str]) = if pref == "firefox" {
645            ("firefox", &firefox_bins)
646        } else {
647            ("chrome", &chrome_bins)
648        };
649        for bin in bins {
650            if let Some(path) = which(bin) {
651                return Ok((label, path));
652            }
653        }
654        return Err(anyhow::anyhow!(
655            "{} not found. Install it or try the other browser.",
656            pref
657        ));
658    }
659
660    // Auto-detect: prefer Firefox (better CDP support on Linux)
661    for bin in &firefox_bins {
662        if let Some(path) = which(bin) {
663            return Ok(("firefox", path));
664        }
665    }
666    for bin in &chrome_bins {
667        if let Some(path) = which(bin) {
668            return Ok(("chrome", path));
669        }
670    }
671
672    Err(anyhow::anyhow!(
673        "No browser found. Install Firefox or Chrome."
674    ))
675}
676
677fn which(name: &str) -> Option<String> {
678    Command::new("which")
679        .arg(name)
680        .output()
681        .ok()
682        .filter(|o| o.status.success())
683        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
684}