Skip to main content

agentmux_mcp/tools/
browser_tool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Browser: one tool for the browser panes an agent drives, with an `action`
5//! (docs/specs/SPEC_MUXAPI_TOOL_CONSOLIDATION_2026_10_15.md §4.2, slice S2). It
6//! replaces OpenBrowser and the sixteen Browser* tools; their handlers
7//! (browser.rs) run each action unchanged. An action that changes the page can
8//! wait and read it again in the same call.
9
10use super::family::{pick, relabeled, Act};
11use super::*;
12
13pub(super) const ACTS: &[Act] = &[
14    Act { action: "open", tool: "OpenBrowser", rename: &[] },
15    Act { action: "snapshot", tool: "BrowserSnapshot", rename: &[] },
16    Act { action: "find", tool: "BrowserFind", rename: &[] },
17    Act { action: "click", tool: "BrowserClick", rename: &[] },
18    Act { action: "fill", tool: "BrowserFill", rename: &[] },
19    Act { action: "request_value", tool: "BrowserRequestValue", rename: &[] },
20    Act { action: "capture", tool: "BrowserCapture", rename: &[] },
21    Act { action: "signin", tool: "BrowserSignin", rename: &[] },
22    Act { action: "generate_password", tool: "BrowserGeneratePassword", rename: &[] },
23    Act { action: "select", tool: "BrowserSelect", rename: &[] },
24    Act { action: "check", tool: "BrowserCheck", rename: &[] },
25    Act { action: "set_files", tool: "BrowserSetFiles", rename: &[] },
26    Act { action: "navigate", tool: "BrowserNavigate", rename: &[] },
27    Act { action: "back", tool: "BrowserBack", rename: &[] },
28    Act { action: "forward", tool: "BrowserForward", rename: &[] },
29    Act { action: "reload", tool: "BrowserReload", rename: &[] },
30    Act { action: "zoom", tool: "BrowserZoom", rename: &[] },
31    Act { action: "scroll", tool: "BrowserScroll", rename: &[] },
32    Act { action: "drag", tool: "BrowserDrag", rename: &[] },
33    Act { action: "locate", tool: "BrowserLocate", rename: &[] },
34    Act { action: "click_at", tool: "BrowserClickAt", rename: &[] },
35    Act { action: "key", tool: "BrowserDispatchKey", rename: &[] },
36    Act { action: "terminal", tool: "BrowserTerminal", rename: &[] },
37    Act { action: "focus", tool: "BrowserFocusElement", rename: &[] },
38    Act { action: "focus_info", tool: "BrowserFocusInfo", rename: &[] },
39    Act {
40        action: "wait",
41        tool: "BrowserWaitFor",
42        rename: &[("until_text", "text"), ("until_url", "url_contains"), ("until_gone", "gone"), ("until_state", "state")],
43    },
44    Act { action: "eval", tool: "BrowserEval", rename: &[] },
45    Act { action: "handoff", tool: "BrowserHandoff", rename: &[] },
46    Act { action: "handoff_status", tool: "BrowserHandoffStatus", rename: &[] },
47    Act { action: "request_status", tool: "BrowserRequestStatus", rename: &[] },
48    Act { action: "cancel_request", tool: "BrowserCancelRequest", rename: &[] },
49    Act { action: "retake", tool: "BrowserRetake", rename: &[] },
50    Act { action: "take_control", tool: "BrowserTakeControl", rename: &[] },
51    Act { action: "release", tool: "BrowserRelease", rename: &[] },
52    Act { action: "request_auto_approve", tool: "BrowserRequestBypass", rename: &[] },
53    Act { action: "stop_auto_approve", tool: "BrowserEndBypass", rename: &[] },
54    Act { action: "list", tool: "BrowserList", rename: &[] },
55    Act { action: "show", tool: "BrowserShow", rename: &[] },
56    Act { action: "hide", tool: "BrowserHide", rename: &[] },
57    Act { action: "log", tool: "BrowserLog", rename: &[] },
58    Act { action: "close", tool: "BrowserClose", rename: &[] },
59];
60
61/// Actions after which `until_*` and `snapshot` may follow in the same call.
62const CHANGES_THE_PAGE: &[&str] = &["click", "click_at", "fill", "select", "check", "key", "navigate", "back", "forward", "reload"];
63
64pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
65    match name {
66        "Browser" => masked(relabeled("Browser", ACTS, run(arguments, cx).await)),
67        _ => Err(not_in_family()),
68    }
69}
70
71/// Everything the agent reads from a Browser call, with card, ID and bank numbers and one-time
72/// codes hidden by their shape: the last line of the secret-field rule (the host hides a secret
73/// *field*'s value; this hides the number a page prints in plain text, or a dialog, a popup title
74/// or the Log repeats). Not grantable: no site grant reaches it.
75fn masked(result: Result<String>) -> Result<String> {
76    use agentmux_common::pii_mask::mask_short_text;
77    match result {
78        Ok(text) => Ok(mask_short_text(&text)),
79        Err(e) => Err(anyhow::anyhow!(mask_short_text(&format!("{e:#}")))),
80    }
81}
82
83/// One Browser call: the action, then any follow-up it asked for.
84async fn run(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
85    let (act, args) = pick("Browser", ACTS, arguments)?;
86    match act.action {
87        "close" => return close(arguments, cx).await,
88        "retake" => return retake(arguments, cx).await,
89        "take_control" => return take_control(arguments, cx).await,
90        "release" => return release(arguments, cx).await,
91        "handoff_status" => return handoff_status(arguments, cx).await,
92        "request_status" => return super::browser_waiting::request(arguments, cx, false).await,
93        "cancel_request" => return super::browser_waiting::request(arguments, cx, true).await,
94        _ => {}
95    }
96    // `wait`'s own conditions are the until_* parameters (pick renamed
97    // them for its handler): for wait they are not a follow-up.
98    // `terminal` waits for its own output (until_text, timeout_seconds), so its until_* is no follow-up either.
99    let is_wait = act.action == "wait" || act.action == "terminal";
100    let follow_wait =
101        !is_wait && ["until_text", "until_url", "until_gone", "until_state"].iter().any(|k| arguments.get(*k).is_some());
102    let follow_snapshot = arguments.get("snapshot").and_then(|v| v.as_bool()).unwrap_or(false);
103    // `wait` is itself the wait, so a snapshot after it is the one follow-up it can take (wait, then read).
104    let reads_after_wait = act.action == "wait";
105    if (follow_wait || (follow_snapshot && !reads_after_wait)) && !CHANGES_THE_PAGE.contains(&act.action) {
106        anyhow::bail!(
107            "until_text/until_url/until_gone/until_state and snapshot follow an action that changes the page ({}); \
108             for action {:?}, call wait or snapshot on its own",
109            CHANGES_THE_PAGE.join(", "),
110            act.action
111        );
112    }
113    // A page dialog the action opened is reported with it, also when the
114    // action failed (a click whose confirm is waiting for the user times out).
115    let mut out = match browser::call(act.tool, &args, cx).await {
116        Ok(out) => out,
117        Err(e) => {
118            let dialogs = browser::dialogs_note(cx).await;
119            return Err(if dialogs.is_empty() { e } else { anyhow::anyhow!("{e}{dialogs}") });
120        }
121    };
122    // Waiting for the person: nothing has happened yet, so the follow-ups have nothing to wait for or read.
123    if out.starts_with(super::browser_waiting::WAITING_PREFIX) {
124        return Ok(out);
125    }
126    // The action has run: a follow-up that fails is reported after its
127    // result, never instead of it, so the agent doesn't repeat a click
128    // that already submitted something.
129    if follow_wait {
130        out = match browser::call("BrowserWaitFor", &follow_wait_args(arguments), cx).await {
131            Ok(waited) => format!("{out}\n\nwait: {waited}"),
132            Err(e) => format!("{out}\n\nwait failed (the {} itself was done): {e}", act.action),
133        };
134    }
135    if follow_snapshot {
136        // An action that navigates leaves the page loading: read it once it has
137        // settled, not the empty page of a moment ago. A page that never settles (3 seconds at most)
138        // is read as it is.
139        if !follow_wait && !reads_after_wait {
140            let settle = json!({ "state": "idle", "timeout_seconds": 3, "pane": arguments.get("pane") });
141            let _ = tokio::time::timeout(std::time::Duration::from_secs(4), browser::call("BrowserWaitFor", &settle, cx)).await;
142        }
143        out = match browser::call("BrowserSnapshot", &only(arguments, &["pane", "scope", "max_text", "include_hidden"]), cx).await {
144            Ok(snap) => format!("{out}\n\nsnapshot:\n{snap}"),
145            Err(e) => format!("{out}\n\nsnapshot failed (the {} itself was done): {e}", act.action),
146        };
147    }
148    out.push_str(&browser::dialogs_note(cx).await);
149    Ok(out)
150}
151
152/// `close`: Stop's `pane` with the tab named: that tab closes, and its pane only when it was the last. With none,
153/// ClosePane would end the caller's own session, so a pane is required and there is no default.
154async fn close(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
155    let pane = arguments.get("pane").and_then(|v| v.as_str()).map(str::trim).filter(|p| !p.is_empty());
156    let Some(pane) = pane.filter(|p| *p != cx.block_id) else {
157        anyhow::bail!("Browser close needs pane: the id Browser open gave you. It never closes your own pane");
158    };
159    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
160    require_agent_env(local_url, auth_key, block_id)?;
161    let req = agentmux_common::api_types::UiBrowserCloseRequest { auth: sign_ui_automation_auth()?, pane: Some(pane.to_string()) };
162    let url = format!("{}/api/v1/ui/browser/close", local_url.trim_end_matches('/'));
163    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&req).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
164    let status = resp.status();
165    if status.as_u16() == 202 {
166        // The pane's user has 10 s to keep it; wait for their answer.
167        let body: Value = resp.json().await.unwrap_or(Value::Null);
168        let now = await_shutdown(client, local_url, auth_key, body["request_id"].as_str().unwrap_or_default(), true).await;
169        return close_pane_outcome_for(pane, &now, body["pane_closes"].as_bool());
170    }
171    if !status.is_success() {
172        let text = resp.text().await.unwrap_or_default();
173        anyhow::bail!("Browser close failed: HTTP {status} — {text}");
174    }
175    Ok(format!("Closed tab {pane:?}"))
176}
177
178/// `retake`: drive again a pane the user took over and gave back. The pane is required (it is not the caller's own), and
179/// a snapshot comes with the answer: the user has been using the page, so what the agent last saw is out of date.
180async fn retake(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
181    let pane = arguments.get("pane").and_then(|v| v.as_str()).map(str::trim).filter(|p| !p.is_empty());
182    let Some(pane) = pane else {
183        anyhow::bail!("Browser retake needs pane: the id of the pane the user took over");
184    };
185    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
186    require_agent_env(local_url, auth_key, block_id)?;
187    let req = agentmux_common::api_types::UiBrowserRetakeRequest { auth: sign_ui_automation_auth()?, pane: Some(pane.to_string()) };
188    let url = format!("{}/api/v1/ui/browser/retake", local_url.trim_end_matches('/'));
189    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&req).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
190    let status = resp.status();
191    if !status.is_success() {
192        let text = resp.text().await.unwrap_or_default();
193        anyhow::bail!("Browser retake failed: HTTP {status} — {text}");
194    }
195    let body: Value = resp.json().await.unwrap_or(Value::Null);
196    let lead = if body.pointer("/data/already").and_then(|v| v.as_bool()) == Some(true) {
197        format!("You already drive pane {pane:?}.")
198    } else {
199        format!("You drive pane {pane:?} again. The user used the page meanwhile, so read it before you act; an auto-approve you had is not back (ask again if you need it).")
200    };
201    match browser::call("BrowserSnapshot", &json!({ "pane": pane }), cx).await {
202        Ok(snap) => Ok(format!("{lead}\n\nsnapshot:\n{snap}")),
203        Err(e) => Ok(format!("{lead}\n\nsnapshot failed (the retake itself was done): {e}")),
204    }
205}
206
207/// How long a take_control waits for srv: the person has 120 s to answer the pane's question, and the shared client's own
208/// limit (10 s) would end the call long before.
209const TAKE_CONTROL_WAIT: std::time::Duration = std::time::Duration::from_secs(150);
210
211/// POST `body` to srv's `/api/v1/ui/browser/{route}` and read its answer, or fail with what srv said. `wait` is the time
212/// limit for a call that waits for the person; none: the client's own.
213async fn control_call<T: serde::Serialize>(route: &str, body: &T, wait: Option<std::time::Duration>, cx: &ToolCtx<'_>) -> Result<Value> {
214    let ToolCtx { local_url, auth_key, client, .. } = *cx;
215    let url = format!("{}/api/v1/ui/browser/{route}", local_url.trim_end_matches('/'));
216    let mut request = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(body);
217    if let Some(wait) = wait {
218        request = request.timeout(wait);
219    }
220    let resp = request.send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
221    let status = resp.status();
222    if !status.is_success() {
223        let text = resp.text().await.unwrap_or_default();
224        anyhow::bail!("Browser {route} failed: HTTP {status} — {text}");
225    }
226    Ok(resp.json().await.unwrap_or(Value::Null))
227}
228
229/// The pane a take_control or release names: required, since neither defaults to the caller's own.
230fn named_pane(arguments: &Value, action: &str, what: &str) -> Result<String> {
231    let pane = arguments.get("pane").and_then(|v| v.as_str()).map(str::trim).filter(|p| !p.is_empty());
232    pane.map(str::to_string).ok_or_else(|| anyhow::anyhow!("Browser {action} needs pane: {what}"))
233}
234
235/// `take_control`: drive a browser pane the agent did not open. srv may ask the person in the pane first (their Personal
236/// sign-ins, a pane another agent drives, a pane they used a moment ago) and the call waits for the answer.
237async fn take_control(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
238    let pane = named_pane(arguments, "take_control", "the id of a browser pane (Pane layout lists them)")?;
239    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
240    require_agent_env(local_url, auth_key, block_id)?;
241    let allowed_origins = arguments.get("allowed_origins").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|o| o.as_str().map(str::to_string)).collect());
242    let req = agentmux_common::api_types::UiBrowserTakeControlRequest { auth: sign_ui_automation_auth()?, pane: Some(pane.clone()), allowed_origins };
243    let body = control_call("take_control", &req, Some(TAKE_CONTROL_WAIT), cx).await?;
244    let data = &body["data"];
245    let lead = if data["already"].as_bool() == Some(true) {
246        format!("You already drive pane {pane:?}.")
247    } else {
248        let limit = data["limited_to"].as_array().map(|l| l.iter().filter_map(|o| o.as_str()).collect::<Vec<_>>().join(", ")).filter(|l| !l.is_empty());
249        let limit = limit.map_or_else(String::new, |l| format!(" It is limited to {l}."));
250        format!(
251            "You drive pane {pane:?}, which you did not open; it browses as {}.{limit} The user sees you driving it and can take it back with Take over. Read the page before you act: it was not yours until now.",
252            data["browsing_as"].as_str().unwrap_or("its own profile")
253        )
254    };
255    match browser::call("BrowserSnapshot", &json!({ "pane": pane }), cx).await {
256        Ok(snap) => Ok(format!("{lead}
257
258snapshot:
259{snap}")),
260        Err(e) => Ok(format!("{lead}
261
262snapshot failed (taking control itself was done): {e}")),
263    }
264}
265
266/// `release`: stop driving a pane, so that it has no driver and another agent can take it without asking the person.
267async fn release(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
268    let pane = named_pane(arguments, "release", "the id of a pane you drive")?;
269    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
270    require_agent_env(local_url, auth_key, block_id)?;
271    let req = agentmux_common::api_types::UiBrowserReleaseRequest { auth: sign_ui_automation_auth()?, pane: Some(pane.clone()) };
272    control_call("release", &req, None, cx).await?;
273    Ok(format!("You no longer drive pane {pane:?}; it stays open for whoever uses it next."))
274}
275
276/// `handoff_status`: what became of a hand-off, by its id or the newest on a pane.
277async fn handoff_status(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
278    let text_arg = |k: &str| arguments.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
279    let (handoff_id, pane) = (text_arg("handoff_id"), text_arg("pane"));
280    if handoff_id.is_none() && pane.is_none() {
281        anyhow::bail!("Browser handoff_status needs handoff_id (the hand-off's answer gave it) or pane");
282    }
283    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
284    require_agent_env(local_url, auth_key, block_id)?;
285    let req = agentmux_common::api_types::UiBrowserHandoffStatusRequest { auth: sign_ui_automation_auth()?, pane, handoff_id };
286    let url = format!("{}/api/v1/ui/browser/handoff_status", local_url.trim_end_matches('/'));
287    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&req).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
288    let status = resp.status();
289    if !status.is_success() {
290        let text = resp.text().await.unwrap_or_default();
291        anyhow::bail!("Browser handoff_status failed: HTTP {status} — {text}");
292    }
293    let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("Browser handoff_status: bad response: {e}"))?;
294    Ok(handoff_status_text(body.get("data").unwrap_or(&Value::Null)))
295}
296
297/// What the agent reads for a hand-off's status.
298fn handoff_status_text(d: &Value) -> String {
299    let id = d["handoff_id"].as_str().unwrap_or("?");
300    let pane = d["pane"].as_str().unwrap_or("?");
301    let ago = |k: &str| d[k].as_u64().map(|s| if s < 90 { format!("{s} s ago") } else { format!("{} min ago", s / 60) });
302    // How long the banner was up before the answer: an early Done reads as one.
303    let after = || d["open_secs"].as_u64().map(|s| format!(" after {}", agentmux_common::time::span_words(s))).unwrap_or_default();
304    match d["status"].as_str().unwrap_or("") {
305        "pending" => format!("Hand-off {id} on pane {pane:?} is still waiting for the user (asked {}).", ago("started_secs_ago").unwrap_or_default()),
306        "done" => format!("Hand-off {id}: the user clicked Done{} ({}). Take a new snapshot: don't assume what they changed.", after(), ago("ended_secs_ago").unwrap_or_default()),
307        "cancelled" => format!("Hand-off {id}: the user clicked Cancel{} ({}). Ask them in chat how to proceed.", after(), ago("ended_secs_ago").unwrap_or_default()),
308        "timed_out" => format!("Hand-off {id}: the user didn't answer in time ({}). Ask them in chat.", ago("ended_secs_ago").unwrap_or_default()),
309        _ => format!(
310            "Hand-off {id}: abandoned ({}): your call ended before the user answered, so its request went down with it and nobody can answer it. Make a new hand-off if you still need the user.",
311            ago("ended_secs_ago").unwrap_or_default()
312        ),
313    }
314}
315
316/// The wait that follows an action, from its `until_*` parameters only: the
317/// action's own `text` (a fill's value) is not a wait condition.
318fn follow_wait_args(arguments: &Value) -> Value {
319    let mut out = serde_json::Map::new();
320    for (ours, theirs) in [
321        ("pane", "pane"),
322        ("until_text", "text"),
323        ("until_url", "url_contains"),
324        ("until_gone", "gone"),
325        ("until_state", "state"),
326        ("timeout_seconds", "timeout_seconds"),
327    ] {
328        if let Some(v) = arguments.get(ours) {
329            out.insert(theirs.to_string(), v.clone());
330        }
331    }
332    Value::Object(out)
333}
334
335/// `arguments` with only `keys`, for a follow-up handler that checks what it's given.
336fn only(arguments: &Value, keys: &[&str]) -> Value {
337    let mut out = serde_json::Map::new();
338    for k in keys {
339        if let Some(v) = arguments.get(*k) {
340            out.insert((*k).to_string(), v.clone());
341        }
342    }
343    Value::Object(out)
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    fn cx_parts() -> (reqwest::Client, LoopRegistry, std::sync::atomic::AtomicU64) {
351        (reqwest::Client::new(), LoopRegistry::default(), std::sync::atomic::AtomicU64::new(0))
352    }
353
354    #[test]
355    fn every_action_is_in_the_schema() {
356        let schema: Value = serde_json::from_str(crate::tool_schemas::BROWSER_TOOL).unwrap();
357        let mut listed: Vec<&str> = schema["inputSchema"]["properties"]["action"]["enum"]
358            .as_array()
359            .unwrap()
360            .iter()
361            .filter_map(|v| v.as_str())
362            .collect();
363        let mut want = super::super::family::action_names(ACTS);
364        listed.sort();
365        want.sort();
366        assert_eq!(listed, want);
367    }
368
369    #[test]
370    fn wait_takes_the_until_parameters() {
371        let (act, args) = pick("Browser", ACTS, &json!({ "action": "wait", "until_url": "/done", "pane": "p" })).unwrap();
372        assert_eq!(act.tool, "BrowserWaitFor");
373        assert_eq!(args, json!({ "url_contains": "/done", "pane": "p" }));
374        assert_eq!(only(&json!({ "a": 1, "b": 2 }), &["b", "c"]), json!({ "b": 2 }));
375    }
376
377    #[test]
378    fn wait_takes_until_state_and_a_follow_up_wait_passes_it_on() {
379        let (_, args) = pick("Browser", ACTS, &json!({ "action": "wait", "until_state": "idle", "pane": "p" })).unwrap();
380        assert_eq!(args, json!({ "state": "idle", "pane": "p" }));
381        let args = json!({ "action": "click", "pane": "p", "ref": "e2", "until_state": "load" });
382        assert_eq!(follow_wait_args(&args), json!({ "pane": "p", "state": "load" }));
383    }
384
385    #[test]
386    fn a_follow_up_wait_uses_the_until_parameters_not_the_actions_text() {
387        let args = json!({ "action": "fill", "pane": "p", "ref": "e2", "text": "hello", "until_url": "/next", "timeout_seconds": 5 });
388        assert_eq!(follow_wait_args(&args), json!({ "pane": "p", "url_contains": "/next", "timeout_seconds": 5 }));
389    }
390
391    /// wait with its conditions reaches its handler (which, with no srv here,
392    /// fails on the missing environment) instead of the follow-up guard.
393    #[tokio::test]
394    async fn wait_with_its_conditions_is_not_taken_for_a_follow_up() {
395        let (client, loops, counter) = cx_parts();
396        let cx = ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
397        for args in [
398            json!({ "action": "wait", "until_text": "Done" }),
399            json!({ "action": "wait", "until_url": "/next", "pane": "p" }),
400            json!({ "action": "wait", "until_gone": "e4" }),
401            // wait, then read the page: the one follow-up a wait takes.
402            json!({ "action": "wait", "until_state": "load", "snapshot": true }),
403            json!({ "action": "wait", "until_text": "Done", "snapshot": true, "pane": "p" }),
404        ] {
405            let e = call("Browser", &args, &cx).await.unwrap_err().to_string();
406            assert!(!e.contains("follow an action that changes the page"), "{args}: {e}");
407        }
408    }
409
410    /// ClosePane with no pane ends the caller's own session, so `close` must name one: no default, even the
411    /// caller's own pane, and a blank id is none.
412    #[tokio::test]
413    async fn close_needs_a_pane_and_never_defaults_to_the_callers_own() {
414        let (client, loops, counter) = cx_parts();
415        let cx = ToolCtx { local_url: "", auth_key: "", block_id: "my-block", client: &client, loops: &loops, loop_counter: &counter };
416        for args in [json!({ "action": "close" }), json!({ "action": "close", "pane": "  " })] {
417            let e = call("Browser", &args, &cx).await.unwrap_err().to_string();
418            assert!(e.contains("needs pane") && e.contains("never closes your own pane"), "{args}: {e}");
419        }
420        let own = call("Browser", &json!({ "action": "close", "pane": "my-block" }), &cx).await.unwrap_err().to_string();
421        assert!(own.contains("never closes your own pane"), "{own}");
422        // With a pane it reaches ClosePane (which, with no srv here, fails on the missing environment).
423        let e = call("Browser", &json!({ "action": "close", "pane": "p1" }), &cx).await.unwrap_err().to_string();
424        assert!(!e.contains("needs pane"), "{e}");
425    }
426
427    /// The person has 120 s to answer a take_control question (srv's `ASK_FOR`): the call must outlast it, and the shared
428    /// client's 10 s limit must not be the one that applies.
429    #[test]
430    fn a_take_control_waits_longer_than_the_person_has_to_answer() {
431        assert!(TAKE_CONTROL_WAIT > std::time::Duration::from_secs(120));
432        assert!(TAKE_CONTROL_WAIT > std::time::Duration::from_secs(10));
433    }
434
435    /// Taking control and releasing name the pane they act on: neither defaults to the caller's own.
436    #[tokio::test]
437    async fn take_control_and_release_need_a_pane() {
438        let (client, loops, counter) = cx_parts();
439        let cx = ToolCtx { local_url: "", auth_key: "", block_id: "my-block", client: &client, loops: &loops, loop_counter: &counter };
440        for action in ["take_control", "release"] {
441            let e = call("Browser", &json!({ "action": action }), &cx).await.unwrap_err().to_string();
442            assert!(e.contains(&format!("{action} needs pane")), "{e}");
443            let e = call("Browser", &json!({ "action": action, "pane": "p1" }), &cx).await.unwrap_err().to_string();
444            assert!(!e.contains("needs pane"), "{e}");
445        }
446    }
447
448    /// A retake names the pane it takes back and a status names the hand-off or the pane: neither defaults to the caller's own.
449    #[tokio::test]
450    async fn retake_and_handoff_status_need_something_to_name() {
451        let (client, loops, counter) = cx_parts();
452        let cx = ToolCtx { local_url: "", auth_key: "", block_id: "my-block", client: &client, loops: &loops, loop_counter: &counter };
453        let e = call("Browser", &json!({ "action": "retake", "pane": "  " }), &cx).await.unwrap_err().to_string();
454        assert!(e.contains("retake needs pane"), "{e}");
455        let e = call("Browser", &json!({ "action": "handoff_status" }), &cx).await.unwrap_err().to_string();
456        assert!(e.contains("needs handoff_id"), "{e}");
457        // With one they reach srv (which, with none here, fails on the missing environment).
458        let e = call("Browser", &json!({ "action": "retake", "pane": "p1" }), &cx).await.unwrap_err().to_string();
459        assert!(!e.contains("needs pane"), "{e}");
460        let e = call("Browser", &json!({ "action": "handoff_status", "pane": "p1" }), &cx).await.unwrap_err().to_string();
461        assert!(!e.contains("needs handoff_id"), "{e}");
462    }
463
464    #[test]
465    fn a_hand_off_status_says_what_to_do_next() {
466        let d = |status: &str| json!({ "handoff_id": "h1", "pane": "p1", "status": status, "started_secs_ago": 30, "ended_secs_ago": 200 });
467        assert!(handoff_status_text(&d("pending")).contains("still waiting for the user (asked 30 s ago)"));
468        assert!(handoff_status_text(&d("done")).contains("clicked Done (3 min ago)") && handoff_status_text(&d("done")).contains("snapshot"));
469        assert!(handoff_status_text(&d("cancelled")).contains("clicked Cancel"));
470        // With how long the banner was up, so an early Done reads as one.
471        let timed = json!({ "handoff_id": "h1", "pane": "p1", "status": "done", "started_secs_ago": 30, "ended_secs_ago": 20, "open_secs": 4 });
472        assert!(handoff_status_text(&timed).contains("clicked Done after 4 s (20 s ago)"), "{}", handoff_status_text(&timed));
473        assert!(handoff_status_text(&d("timed_out")).contains("didn't answer in time"));
474        let abandoned = handoff_status_text(&d("abandoned"));
475        assert!(abandoned.contains("abandoned") && abandoned.contains("nobody can answer it") && abandoned.contains("new hand-off"), "{abandoned}");
476    }
477
478    #[test]
479    fn a_hand_off_answer_says_how_long_the_banner_was_up_and_doubts_a_quick_done() {
480        use super::super::browser::handoff_answer_text as text;
481        assert_eq!(
482            text("done", Some(42)),
483            "The user clicked Done after 42 s. Take a new snapshot: don't assume what they changed."
484        );
485        let quick = text("done", Some(1));
486        assert!(quick.contains("clicked Done after 1 s.") && quick.contains("That was quick") && quick.contains("really changed"), "{quick}");
487        assert!(!text("done", Some(5)).contains("quick"), "five seconds is the person's own pace");
488        // From an srv that does not say: the answer is as it was.
489        assert!(text("done", None).starts_with("The user clicked Done. Take a new snapshot"));
490        assert!(text("cancelled", Some(90)).starts_with("The user clicked Cancel after 1 min."));
491        assert!(text("timed_out", Some(15 * 60)).starts_with("The user didn't answer in time after 15 min."));
492    }
493
494    #[tokio::test]
495    async fn a_follow_up_is_refused_after_an_action_that_reads() {
496        let (client, loops, counter) = cx_parts();
497        let cx = ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
498        let e = call("Browser", &json!({ "action": "eval", "script": "1", "snapshot": true }), &cx).await.unwrap_err().to_string();
499        assert!(e.contains("follow an action that changes the page"), "{e}");
500    }
501}
502
503#[cfg(test)]
504mod mask_tests {
505    use super::*;
506
507    #[test]
508    fn every_answer_and_error_has_card_numbers_and_codes_hidden() {
509        let ok = masked(Ok("- text \"Paid with 4111 1111 1111 1111, CVV 123\"
510".into())).unwrap();
511        assert!(!ok.contains("4111") && ok.contains("[card number hidden]") && ok.contains("[code hidden]"), "{ok}");
512        let err = masked(Err(anyhow::anyhow!("the page said: your verification code is 482913"))).unwrap_err().to_string();
513        assert!(!err.contains("482913") && err.contains("[code hidden]"), "{err}");
514        assert_eq!(masked(Ok("pane 7f3a2c: done".into())).unwrap(), "pane 7f3a2c: done");
515    }
516}