agentmux_mcp/tools/
browser_waiting.rs1use anyhow::Result;
9use serde_json::Value;
10
11use super::*;
12
13pub(super) const WAITING_PREFIX: &str = "Waiting for the person";
16
17pub(super) fn waiting_text(body: &Value) -> Option<String> {
20 let d = body.get("data").filter(|d| d.get("waiting").and_then(Value::as_bool) == Some(true))?;
21 let id = d.get("request").and_then(Value::as_str).unwrap_or("?");
22 let question = d.get("question").and_then(Value::as_str).unwrap_or("something");
23 let pane = d.get("pane").and_then(Value::as_str).unwrap_or("?");
24 let minutes = d.get("expires_in_secs").and_then(Value::as_u64).map(|s| (s + 59) / 60);
25 let until = minutes.map_or(String::new(), |m| format!(" It stays open for {m} min."));
26 Some(format!(
27 "{WAITING_PREFIX}: {question} (request {id}, pane {pane:?}).{until} Nothing has been done yet. Say in one line what you are \
28 waiting for and END YOUR TURN: the person can ask you questions while they decide, and you are told how it ends. Do not call again \
29 and do not ask again; if you need to take the question back, Browser cancel_request with request {id}, or Browser request_status \
30 if you are unsure whether it is still open."
31 ))
32}
33
34pub(super) async fn request(arguments: &Value, cx: &ToolCtx<'_>, cancel: bool) -> Result<String> {
36 let name = if cancel { "cancel_request" } else { "request_status" };
37 let text_arg = |k: &str| arguments.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
38 let (request, pane) = (text_arg("request"), text_arg("pane"));
39 if request.is_none() && (cancel || pane.is_none()) {
40 anyhow::bail!("Browser {name} needs request (the id a waiting answer gave){}", if cancel { "" } else { " or pane" });
41 }
42 let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
43 require_agent_env(local_url, auth_key, block_id)?;
44 let req = agentmux_common::api_types::UiBrowserRequestRequest { auth: sign_ui_automation_auth()?, request, pane, cancel };
45 let url = format!("{}/api/v1/ui/browser/request", local_url.trim_end_matches('/'));
46 let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&req).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
47 let status = resp.status();
48 if !status.is_success() {
49 let text = resp.text().await.unwrap_or_default();
50 anyhow::bail!("Browser {name} failed: HTTP {status} — {text}");
51 }
52 let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("Browser {name}: bad response: {e}"))?;
53 let d = body.get("data").unwrap_or(&Value::Null);
54 Ok(if cancel {
55 format!("Request {} is taken down: nothing will be done for it, and nobody is waiting for the person's answer any more.", d["request"].as_str().unwrap_or("?"))
56 } else {
57 status_text(d)
58 })
59}
60
61fn status_text(d: &Value) -> String {
63 let id = d["request"].as_str().unwrap_or("?");
64 let question = d["question"].as_str().unwrap_or("?");
65 let ago = |k: &str| d[k].as_u64().map(|s| if s < 90 { format!("{s} s ago") } else { format!("{} min ago", s / 60) }).unwrap_or_default();
66 let detail = d["detail"].as_str().filter(|s| !s.is_empty()).map(|s| format!(" {s}")).unwrap_or_default();
67 match d["status"].as_str().unwrap_or("") {
68 "open" => format!(
69 "Request {id} ({question}) is still waiting for the person (asked {}). End your turn: you are told how it ends.",
70 ago("started_secs_ago")
71 ),
72 "done" => format!("Request {id} ({question}): the person approved it and it was done ({}).{detail}", ago("ended_secs_ago")),
73 "declined" => format!("Request {id} ({question}): the person declined it ({}). Don't retry it; ask them what to do.", ago("ended_secs_ago")),
74 "timed_out" => format!("Request {id} ({question}): nobody answered in time ({}). Ask them in chat before trying again.", ago("ended_secs_ago")),
75 "void" => format!("Request {id} ({question}): void, nothing was done ({}):{detail}", ago("ended_secs_ago")),
76 "failed" => format!("Request {id} ({question}): the person approved it, but it wasn't done ({}):{detail}", ago("ended_secs_ago")),
77 "cancelled" => format!("Request {id} ({question}): you took it back ({}).", ago("ended_secs_ago")),
78 other => format!("Request {id}: {other}."),
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85 use serde_json::json;
86
87 #[test]
88 fn a_waiting_answer_tells_the_agent_to_end_its_turn_and_not_call_again() {
89 let body = json!({ "ok": true, "data": { "waiting": true, "request": "r-1", "kind": "approval", "pane": "p1", "question": "Click \"Send\" on https://a.test/", "expires_in_secs": 598 } });
90 let t = waiting_text(&body).unwrap();
91 assert!(t.starts_with(WAITING_PREFIX));
92 for want in ["request r-1", "Click \"Send\"", "END YOUR TURN", "Do not call again", "cancel_request", "Nothing has been done yet", "10 min"] {
93 assert!(t.contains(want), "{want}: {t}");
94 }
95 }
96
97 #[test]
98 fn any_other_answer_is_not_a_waiting_one() {
99 assert_eq!(waiting_text(&json!({ "ok": true, "data": { "after": null } })), None);
100 assert_eq!(waiting_text(&json!({ "ok": true, "data": { "waiting": false } })), None);
101 assert_eq!(waiting_text(&json!({ "ok": true })), None);
102 }
103
104 #[test]
105 fn each_status_says_what_happened_and_what_to_do() {
106 let d = |status: &str, detail: Option<&str>| {
107 json!({ "request": "r-2", "question": "Click \"Pay\"", "status": status, "detail": detail, "started_secs_ago": 30, "ended_secs_ago": 200 })
108 };
109 assert!(status_text(&d("open", None)).contains("still waiting for the person (asked 30 s ago). End your turn"));
110 assert!(status_text(&d("done", Some("The page is now https://a.test/paid."))).contains("approved it and it was done (3 min ago). The page is now"));
111 assert!(status_text(&d("declined", None)).contains("Don't retry it"));
112 assert!(status_text(&d("timed_out", None)).contains("Ask them in chat"));
113 assert!(status_text(&d("void", Some("the page changed"))).contains("void, nothing was done (3 min ago): the page changed"));
114 assert!(status_text(&d("failed", Some("the form changed"))).contains("wasn't done (3 min ago): the form changed"));
115 assert!(status_text(&d("cancelled", None)).contains("you took it back"));
116 }
117}