agentmux_mcp/tools/
browser_scroll.rs1use agentmux_common::browser_control_types::UiBrowserScrollRequest;
8
9use super::*;
10
11fn number(arguments: &Value, key: &str) -> Result<Option<f64>> {
13 match arguments.get(key) {
14 None | Some(Value::Null) => Ok(None),
15 Some(v) => v.as_f64().map(Some).ok_or_else(|| anyhow::anyhow!("{key} is a number of pixels")),
16 }
17}
18
19pub(super) async fn run_scroll(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
20 let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
21 require_agent_env(local_url, auth_key, block_id)?;
22 let auth = sign_ui_automation_auth()?;
23 let (dx, dy) = (number(arguments, "dx")?, number(arguments, "dy")?);
24 let ref_ = arguments.get("ref").and_then(Value::as_str).map(str::trim).filter(|r| !r.is_empty()).map(str::to_string);
25 if ref_.is_some() == (dx.is_some_and(|d| d != 0.0) || dy.is_some_and(|d| d != 0.0)) {
26 anyhow::bail!("scroll takes either ref (an element to bring into view) or dy and dx (pixels: down and right are positive), one of them");
27 }
28 let req_url = format!("{}/api/v1/ui/browser/scroll", local_url.trim_end_matches('/'));
29 let resp = client
30 .post(&req_url)
31 .header(AUTH_KEY_HEADER, auth_key)
32 .json(&UiBrowserScrollRequest { auth, pane: pane_arg(arguments), ref_, dx, dy })
33 .send()
34 .await
35 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
36 if !resp.status().is_success() {
37 let status = resp.status();
38 let text = resp.text().await.unwrap_or_default();
39 anyhow::bail!("scroll failed: HTTP {status} - {text}");
40 }
41 let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("scroll: bad response: {e}"))?;
42 Ok(scrolled_text(body.get("data").unwrap_or(&Value::Null)))
43}
44
45fn scrolled_text(d: &Value) -> String {
47 let pair = |k: &str| {
48 let a = d.get(k).and_then(Value::as_array)?;
49 Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))
50 };
51 let (Some(content), Some(viewport), Some(from)) = (pair("content"), pair("viewport"), pair("from")) else {
52 return "Scrolled.".to_string();
53 };
54 let (x, y) = (d.get("x").and_then(Value::as_f64).unwrap_or(0.0), d.get("y").and_then(Value::as_f64).unwrap_or(0.0));
55 let below = (content.1 - viewport.1 - y).max(0.0).round();
56 let mut s = format!("Scrolled: at y {} of {} (viewport {}): {} above, {} below", y.round(), content.1.round(), viewport.1.round(), y.round(), below);
57 if content.0 > viewport.0 + 1.0 {
58 s.push_str(&format!("; x {} of {}: {} to the right", x.round(), content.0.round(), (content.0 - viewport.0 - x).max(0.0).round()));
59 }
60 s.push('.');
61 if from == (x, y) {
62 if d.get("by_ref").and_then(Value::as_bool) == Some(true) {
63 s.push_str(" The page did not move: the element was already in view.");
64 } else {
65 s.push_str(" The page did not move: it is at that end, or nothing under the middle of the view scrolls.");
66 }
67 }
68 s.push_str(" Take a new snapshot to read what is in view now; a screenshot with full_page shows the whole page.");
69 s
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75 use serde_json::json;
76
77 #[test]
78 fn the_answer_says_where_the_page_is_and_how_much_is_left_below() {
79 let d = json!({ "x": 0.0, "y": 1200.0, "content": [1019.0, 4000.0], "viewport": [1019.0, 650.0], "from": [0.0, 600.0] });
80 let t = scrolled_text(&d);
81 assert!(t.starts_with("Scrolled: at y 1200 of 4000 (viewport 650): 1200 above, 2150 below."), "{t}");
82 assert!(!t.contains("did not move"));
83 }
84
85 #[test]
86 fn a_page_that_stayed_where_it_was_says_so() {
87 let d = json!({ "x": 0.0, "y": 3350.0, "content": [1019.0, 4000.0], "viewport": [1019.0, 650.0], "from": [0.0, 3350.0] });
88 assert!(scrolled_text(&d).contains("did not move"));
89 }
90
91 #[test]
92 fn an_element_already_in_view_is_not_called_the_end_of_the_page() {
93 let d = json!({ "x": 0.0, "y": 300.0, "content": [1019.0, 4000.0], "viewport": [1019.0, 650.0], "from": [0.0, 300.0], "by_ref": true });
94 let t = scrolled_text(&d);
95 assert!(t.contains("the element was already in view"), "{t}");
96 assert!(!t.contains("at that end"), "{t}");
97 }
98
99 #[test]
100 fn a_number_that_is_not_one_is_refused() {
101 assert_eq!(number(&json!({ "dy": 600 }), "dy").unwrap(), Some(600.0));
102 assert_eq!(number(&json!({}), "dy").unwrap(), None);
103 assert!(number(&json!({ "dy": "a lot" }), "dy").is_err());
104 }
105}