Skip to main content

agentmux_mcp/tools/
browser_locate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` actions `locate` and `click_at`: the visual fallback for a region the page's accessibility
5//! tree can't describe (a canvas UI, the picture of a button, a control with no accessible name). The
6//! agent looks at a screenshot and names a point; the host finds what a click there would land on and gives
7//! it a reference. `click_at` is that and then a click on the reference, so a committing click still asks
8//! the person, the click must land on the element, and a frame off the pane's allowed sites is refused
9//! (docs/specs/SPEC_BROWSER_PANE_FORMS_IN_FRAMES_AND_VISUAL_FALLBACK_2026_10_16.md §4.6). There is no
10//! `type_at`: to type, locate the field and fill its reference, so the secret guard always sees it.
11
12use agentmux_common::api_types::UiBrowserLocateRequest;
13
14use super::*;
15
16/// What a locate found.
17#[derive(Debug, PartialEq)]
18struct Located {
19    ref_: String,
20    line: String,
21    frame: Option<String>,
22    secret: bool,
23}
24
25fn located(data: &Value) -> Option<Located> {
26    Some(Located {
27        ref_: data.get("ref")?.as_str()?.to_string(),
28        line: data.get("line").and_then(Value::as_str).unwrap_or("").to_string(),
29        frame: data.get("frame").and_then(Value::as_str).map(str::to_string),
30        secret: data.get("secret").and_then(Value::as_bool).unwrap_or(false),
31    })
32}
33
34/// `x` or `y`, a position in the screenshot.
35fn coordinate(arguments: &Value, key: &str) -> Result<f64> {
36    arguments
37        .get(key)
38        .and_then(Value::as_f64)
39        .filter(|v| v.is_finite() && *v >= 0.0)
40        .ok_or_else(|| anyhow::anyhow!("missing required parameter: {key} (a position in the screenshot in pixels, from its top left corner)"))
41}
42
43/// The element and where it is, as the agent reads it.
44fn found_text(found: &Located, x: f64, y: f64) -> String {
45    let frame = found.frame.as_deref().map(|f| format!(" in a frame from {f}")).unwrap_or_default();
46    let secret = if found.secret { " It is a secret field: you can click it, but its value is never read or filled by you; hand off for that." } else { "" };
47    format!("At ({x}, {y}) there is {}{frame} [ref={}].{secret}", found.line, found.ref_)
48}
49
50/// Ask the host what is at the point.
51async fn locate(arguments: &Value, cx: &ToolCtx<'_>) -> Result<(Located, f64, f64)> {
52    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
53    require_agent_env(local_url, auth_key, block_id)?;
54    let auth = sign_ui_automation_auth()?;
55    let (x, y) = (coordinate(arguments, "x")?, coordinate(arguments, "y")?);
56    let image_width = arguments.get("image_width").and_then(Value::as_f64);
57    let req_url = format!("{}/api/v1/ui/browser/locate", local_url.trim_end_matches('/'));
58    let resp = client
59        .post(&req_url)
60        .header(AUTH_KEY_HEADER, auth_key)
61        .json(&UiBrowserLocateRequest { auth, pane: pane_arg(arguments), x, y, image_width })
62        .send()
63        .await
64        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
65    if !resp.status().is_success() {
66        let status = resp.status();
67        let text = resp.text().await.unwrap_or_default();
68        anyhow::bail!("locate failed: HTTP {status} — {text}");
69    }
70    let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("locate: bad response: {e}"))?;
71    let found = located(body.get("data").unwrap_or(&Value::Null)).ok_or_else(|| anyhow::anyhow!("locate: the host found nothing at ({x}, {y})"))?;
72    Ok((found, x, y))
73}
74
75pub(super) async fn run_locate(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
76    let (found, x, y) = locate(arguments, cx).await?;
77    Ok(format!(
78        "{} Nothing was clicked: click it with Browser click, or fill, select or check it, with that ref. References last until the next snapshot or navigation.",
79        found_text(&found, x, y)
80    ))
81}
82
83pub(super) async fn run_click_at(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
84    let (found, x, y) = locate(arguments, cx).await?;
85    let click = json!({ "ref": found.ref_, "pane": arguments.get("pane") });
86    let out = super::browser::run_act("BrowserClick", &click, cx).await?;
87    // A click waiting for the person says so on its own; it is the answer as it is.
88    if out.starts_with(super::browser_waiting::WAITING_PREFIX) {
89        return Ok(out);
90    }
91    Ok(format!("{}\n{out}", found_text(&found, x, y)))
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn the_hosts_answer_is_read_back_as_a_reference_and_a_line() {
100        let d = json!({ "ref": "n1e1", "line": "button \"Next\"", "url": "https://x.example/", "secret": false });
101        assert_eq!(located(&d), Some(Located { ref_: "n1e1".into(), line: "button \"Next\"".into(), frame: None, secret: false }));
102        assert_eq!(located(&json!({})), None, "no reference, no element");
103    }
104
105    #[test]
106    fn a_point_must_be_in_the_image() {
107        assert_eq!(coordinate(&json!({ "x": 12.5 }), "x").unwrap(), 12.5);
108        assert!(coordinate(&json!({ "x": -1 }), "x").is_err());
109        assert!(coordinate(&json!({ "x": "7" }), "x").unwrap_err().to_string().contains("missing required parameter: x"));
110        assert!(coordinate(&json!({}), "y").is_err());
111    }
112
113    #[test]
114    fn the_answer_names_the_element_its_frame_and_its_reference() {
115        let f = Located { ref_: "n2e1".into(), line: "textbox \"Card number\"".into(), frame: Some("https://pay.example".into()), secret: false };
116        let t = found_text(&f, 40.0, 90.0);
117        assert!(t.starts_with("At (40, 90) there is textbox \"Card number\" in a frame from https://pay.example [ref=n2e1]."), "{t}");
118        let s = found_text(&Located { secret: true, frame: None, ..f }, 1.0, 2.0);
119        assert!(s.contains("secret field"), "{s}");
120        assert!(!s.contains("frame from"), "{s}");
121    }
122}