Skip to main content

agentmux_srv/server/
browser_click_approval.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The person's approval of a committing click (browser spec §5.4): a click that
5//! submits a form, or a button named like Send, Pay or Delete, waits for them in
6//! its pane's banner. `act` clicks and `Browser` `capture` of a download use it.
7
8use axum::http::StatusCode;
9use axum::response::IntoResponse;
10use serde_json::json;
11
12use super::browser_actions::How;
13use super::ui_handlers::banner_for;
14use super::AppState;
15
16/// Why a committing click wasn't approved: the banner couldn't be raised, or the
17/// person answered (how, when the Log says so) no, too late, or took the pane over.
18pub(crate) enum ClickRefused {
19    NotAsked(StatusCode, String),
20    Asked(Option<How>, StatusCode, String),
21}
22
23/// A committing click's request, put up and not yet answered: what settling the answer needs.
24pub(crate) struct Asked {
25    banner_at: String,
26    owner_before: Option<String>,
27    asked_at: std::time::Instant,
28}
29
30/// How long the person has to answer an approval.
31const WAIT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
32
33/// Put the approval of the committing click `ask` describes up in its pane's banner (spec §5.4) without waiting
34/// for the answer. The summary is shown, not the fingerprint of everything the click sends (hidden controls
35/// included): that stays in `ask`, for the host's check before the approved click.
36pub(crate) fn raise_approval(
37    state: &AppState,
38    block_id: &str,
39    agent: &str,
40    ask: &serde_json::Value,
41) -> Result<(super::browser_attention::Raised, Asked), ClickRefused> {
42    let (banner_at, in_window) = banner_for(block_id);
43    let mut banner = ask.clone();
44    let exception = super::browser_bypass_routes::payment_exception(block_id, agent, ask);
45    if let Some(b) = banner.as_object_mut() {
46        b.remove("fingerprint");
47        b.insert("window".to_string(), json!(in_window));
48        if let Some(note) = exception {
49            let why = ask.get("why").and_then(|v| v.as_str()).unwrap_or("");
50            b.insert("why".to_string(), json!(if why.is_empty() { note.to_string() } else { format!("{why}; {note}") }));
51        }
52    }
53    let (owner_before, asked_at) = (super::browser_owner::owner_of(&banner_at), std::time::Instant::now());
54    let raised = super::browser_attention::raise(state, &banner_at, agent, super::browser_attention::Kind::Approval, banner)
55        .map_err(|e| ClickRefused::NotAsked(e.status(), e.to_string()))?;
56    Ok((raised, Asked { banner_at, owner_before, asked_at }))
57}
58
59/// A background session the click asks about is shown before the question goes up; refused at once when it cannot be.
60async fn shown_to_ask(state: &AppState, block_id: &str) -> Result<(), ClickRefused> {
61    let (at, _) = banner_for(block_id);
62    super::browser_sessions::show_to_ask(state, &at).await.map_err(|why| ClickRefused::NotAsked(StatusCode::CONFLICT, why))
63}
64
65/// What the person's answer means for the click: `Ok` holds the pane locked (the returned [`Waiting`]) for the
66/// click to be made; `Err` says why there is none.
67pub(crate) fn settle_approval(
68    asked: &Asked,
69    block_id: &str,
70    ask: &serde_json::Value,
71    answer: super::browser_attention::Answer,
72    waiting: super::browser_attention::Waiting,
73) -> Result<(super::browser_attention::Waiting, std::time::Instant), ClickRefused> {
74    use super::browser_attention::Answer;
75    let took_over = super::browser_owner::owner_of(&asked.banner_at) != asked.owner_before;
76    match answer {
77        // The user may have taken the pane over while the banner was up:
78        // their Take over wins over an Approve that comes after it.
79        Answer::Yes | Answer::YesAlways | Answer::YesAsking if took_over => Err(ClickRefused::Asked(
80            None,
81            StatusCode::FORBIDDEN,
82            "the user took over this pane, so the approved click wasn't made".to_string(),
83        )),
84        Answer::Yes | Answer::YesAlways | Answer::YesAsking => {
85            super::browser_dialog::note_approved_click(block_id, ask);
86            Ok((waiting, asked.asked_at))
87        }
88        // Taking the pane over answers its requests as Cancelled: that is not the person's "no".
89        Answer::Cancelled if took_over => Err(ClickRefused::Asked(
90            None,
91            StatusCode::FORBIDDEN,
92            "the user took over this pane, so the click wasn't made".to_string(),
93        )),
94        Answer::Cancelled => Err(ClickRefused::Asked(
95            Some(How::Declined),
96            StatusCode::FORBIDDEN,
97            "the user didn't approve this action: don't retry it; ask them what to do".to_string(),
98        )),
99        Answer::TimedOut => Err(ClickRefused::Asked(
100            Some(How::TimedOut),
101            StatusCode::REQUEST_TIMEOUT,
102            "the user didn't answer the approval within 10 minutes; ask them in chat before trying again".to_string(),
103        )),
104    }
105}
106
107/// Asks the person to approve the committing click `ask` describes, in its pane's
108/// banner (spec §5.4). `Ok` holds the pane locked until it is dropped, so the form
109/// can't change between what they approved and what is sent; make the approved
110/// click before dropping it.
111pub(crate) async fn approve_click(
112    state: &AppState,
113    block_id: &str,
114    agent: &str,
115    ask: &serde_json::Value,
116) -> Result<(super::browser_attention::Waiting, std::time::Instant), ClickRefused> {
117    shown_to_ask(state, block_id).await?;
118    let (raised, asked) = raise_approval(state, block_id, agent, ask)?;
119    let (answer, waiting) = raised.answer(Some(WAIT)).await;
120    settle_approval(&asked, block_id, ask, answer, waiting)
121}
122
123/// The question the agent is told it waits on: the click's own words and its page.
124fn question_of(ask: &serde_json::Value) -> String {
125    let s = |k: &str| ask.get(k).and_then(|v| v.as_str()).unwrap_or("");
126    let question = match (s("what"), s("page")) {
127        ("", "") => "a committing click".to_string(),
128        (what, "") => what.to_string(),
129        (what, page) => format!("{what} on {page}"),
130    };
131    // This is the agent's copy (the waiting notice and the request's status): the person's prompt has the
132    // click's own words, the agent gets them without anything shaped like a secret.
133    agentmux_common::secret_shape::scrub(&question)
134}
135
136/// Where the approved click left the page, for the agent's note.
137fn where_text(clicked: &serde_json::Value) -> String {
138    match clicked.pointer("/page/url").and_then(|v| v.as_str()).filter(|u| !u.is_empty()) {
139        Some(url) => format!("The page is now {url}."),
140        None => "Take a new snapshot to see the page.".to_string(),
141    }
142}
143
144/// The state a click that wasn't made leaves its request in.
145fn refused_state(how: Option<&How>, why: &str) -> super::browser_waiting::State {
146    use super::browser_waiting::State;
147    match how {
148        Some(How::Declined) => State::Declined,
149        Some(How::TimedOut) => State::TimedOut,
150        _ => State::Void(why.to_string()),
151    }
152}
153
154/// The tail of a committing click that wasn't let through: ask the person about
155/// `ask`, then make the click the same way once they approve (`approved_body`,
156/// sent to the host's `route`, carries what they were shown). Used by `act` and
157/// by Enter and Space taken as a click.
158///
159/// If the person hasn't answered within the grace, the call returns "waiting" with the request's id and
160/// the agent ends its turn ([`super::browser_waiting`]); a task of srv's makes the click on their approval
161/// and tells the agent how it went.
162pub(crate) async fn ask_then_click(
163    state: &AppState,
164    block_id: &str,
165    agent: &str,
166    route: &str,
167    ask: &serde_json::Value,
168    approved_body: serde_json::Value,
169    log: impl Fn() -> super::browser_actions::Note,
170) -> axum::response::Response {
171    ask_then_click_within(super::browser_waiting::grace(), state, block_id, agent, route, ask, approved_body, log).await
172}
173
174/// [`ask_then_click`] with the grace given (the tests', which don't wait 8 s).
175#[allow(clippy::too_many_arguments)]
176async fn ask_then_click_within(
177    grace: std::time::Duration,
178    state: &AppState,
179    block_id: &str,
180    agent: &str,
181    route: &str,
182    ask: &serde_json::Value,
183    approved_body: serde_json::Value,
184    log: impl Fn() -> super::browser_actions::Note,
185) -> axum::response::Response {
186    use super::ui_handlers::{err_response, proxy_value};
187    let refuse = |e: ClickRefused| match e {
188        ClickRefused::NotAsked(code, e) => err_response(code, e),
189        ClickRefused::Asked(how, code, e) => match how {
190            Some(how) => log().asked(ask).how(how).fail(state, code, e),
191            None => log().asked(ask).fail(state, code, e),
192        },
193    };
194    if let Err(e) = shown_to_ask(state, block_id).await {
195        return refuse(e);
196    }
197    let (raised, asked) = match raise_approval(state, block_id, agent, ask) {
198        Ok(r) => r,
199        Err(e) => return refuse(e),
200    };
201    let id = raised.id().to_string();
202    let settled = match raised.answer_within(grace).await {
203        Ok((answer, waiting)) => settle_approval(&asked, block_id, ask, answer, waiting),
204        Err(raised) => {
205            let question = question_of(ask);
206            super::browser_waiting::open(&id, agent, &asked.banner_at, "approval", &question, WAIT.saturating_sub(asked.asked_at.elapsed()));
207            let (state, block_id, agent, route, ask, note) =
208                (state.clone(), block_id.to_string(), agent.to_string(), route.to_string(), ask.clone(), log());
209            let task_id = id.clone();
210            tokio::spawn(async move {
211                let (super::browser_attention::Settled { answer, by_agent }, waiting) =
212                    raised.settled(Some(WAIT.saturating_sub(asked.asked_at.elapsed()))).await;
213                // The agent took the question back itself: nothing is clicked and nobody is woken.
214                if by_agent {
215                    drop(waiting);
216                    note.asked(&ask).how(How::Refused("taken back by the agent".to_string())).fail(&state, StatusCode::CONFLICT, String::new());
217                    super::browser_waiting::finish(&task_id, super::browser_waiting::State::Cancelled);
218                    return;
219                }
220                let settled = match settle_approval(&asked, &block_id, &ask, answer, waiting) {
221                    Ok((_waiting, asked_at)) => {
222                        let clicked = proxy_value(&state, &route, approved_body, std::time::Duration::from_secs(20)).await;
223                        let made = super::browser_actions::approved_by_user(clicked, asked_at.elapsed());
224                        let result = match &made {
225                            Ok(data) => super::browser_waiting::State::Done(where_text(data)),
226                            Err((_, e)) => super::browser_waiting::State::Failed(e.clone()),
227                        };
228                        note.asked(&ask).how(How::Approved).outcome(&state, made);
229                        result
230                    }
231                    Err(ClickRefused::Asked(how, code, e)) => {
232                        let result = refused_state(how.as_ref(), &e);
233                        match how {
234                            Some(how) => note.asked(&ask).how(how).fail(&state, code, e),
235                            None => note.asked(&ask).fail(&state, code, e),
236                        };
237                        result
238                    }
239                    Err(ClickRefused::NotAsked(_, e)) => super::browser_waiting::State::Void(e),
240                };
241                // An agent that took the question down itself settled it first, and knows.
242                if super::browser_waiting::finish(&task_id, settled.clone()) {
243                    let text = super::browser_waiting::outcome_text(&task_id, "approval", &question_of(&ask), &settled);
244                    super::browser_waiting::wake(&agent, text).await;
245                }
246            });
247            return (StatusCode::OK, axum::Json(json!({ "ok": true, "data": super::browser_waiting::waiting_json(&id) }))).into_response();
248        }
249    };
250    match settled {
251        Ok((_waiting, asked_at)) => {
252            let clicked = proxy_value(state, route, approved_body, std::time::Duration::from_secs(20)).await;
253            log().asked(ask).how(How::Approved).outcome(state, super::browser_actions::approved_by_user(clicked, asked_at.elapsed()))
254        }
255        Err(e) => refuse(e),
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::super::browser_actions::{note, Kind};
262    use super::super::browser_attention::{self, Answer};
263    use super::super::browser_waiting as waiting;
264    use super::*;
265    use std::sync::atomic::{AtomicUsize, Ordering};
266    use std::sync::Arc;
267    use std::time::Duration;
268
269    const AGENT: &str = "agent-click";
270
271    /// A host whose `act` answers like an approved click and counts how often it is asked.
272    async fn fake_host(state: &AppState) -> Arc<AtomicUsize> {
273        use axum::{routing::post, Json, Router};
274        let clicks = Arc::new(AtomicUsize::new(0));
275        let seen = clicks.clone();
276        let app = Router::new().route(
277            "/agentmux/browser/act",
278            post(move |Json(_b): Json<serde_json::Value>| {
279                let seen = seen.clone();
280                async move {
281                    seen.fetch_add(1, Ordering::SeqCst);
282                    Json(json!({ "ok": true, "data": { "page": { "url": "https://a.test/sent", "title": "", "changed": true } } }))
283                }
284            }),
285        );
286        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
287        let port = listener.local_addr().unwrap().port();
288        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
289        *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port, token: "host-ipc-token".into() });
290        clicks
291    }
292
293    fn ask() -> serde_json::Value {
294        json!({ "what": "Click \"Send\"", "page": "https://a.test/form", "fingerprint": "fp" })
295    }
296
297    async fn body_of(r: axum::response::Response) -> (StatusCode, serde_json::Value) {
298        let code = r.status();
299        let bytes = axum::body::to_bytes(r.into_body(), usize::MAX).await.unwrap();
300        (code, serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null))
301    }
302
303    async fn settled(id: &str) -> waiting::Status {
304        for _ in 0..150 {
305            let s = waiting::status(AGENT, Some(id), None).unwrap();
306            if s.state != "open" {
307                return s;
308            }
309            tokio::time::sleep(Duration::from_millis(20)).await;
310        }
311        panic!("request {id} never settled");
312    }
313
314    /// The call, with `grace`, on `pane`; whatever it answered.
315    async fn call(state: &AppState, pane: &str, grace: Duration) -> (StatusCode, serde_json::Value) {
316        let log = || note(pane, AGENT, Kind::Click);
317        body_of(ask_then_click_within(grace, state, pane, AGENT, "act", &ask(), json!({ "block_id": pane, "approved": true }), log).await).await
318    }
319
320    fn pane(state: &AppState) -> String {
321        let pane = uuid::Uuid::new_v4().to_string();
322        browser_attention::tests::browser_block(state, &pane);
323        pane
324    }
325
326    #[tokio::test]
327    async fn a_quick_allow_still_returns_the_finished_click() {
328        let state = crate::server::tests::test_state();
329        let clicks = fake_host(&state).await;
330        let pane = pane(&state);
331        let (answered_state, answered_pane) = (state.clone(), pane.clone());
332        tokio::spawn(async move {
333            for _ in 0..200 {
334                if let Some(id) = browser_attention::tests::banner(&answered_state, &answered_pane)["id"].as_str() {
335                    let _ = browser_attention::resolve(id, &answered_pane, Answer::Yes);
336                    return;
337                }
338                tokio::time::sleep(Duration::from_millis(10)).await;
339            }
340        });
341        let (code, body) = call(&state, &pane, Duration::from_secs(10)).await;
342        assert_eq!(code, StatusCode::OK, "{body}");
343        assert!(body["data"].get("waiting").is_none(), "it answered with the finished result: {body}");
344        assert_eq!(body["data"]["approved_by_user"], true);
345        assert_eq!(clicks.load(Ordering::SeqCst), 1);
346        assert_eq!(waiting::open_on(&pane), None, "nothing was left waiting");
347    }
348
349    #[tokio::test]
350    async fn a_slow_allow_returns_waiting_then_clicks_once_and_settles_done() {
351        let state = crate::server::tests::test_state();
352        let clicks = fake_host(&state).await;
353        let pane = pane(&state);
354        let (code, body) = call(&state, &pane, Duration::from_millis(30)).await;
355        assert_eq!(code, StatusCode::OK, "{body}");
356        let id = body["data"]["request"].as_str().expect("waiting names the request").to_string();
357        assert_eq!((body["data"]["waiting"].as_bool(), body["data"]["kind"].as_str()), (Some(true), Some("approval")));
358        assert!(body["data"]["question"].as_str().unwrap().contains("Send"));
359        assert_eq!(clicks.load(Ordering::SeqCst), 0, "nothing is clicked before the person answers");
360        // The banner stays up, and the agent's other calls on the pane are refused with the request's id.
361        assert_eq!(browser_attention::tests::banner(&state, &pane)["kind"], "approval");
362        let refused = crate::server::ui_handlers::not_waiting_on_user(&pane).unwrap_err().1;
363        assert!(refused.contains(&id) && refused.contains("end your turn"), "{refused}");
364        browser_attention::resolve(&id, &pane, Answer::Yes).unwrap();
365        let s = settled(&id).await;
366        assert_eq!((s.state, s.detail.as_deref()), ("done", Some("The page is now https://a.test/sent.")));
367        assert_eq!(clicks.load(Ordering::SeqCst), 1, "the approved click is made once");
368        assert!(browser_attention::tests::banner(&state, &pane).is_null(), "the banner comes down");
369        assert!(crate::server::ui_handlers::not_waiting_on_user(&pane).is_ok());
370    }
371
372    #[tokio::test]
373    async fn a_declined_request_clicks_nothing_and_says_declined() {
374        let state = crate::server::tests::test_state();
375        let clicks = fake_host(&state).await;
376        let pane = pane(&state);
377        let (_, body) = call(&state, &pane, Duration::from_millis(30)).await;
378        let id = body["data"]["request"].as_str().unwrap().to_string();
379        browser_attention::resolve(&id, &pane, Answer::Cancelled).unwrap();
380        assert_eq!(settled(&id).await.state, "declined");
381        assert_eq!(clicks.load(Ordering::SeqCst), 0);
382    }
383
384    #[tokio::test]
385    async fn an_agent_that_takes_its_request_back_ends_it_without_a_click() {
386        let state = crate::server::tests::test_state();
387        let clicks = fake_host(&state).await;
388        let pane = pane(&state);
389        let (_, body) = call(&state, &pane, Duration::from_millis(30)).await;
390        let id = body["data"]["request"].as_str().unwrap().to_string();
391        let at = waiting::open_pane_of(AGENT, &id).unwrap();
392        browser_attention::withdraw(&id, &at).unwrap();
393        assert_eq!(settled(&id).await.state, "cancelled");
394        assert_eq!(clicks.load(Ordering::SeqCst), 0);
395        assert!(browser_attention::tests::banner(&state, &pane).is_null());
396    }
397
398    #[tokio::test]
399    async fn an_answer_that_came_first_stands_against_a_late_cancel() {
400        let state = crate::server::tests::test_state();
401        let clicks = fake_host(&state).await;
402        let pane = pane(&state);
403        let (_, body) = call(&state, &pane, Duration::from_millis(30)).await;
404        let id = body["data"]["request"].as_str().unwrap().to_string();
405        // The person's Allow is in; the agent's cancel starts after it.
406        browser_attention::resolve(&id, &pane, Answer::Yes).unwrap();
407        let at = waiting::open_pane_of(AGENT, &id).unwrap();
408        assert!(browser_attention::withdraw(&id, &at).is_err(), "the request was already answered");
409        let s = settled(&id).await;
410        assert_eq!(s.state, "done", "the approved click is made and the agent is told");
411        assert_eq!(clicks.load(Ordering::SeqCst), 1);
412    }
413
414    #[tokio::test]
415    async fn a_person_who_cancels_while_the_agent_cancels_is_read_as_one_or_the_other_never_both() {
416        let state = crate::server::tests::test_state();
417        let clicks = fake_host(&state).await;
418        let pane = pane(&state);
419        let (_, body) = call(&state, &pane, Duration::from_millis(30)).await;
420        let id = body["data"]["request"].as_str().unwrap().to_string();
421        // The person's Cancel is in; the agent's cancel starts after it and finds the request answered.
422        browser_attention::resolve(&id, &pane, Answer::Cancelled).unwrap();
423        let at = waiting::open_pane_of(AGENT, &id).unwrap();
424        assert!(browser_attention::withdraw(&id, &at).is_err(), "the person's answer settled it");
425        assert_eq!(settled(&id).await.state, "declined", "the agent is told it was declined, not that it cancelled");
426        assert_eq!(clicks.load(Ordering::SeqCst), 0);
427    }
428
429    #[tokio::test]
430    async fn a_background_session_that_cannot_be_shown_is_not_asked_and_the_click_is_refused_at_once() {
431        let state = crate::server::tests::test_state();
432        let clicks = fake_host(&state).await;
433        let pane = pane(&state);
434        crate::server::pane_openers::record_floating(&pane, AGENT, true, None);
435        let refused = approve_click(&state, &pane, AGENT, &ask()).await.err().expect("refused");
436        match refused {
437            ClickRefused::NotAsked(code, why) => {
438                assert_eq!(code, StatusCode::CONFLICT);
439                assert!(why.contains("background session") && why.contains("not made"), "{why}");
440            }
441            ClickRefused::Asked(..) => panic!("nothing was asked"),
442        }
443        assert!(browser_attention::tests::banner(&state, &pane).is_null(), "no question is left waiting unseen");
444        assert_eq!(clicks.load(Ordering::SeqCst), 0);
445        crate::server::pane_openers::forget(&pane);
446    }
447
448    #[test]
449    fn a_click_that_was_not_made_settles_by_why() {
450        use super::super::browser_waiting::State;
451        assert_eq!(refused_state(Some(&How::Declined), "x"), State::Declined);
452        assert_eq!(refused_state(Some(&How::TimedOut), "x"), State::TimedOut);
453        assert_eq!(refused_state(None, "the user took over this pane"), State::Void("the user took over this pane".to_string()));
454        assert_eq!(question_of(&ask()), "Click \"Send\" on https://a.test/form");
455        assert_eq!(where_text(&json!({ "page": { "url": "https://a.test/x" } })), "The page is now https://a.test/x.");
456        assert!(where_text(&json!({})).contains("snapshot"));
457    }
458}