poly-mcp 0.5.0

A comprehensive MCP server with filesystem, diagnostics, scripting, time, network, context, git, input, clipboard, transform, and screen control tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Browser remote protocol client. Supports:
//! - Firefox BiDi (WebDriver BiDi over ws://host:port/session)
//! - Chrome CDP (Chrome DevTools Protocol over ws://host:port/devtools/page/ID)

use anyhow::Context;
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
use tokio_tungstenite::tungstenite::Message;

type WsStream = tokio_tungstenite::WebSocketStream<
    tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
>;

static CMD_ID: AtomicU64 = AtomicU64::new(1);

/// Escape a string for safe embedding in single-quoted JavaScript strings.
pub fn js_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('\'', "\\'").replace('\n', "\\n").replace('\r', "\\r")
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BrowserKind {
    Firefox,
    Chrome,
}

/// A browser session that abstracts over Firefox BiDi and Chrome CDP.
pub struct BrowserSession {
    ws: WsStream,
    kind: BrowserKind,
    context_id: Option<String>,
}

/// Cache detected browser kind per port to avoid redundant HTTP probes.
static BROWSER_KIND_CACHE: std::sync::Mutex<Option<std::collections::HashMap<u16, BrowserKind>>> =
    std::sync::Mutex::new(None);

/// Detect which browser is running on the given port (cached after first probe).
pub async fn detect_browser(port: u16) -> anyhow::Result<BrowserKind> {
    // Check cache first
    if let Ok(cache) = BROWSER_KIND_CACHE.lock() {
        if let Some(kind) = cache.as_ref().and_then(|m| m.get(&port)) {
            return Ok(*kind);
        }
    }

    // Chrome has /json/version, Firefox doesn't
    let url = format!("http://127.0.0.1:{}/json/version", port);
    let kind = match reqwest::get(&url).await {
        Ok(resp) if resp.status().is_success() => BrowserKind::Chrome,
        _ => BrowserKind::Firefox,
    };

    // Cache the result
    if let Ok(mut cache) = BROWSER_KIND_CACHE.lock() {
        cache.get_or_insert_with(std::collections::HashMap::new).insert(port, kind);
    }

    Ok(kind)
}

/// Clear cached browser kind for a port (call when browser is closed/restarted).
pub fn clear_browser_cache(port: u16) {
    if let Ok(mut cache) = BROWSER_KIND_CACHE.lock() {
        if let Some(map) = cache.as_mut() {
            map.remove(&port);
        }
    }
}

/// List open tabs.
pub async fn list_tabs(port: u16) -> anyhow::Result<Vec<Value>> {
    let kind = detect_browser(port).await?;

    match kind {
        BrowserKind::Chrome => {
            let url = format!("http://127.0.0.1:{}/json/list", port);
            let resp = reqwest::get(&url).await.context("Failed to connect to Chrome CDP")?;
            let tabs: Vec<Value> = resp.json().await?;
            Ok(tabs.iter().map(|t| json!({
                "id": t["id"],
                "title": t["title"],
                "url": t["url"],
            })).collect())
        }
        BrowserKind::Firefox => {
            let mut session = BrowserSession::connect(port).await?;
            let tree = session.send_raw("browsingContext.getTree", json!({})).await?;
            let contexts = tree.get("contexts").and_then(|c| c.as_array()).cloned().unwrap_or_default();
            Ok(contexts.iter().map(|c| json!({
                "id": c["context"],
                "title": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
                "url": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
            })).collect())
        }
    }
}

/// Close a tab by ID.
pub async fn close_tab(port: u16, tab_id: &str) -> anyhow::Result<()> {
    let kind = detect_browser(port).await?;

    match kind {
        BrowserKind::Chrome => {
            let url = format!("http://127.0.0.1:{}/json/close/{}", port, tab_id);
            reqwest::get(&url).await?;
            Ok(())
        }
        BrowserKind::Firefox => {
            let mut session = BrowserSession::connect(port).await?;
            session.send_raw("browsingContext.close", json!({"context": tab_id})).await?;
            Ok(())
        }
    }
}

impl BrowserSession {
    pub fn browser_kind(&self) -> BrowserKind {
        self.kind
    }

    /// Connect to the browser on the given port. Auto-detects Firefox vs Chrome.
    pub async fn connect(port: u16) -> anyhow::Result<Self> {
        let kind = detect_browser(port).await?;

        match kind {
            BrowserKind::Firefox => Self::connect_firefox(port).await,
            BrowserKind::Chrome => Self::connect_chrome(port).await,
        }
    }

    async fn connect_firefox(port: u16) -> anyhow::Result<Self> {
        let ws_url = format!("ws://127.0.0.1:{}/session", port);

        // Retry session creation up to 5 times — Firefox needs time to clean up
        // stale sessions from previous WebSocket connections.
        let delays = [100u64, 300, 500, 1000, 2000];
        let mut last_err = String::new();

        for (attempt, delay) in delays.iter().enumerate() {
            let url = url::Url::parse(&ws_url)?;
            let (ws, _) = match tokio_tungstenite::connect_async(url).await {
                Ok(conn) => conn,
                Err(e) => {
                    last_err = format!("WebSocket connect failed: {}", e);
                    tokio::time::sleep(tokio::time::Duration::from_millis(*delay)).await;
                    continue;
                }
            };

            let mut session = Self { ws, kind: BrowserKind::Firefox, context_id: None };

            match session.send_raw("session.new", json!({"capabilities": {}})).await {
                Ok(_) => {
                    // Session created — get browsing context
                    let tree = session.send_raw("browsingContext.getTree", json!({})).await?;
                    if let Some(contexts) = tree.get("contexts").and_then(|c| c.as_array()) {
                        if let Some(first) = contexts.first() {
                            session.context_id = first.get("context")
                                .and_then(|c| c.as_str()).map(String::from);
                        }
                    }
                    return Ok(session);
                }
                Err(e) => {
                    last_err = e.to_string();
                    if attempt < delays.len() - 1 {
                        tokio::time::sleep(tokio::time::Duration::from_millis(*delay)).await;
                    }
                }
            }
        }

        Err(anyhow::anyhow!("Failed to create Firefox BiDi session after {} retries: {}", delays.len(), last_err))
    }

    async fn connect_chrome(port: u16) -> anyhow::Result<Self> {
        let list_url = format!("http://127.0.0.1:{}/json/list", port);
        let resp = reqwest::get(&list_url).await?;
        let tabs: Vec<Value> = resp.json().await?;

        let ws_url = tabs.first()
            .and_then(|t| t["webSocketDebuggerUrl"].as_str())
            .context("No Chrome tabs available")?;

        let url = url::Url::parse(ws_url)?;
        let (ws, _) = tokio_tungstenite::connect_async(url).await
            .context("Failed to connect to Chrome CDP WebSocket")?;

        Ok(Self { ws, kind: BrowserKind::Chrome, context_id: None })
    }

    /// Send a raw command and wait for the matching response.
    pub async fn send_raw(&mut self, method: &str, params: Value) -> anyhow::Result<Value> {
        let id = CMD_ID.fetch_add(1, Ordering::Relaxed);
        let cmd = json!({"id": id, "method": method, "params": params});

        self.ws.send(Message::Text(cmd.to_string())).await
            .context("Failed to send command")?;

        let timeout = tokio::time::Duration::from_secs(30);
        let deadline = tokio::time::Instant::now() + timeout;

        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                return Err(anyhow::anyhow!("Command '{}' timed out", method));
            }

            let msg = tokio::time::timeout(remaining, self.ws.next())
                .await
                .map_err(|_| anyhow::anyhow!("Response timeout"))?
                .context("WebSocket closed")?
                .context("WebSocket error")?;

            match msg {
                Message::Text(text) => {
                    let resp: Value = match serde_json::from_str(&text) {
                        Ok(v) => v,
                        Err(_) => continue, // Malformed JSON — skip, don't create empty object
                    };

                    if resp.get("id").and_then(|i| i.as_u64()) == Some(id) {
                        // Check for error (handles both Chrome CDP and Firefox BiDi formats)
                        if let Some(err) = resp.get("error") {
                            let msg = err.as_str()
                                .or_else(|| err.get("message").and_then(|m| m.as_str()))
                                .or_else(|| err.get("name").and_then(|n| n.as_str()))
                                .unwrap_or("unknown error");
                            return Err(anyhow::anyhow!("Browser error: {}", msg));
                        }
                        return Ok(resp.get("result").cloned().unwrap_or(json!({})));
                    }
                    // Ignore events and other responses
                }
                Message::Close(_) => {
                    return Err(anyhow::anyhow!("WebSocket closed by browser"));
                }
                Message::Ping(data) => {
                    let _ = self.ws.send(Message::Pong(data)).await;
                    continue;
                }
                _ => continue, // Pong, Binary — ignore
            }
        }
    }

    // ── High-level operations ─────────────────────────────────────

    pub async fn navigate(&mut self, url: &str) -> anyhow::Result<()> {
        match self.kind {
            BrowserKind::Firefox => {
                let ctx = self.context_id.clone().context("No browsing context")?;
                self.send_raw("browsingContext.navigate", json!({
                    "context": ctx,
                    "url": url,
                    "wait": "complete"
                })).await?;

                // Refresh context ID — navigation may have created a new context
                // (e.g., cross-origin redirect)
                if let Ok(tree) = self.send_raw("browsingContext.getTree", json!({})).await {
                    if let Some(contexts) = tree.get("contexts").and_then(|c| c.as_array()) {
                        if let Some(first) = contexts.first() {
                            if let Some(new_ctx) = first.get("context").and_then(|c| c.as_str()) {
                                self.context_id = Some(new_ctx.to_string());
                            }
                        }
                    }
                }
            }
            BrowserKind::Chrome => {
                self.send_raw("Page.navigate", json!({"url": url})).await?;
                // Wait for load event
                self.send_raw("Page.enable", json!({})).await.ok();
                let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(30);
                loop {
                    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                    if remaining.is_zero() { break; }
                    if let Ok(Some(Ok(Message::Text(text)))) =
                        tokio::time::timeout(remaining, self.ws.next()).await
                    {
                        let ev: Value = serde_json::from_str(&text).unwrap_or(json!({}));
                        if ev["method"].as_str() == Some("Page.loadEventFired") { break; }
                    } else { break; }
                }
            }
        }

        // Smart SPA stability poll: only wait if page content is small (likely still loading).
        // Static pages with substantial content skip the poll entirely.
        let content_len = self.evaluate("document.body ? document.body.innerHTML.length : 0")
            .await.ok()
            .and_then(|v| v.as_u64())
            .unwrap_or(0);

        if content_len < 2000 {
            // Page has little content — likely an SPA still rendering. Poll for stability.
            let stability_js = r#"new Promise(resolve => {
                let last = document.body ? document.body.innerHTML.length : 0;
                let stable = 0;
                const check = () => {
                    const now = document.body ? document.body.innerHTML.length : 0;
                    if (now === last && now > 0) {
                        stable++;
                        if (stable >= 3) { resolve(true); return; }
                    } else { stable = 0; }
                    last = now;
                    setTimeout(check, 100);
                };
                setTimeout(check, 50);
            })"#;

            let _ = tokio::time::timeout(
                tokio::time::Duration::from_secs(5),
                self.evaluate_await(stability_js),
            ).await;
        }

        Ok(())
    }

    pub async fn screenshot(&mut self) -> anyhow::Result<String> {
        match self.kind {
            BrowserKind::Firefox => {
                let ctx = self.context_id.clone().context("No browsing context")?;
                let result = self.send_raw("browsingContext.captureScreenshot", json!({
                    "context": ctx
                })).await?;
                Ok(result["data"].as_str().unwrap_or("").to_string())
            }
            BrowserKind::Chrome => {
                let result = self.send_raw("Page.captureScreenshot", json!({"format": "png"})).await?;
                Ok(result["data"].as_str().unwrap_or("").to_string())
            }
        }
    }

    pub async fn evaluate(&mut self, expression: &str) -> anyhow::Result<Value> {
        self.evaluate_inner(expression, false).await
    }

    /// Evaluate with awaitPromise support (for async JS like Promises).
    pub async fn evaluate_await(&mut self, expression: &str) -> anyhow::Result<Value> {
        self.evaluate_inner(expression, true).await
    }

    async fn evaluate_inner(&mut self, expression: &str, await_promise: bool) -> anyhow::Result<Value> {
        match self.kind {
            BrowserKind::Firefox => {
                let ctx = self.context_id.clone().context("No browsing context")?;
                let result = self.send_raw("script.evaluate", json!({
                    "expression": expression,
                    "target": {"context": ctx},
                    "awaitPromise": await_promise,
                    "resultOwnership": "none"
                })).await?;

                // BiDi returns: {result: {type: "string", value: "..."}, realm: "..."}
                // send_raw() already extracts .result from the response envelope.
                let bidi_result = result.get("result").unwrap_or(&result);

                // Check for BiDi error type (e.g. JS exceptions)
                if let Some("error") = bidi_result.get("type").and_then(|t| t.as_str()) {
                    let msg = bidi_result.get("value")
                        .and_then(|v| v.get("message"))
                        .and_then(|m| m.as_str())
                        .or_else(|| bidi_result.get("value").and_then(|v| v.as_str()))
                        .unwrap_or("JavaScript error");
                    return Err(anyhow::anyhow!("JS error: {}", msg));
                }

                let val = match bidi_result.get("type").and_then(|t| t.as_str()) {
                    Some("string") | Some("number") | Some("boolean") =>
                        bidi_result.get("value").cloned().unwrap_or(json!(null)),
                    Some("null") | Some("undefined") => json!(null),
                    Some("array") | Some("object") | Some("map") | Some("set") =>
                        bidi_result.get("value").cloned()
                            .unwrap_or_else(|| bidi_result.clone()),
                    _ => bidi_result.get("value").cloned().unwrap_or(json!(null)),
                };
                Ok(val)
            }
            BrowserKind::Chrome => {
                let result = self.send_raw("Runtime.evaluate", json!({
                    "expression": expression,
                    "returnByValue": true,
                    "awaitPromise": await_promise
                })).await?;

                // Check for JS exceptions
                if let Some(exception) = result.get("exceptionDetails") {
                    let desc = exception.get("text")
                        .or_else(|| exception.pointer("/exception/description"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("JavaScript error");
                    return Err(anyhow::anyhow!("JS error: {}", desc));
                }

                Ok(result.get("result")
                    .and_then(|r| r.get("value"))
                    .cloned()
                    .unwrap_or(json!(null)))
            }
        }
    }

    pub async fn get_title(&mut self) -> anyhow::Result<String> {
        let val = self.evaluate("document.title").await?;
        Ok(val.as_str().unwrap_or("").to_string())
    }

    pub async fn get_content(&mut self) -> anyhow::Result<String> {
        let val = self.evaluate("document.documentElement.outerHTML").await?;
        Ok(val.as_str().unwrap_or("").to_string())
    }

    #[allow(dead_code)]
    pub async fn get_text(&mut self) -> anyhow::Result<String> {
        let val = self.evaluate("document.body?.innerText || ''").await?;
        Ok(val.as_str().unwrap_or("").to_string())
    }

    #[allow(dead_code)]
    pub async fn get_url(&mut self) -> anyhow::Result<String> {
        let val = self.evaluate("window.location.href").await?;
        Ok(val.as_str().unwrap_or("").to_string())
    }

    // ── High-level operations ─────────────────────────────────────

    /// Escape a string for embedding in single-quoted JavaScript strings.
    pub fn js_escape(s: &str) -> String {
        js_escape(s)
    }

    pub async fn query_selector_all(&mut self, selector: &str) -> anyhow::Result<Value> {
        let js = format!(
            r#"JSON.stringify(Array.from(document.querySelectorAll('{sel}')).map((el, i) => ({{
                index: i,
                tag: el.tagName.toLowerCase(),
                text: (el.textContent || '').trim().substring(0, 200),
                value: el.value || '',
                href: el.href || '',
                id: el.id || '',
                className: el.className || '',
                type: el.type || '',
                placeholder: el.placeholder || '',
                disabled: el.disabled || false,
                visible: (() => {{ const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }})(),
                x: Math.round(el.getBoundingClientRect().x),
                y: Math.round(el.getBoundingClientRect().y),
                width: Math.round(el.getBoundingClientRect().width),
                height: Math.round(el.getBoundingClientRect().height),
                center_x: Math.round(el.getBoundingClientRect().x + el.getBoundingClientRect().width / 2),
                center_y: Math.round(el.getBoundingClientRect().y + el.getBoundingClientRect().height / 2),
            }}))))"#,
            sel = Self::js_escape(selector)
        );

        let val = self.evaluate(&js).await?;
        // The result is a JSON string, parse it
        let text = val.as_str().unwrap_or("[]");
        let parsed: Value = serde_json::from_str(text).unwrap_or(json!([]));
        Ok(parsed)
    }

    pub async fn click_selector(&mut self, selector: &str) -> anyhow::Result<Value> {
        let js = format!(
            r#"JSON.stringify((() => {{
                const el = document.querySelector('{sel}');
                if (!el) return {{ success: false, error: 'Element not found: {sel}' }};
                el.scrollIntoView({{ behavior: 'auto', block: 'center', inline: 'center' }});
                const rect = el.getBoundingClientRect();
                if (rect.width === 0 && rect.height === 0) {{
                    const style = getComputedStyle(el);
                    return {{ success: false, error: 'Element not visible', display: style.display, visibility: style.visibility }};
                }}
                el.dispatchEvent(new MouseEvent('mousedown', {{ bubbles: true, cancelable: true, view: window }}));
                el.dispatchEvent(new MouseEvent('mouseup', {{ bubbles: true, cancelable: true, view: window }}));
                el.dispatchEvent(new MouseEvent('click', {{ bubbles: true, cancelable: true, view: window }}));
                return {{ success: true, tag: el.tagName.toLowerCase(), text: (el.textContent||'').trim().substring(0, 100) }};
            }})())"#,
            sel = Self::js_escape(selector)
        );

        let val = self.evaluate(&js).await?;
        let text = val.as_str().unwrap_or("{}");
        Ok(serde_json::from_str(text).unwrap_or(json!({})))
    }

    pub async fn fill_selector(&mut self, selector: &str, value: &str) -> anyhow::Result<Value> {
        let js = format!(
            r#"JSON.stringify((() => {{
                const el = document.querySelector('{sel}');
                if (!el) return {{ success: false, error: 'Element not found: {sel}' }};
                el.scrollIntoView({{ behavior: 'auto', block: 'center' }});
                el.focus();
                // Use native value setter to bypass React/Vue controlled component guards
                const proto = el instanceof HTMLTextAreaElement
                    ? HTMLTextAreaElement.prototype
                    : HTMLInputElement.prototype;
                const nativeSetter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
                if (nativeSetter) {{
                    nativeSetter.call(el, '{val}');
                }} else {{
                    el.value = '{val}';
                }}
                el.dispatchEvent(new Event('input', {{ bubbles: true, composed: true }}));
                el.dispatchEvent(new Event('change', {{ bubbles: true, composed: true }}));
                return {{ success: true, tag: el.tagName.toLowerCase(), value: el.value }};
            }})())"#,
            sel = Self::js_escape(selector),
            val = Self::js_escape(value)
        );

        let val = self.evaluate(&js).await?;
        let text = val.as_str().unwrap_or("{}");
        Ok(serde_json::from_str(text).unwrap_or(json!({})))
    }

    /// Wait for a JS condition to become truthy, polling every 100ms.
    pub async fn wait_for(&mut self, condition_js: &str, timeout_ms: u64) -> anyhow::Result<Value> {
        let poll_interval = tokio::time::Duration::from_millis(100);
        let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(timeout_ms);
        let start = std::time::Instant::now();

        loop {
            match self.evaluate(condition_js).await {
                Ok(result) => {
                    let truthy = match &result {
                        Value::Bool(b) => *b,
                        Value::Number(n) => n.as_f64().unwrap_or(0.0) != 0.0,
                        Value::String(s) => !s.is_empty(),
                        Value::Null => false,
                        _ => true,
                    };
                    if truthy {
                        return Ok(json!({
                            "met": true,
                            "value": result,
                            "elapsed_ms": start.elapsed().as_millis() as u64
                        }));
                    }
                }
                Err(_) => {} // Element may not exist yet — keep polling
            }

            if tokio::time::Instant::now() >= deadline {
                return Ok(json!({
                    "met": false,
                    "timeout": true,
                    "elapsed_ms": start.elapsed().as_millis() as u64
                }));
            }
            tokio::time::sleep(poll_interval).await;
        }
    }

    pub async fn scroll_page(&mut self, direction: &str, pixels: i64, selector: Option<&str>) -> anyhow::Result<Value> {
        if let Some(sel) = selector {
            let js = format!(
                r#"JSON.stringify((() => {{
                    const el = document.querySelector('{sel}');
                    if (!el) return {{ success: false, error: 'Element not found' }};
                    el.scrollIntoView({{ behavior: 'smooth', block: 'center' }});
                    return {{ success: true, scrolledTo: '{sel}' }};
                }})())"#,
                sel = Self::js_escape(sel)
            );
            let val = self.evaluate(&js).await?;
            let text = val.as_str().unwrap_or("{}");
            Ok(serde_json::from_str(text).unwrap_or(json!({})))
        } else {
            let (dx, dy) = match direction {
                "up" => (0, -pixels),
                "down" => (0, pixels),
                "left" => (-pixels, 0),
                "right" => (pixels, 0),
                _ => (0, pixels),
            };
            let js = format!("window.scrollBy({}, {}); JSON.stringify({{success: true, scrollX: window.scrollX, scrollY: window.scrollY}})", dx, dy);
            let val = self.evaluate(&js).await?;
            let text = val.as_str().unwrap_or("{}");
            Ok(serde_json::from_str(text).unwrap_or(json!({})))
        }
    }

    pub async fn hover_element(&mut self, selector: &str) -> anyhow::Result<Value> {
        let js = format!(
            r#"JSON.stringify((() => {{
                const el = document.querySelector('{sel}');
                if (!el) return {{ success: false, error: 'Element not found: {sel}' }};
                el.dispatchEvent(new MouseEvent('mouseenter', {{ bubbles: true }}));
                el.dispatchEvent(new MouseEvent('mouseover', {{ bubbles: true }}));
                return {{ success: true, tag: el.tagName.toLowerCase(), text: (el.textContent||'').trim().substring(0, 100) }};
            }})())"#,
            sel = Self::js_escape(selector)
        );
        let val = self.evaluate(&js).await?;
        let text = val.as_str().unwrap_or("{}");
        Ok(serde_json::from_str(text).unwrap_or(json!({})))
    }

    pub async fn select_option(&mut self, selector: &str, value: Option<&str>, text: Option<&str>) -> anyhow::Result<Value> {
        let match_by = if let Some(v) = value {
            format!("sel.value = '{}';", Self::js_escape(v))
        } else if let Some(t) = text {
            format!(
                "const opt = Array.from(sel.options).find(o => o.textContent.trim() === '{}'); if (opt) sel.value = opt.value; else return {{success:false,error:'Option not found'}};",
                Self::js_escape(t)
            )
        } else {
            return Err(anyhow::anyhow!("Provide either 'value' or 'text' parameter"));
        };

        let js = format!(
            r#"JSON.stringify((() => {{
                const sel = document.querySelector('{selector}');
                if (!sel) return {{ success: false, error: 'Element not found: {selector}' }};
                {match_by}
                sel.dispatchEvent(new Event('change', {{ bubbles: true }}));
                return {{ success: true, selectedValue: sel.value, selectedText: sel.options[sel.selectedIndex]?.text || '' }};
            }})())"#,
            selector = Self::js_escape(selector),
            match_by = match_by
        );
        let val = self.evaluate(&js).await?;
        let text_result = val.as_str().unwrap_or("{}");
        Ok(serde_json::from_str(text_result).unwrap_or(json!({})))
    }
}