Skip to main content

agentmux_srv/server/
browser_capture_read.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a `Browser` `capture` reads from the page, and the check on what it read: the part of
5//! `browser_capture.rs` that asks the host, so the handler keeps to what is stored and told.
6//!
7//! Three ways to read, all by the host, none of which returns the value to the agent:
8//! - the element a reference names (its field value, or the one secret in its text);
9//! - text with no reference of its own, found by the label beside it (`near`), which the host gives a
10//!   reference of its own so the saved element can be marked like any other;
11//! - the page's own copy button (`copy`): the host clicks it with the page's copy intercepted, so the
12//!   value never reaches the system clipboard. A click that commits something waits for the person, as an
13//!   `act` click does.
14
15use axum::response::Response;
16use serde_json::{json, Value};
17
18use super::browser_actions::{note, How, Kind};
19use super::browser_capture::{CaptureRequest, DOWNLOAD_WAIT, HOST_WAIT};
20use agentmux_common::capture_shape::CaptureShape;
21
22use super::browser_capture_shape::miss;
23use super::browser_attention::Waiting;
24use super::browser_click_approval::{approve_click, ClickRefused};
25use super::ui_handlers::{err_response, proxy_value};
26use super::AppState;
27
28/// What the request reads: its reference (empty when `near` names the text instead), and the shape the
29/// value must have. An error says what to give.
30pub(super) fn what_to_read(req: &CaptureRequest) -> Result<(String, Option<CaptureShape>), String> {
31    let ref_ = req.ref_.clone().filter(|r| !r.trim().is_empty());
32    let near = req.near.as_deref().map(str::trim).filter(|n| !n.is_empty());
33    if near.is_some() && (ref_.is_some() || req.download || req.copy) {
34        return Err("near names the text beside a label, instead of a ref: give one or the other, and not with download or copy".into());
35    }
36    if req.download && req.copy {
37        return Err("a ref is a file's download button (download) or a copy button (copy), not both".into());
38    }
39    let shape = CaptureShape::new(req.prefix.as_deref(), req.shape.as_deref(), req.min_length, req.max_length)?;
40    match (ref_, near) {
41        (Some(r), None) => Ok((r, shape)),
42        (None, Some(_)) => Ok((String::new(), shape)),
43        _ => {
44            let what = if req.download {
45                "the button or link that downloads the file"
46            } else if req.copy {
47                "the page's copy button"
48            } else {
49                "the element that shows the secret (or near: the label beside it)"
50            };
51            Err(format!("capture needs the ref of {what} (from snapshot or find)"))
52        }
53    }
54}
55
56/// Ask the host for the value: `{value, origin, ...}`, and the wait that holds a click the person approved
57/// until the host has made it. An error is the answer to give the agent.
58pub(super) async fn read_page(
59    state: &AppState,
60    req: &CaptureRequest,
61    block_id: &str,
62    agent: &str,
63    (ref_, shape): (&str, Option<&CaptureShape>),
64) -> Result<(Value, Option<Waiting>), Response> {
65    let route = if req.download {
66        "capture_download"
67    } else if req.copy {
68        "capture_copy"
69    } else {
70        let body = json!({ "block_id": block_id, "ref": ref_, "near": req.near.as_deref().map(str::trim), "shape": shape });
71        return proxy_value(state, "capture_value", body, HOST_WAIT).await.map(|v| (v, None)).map_err(|(code, e)| err_response(code, e));
72    };
73    let body = |approved: Option<&Value>| json!({ "block_id": block_id, "ref": ref_, "timeout_ms": req.timeout_ms, "approved_as": approved });
74    let first = proxy_value(state, route, body(None), DOWNLOAD_WAIT).await.map_err(|(code, e)| err_response(code, e))?;
75    let Some(ask) = first.get("needs_approval").cloned() else { return Ok((first, None)) };
76    let log = note(block_id, agent, Kind::Capture).target(ref_);
77    match approve_click(state, block_id, agent, &ask).await {
78        Ok((waiting, _)) => proxy_value(state, route, body(Some(&ask)), DOWNLOAD_WAIT).await.map(|v| (v, Some(waiting))).map_err(|(code, e)| err_response(code, e)),
79        Err(ClickRefused::NotAsked(code, e)) => Err(err_response(code, e)),
80        Err(ClickRefused::Asked(how, code, e)) => {
81            log.how(how.unwrap_or(How::Refused(e.clone()))).record(state);
82            Err(err_response(code, format!("nothing was clicked or saved: {e}")))
83        }
84    }
85}
86
87/// A shape is a question about a value the agent can't read: each capture with one is counted, match or miss,
88/// and refused when the agent has used its budget. A capture with no shape is never counted.
89pub(super) fn begin(shape: Option<&CaptureShape>, agent: &str) -> Result<(), String> {
90    if shape.is_some() {
91        super::browser_capture_shape::start(agent)?;
92    }
93    Ok(())
94}
95
96/// The value has the shape the agent gave, or nothing is saved. The answer says only that it did not.
97pub(super) fn check_shape(shape: Option<&CaptureShape>, value: &str, agent: &str) -> Result<(), String> {
98    match shape {
99        Some(s) if !s.matches(value) => {
100            let more = miss(agent);
101            Err(format!("nothing was saved: what the page holds there does not match the shape you gave (it is not shown to you).{more}"))
102        }
103        _ => Ok(()),
104    }
105}
106
107/// A capture with a shape that the host could not read a value for (no value beside the label, none with
108/// the prefix, two of them) is the same answer as a mismatch, and counts as one: the host tests the shape
109/// too, to choose the value, so a failure there says whether one matched.
110pub(super) fn counted(refused: Response, shape: Option<&CaptureShape>, agent: &str) -> Response {
111    if shape.is_some() {
112        let _ = miss(agent);
113    }
114    refused
115}
116
117#[cfg(test)]
118#[path = "browser_capture_read_tests.rs"]
119mod tests;