Skip to main content

agentmux_srv/server/
browser_dialog.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A page's own dialogs (alert, confirm, prompt, "Leave site?") in a browser
5//! pane an agent drives (docs/specs/SPEC_BROWSER_PANE_NATIVE_DIALOGS_2026_10_17.md).
6//! The host parks each one and asks here (`/api/v1/host/browser_dialog`); this
7//! decides by policy (§5), or asks the person in the pane and answers the host
8//! later. The agent can never accept a confirm itself: only Auto-approve, for
9//! the confirm that follows its own click, or the person.
10
11use std::collections::{HashMap, VecDeque};
12use std::sync::{Mutex, OnceLock};
13use std::time::{Duration, Instant};
14
15use axum::extract::State;
16use axum::http::StatusCode;
17use axum::response::IntoResponse;
18use axum::Json;
19use serde_json::{json, Value};
20
21use crate::server::browser_attention::{self, Answer, Kind};
22use crate::server::ui_handlers::{banner_for, err_response, from_host, get_host_ipc, proxy_ack, verified_block_id};
23use crate::server::AppState;
24
25/// How long after a committing click a confirm still counts as its own (§5.2).
26const PAIR_WINDOW: Duration = Duration::from_secs(5);
27/// How long the person has to answer. The host gives up a minute later.
28const ASK_TIMEOUT: Duration = Duration::from_secs(10 * 60);
29/// Dialog outcomes kept per agent until its next `Browser` call reads them.
30const LOG_MAX: usize = 20;
31/// The page's words kept and shown: no more than this.
32const MESSAGE_MAX: usize = 300;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(crate) enum How {
36    /// Made under Auto-approve, without asking.
37    Auto,
38    /// The person approved it in the banner.
39    Approved,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(crate) enum DialogKind {
44    Alert,
45    Confirm,
46    Prompt,
47    BeforeUnload,
48}
49
50impl DialogKind {
51    fn parse(s: &str) -> Option<Self> {
52        match s {
53            "alert" => Some(Self::Alert),
54            "confirm" => Some(Self::Confirm),
55            "prompt" => Some(Self::Prompt),
56            "beforeunload" => Some(Self::BeforeUnload),
57            _ => None,
58        }
59    }
60
61    fn as_str(self) -> &'static str {
62        match self {
63            Self::Alert => "alert",
64            Self::Confirm => "confirm",
65            Self::Prompt => "prompt",
66            Self::BeforeUnload => "beforeunload",
67        }
68    }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub(crate) enum Decision {
73    Accept(String),
74    Cancel(String),
75    Ask(String),
76}
77
78struct Click {
79    at: Instant,
80    label: String,
81    how: How,
82    paired: bool,
83}
84
85fn clicks() -> std::sync::MutexGuard<'static, HashMap<String, Click>> {
86    static C: OnceLock<Mutex<HashMap<String, Click>>> = OnceLock::new();
87    C.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
88}
89
90/// Remember a committing click about to be made on `target` (a pane or popup
91/// window), so the confirm it opens can be matched to it. Called before the
92/// click is sent: the page shows its confirm while the click is still running.
93pub(crate) fn note_click(target: &str, label: &str, how: How) {
94    let mut c = clicks();
95    c.retain(|_, k| k.at.elapsed() < PAIR_WINDOW);
96    c.insert(target.to_string(), Click { at: Instant::now(), label: label.to_string(), how, paired: false });
97}
98
99/// [`note_click`] for a click the person approved in the banner; `ask` is the
100/// approval it was shown as.
101pub(crate) fn note_approved_click(target: &str, ask: &Value) {
102    note_click(target, ask.get("what").and_then(|v| v.as_str()).unwrap_or(""), How::Approved);
103}
104
105/// The click a dialog on `target` belongs to: one made there within the
106/// window and not matched to a dialog yet. One click, one confirm.
107fn pair(target: &str) -> Option<(How, String)> {
108    let mut c = clicks();
109    let k = c.get_mut(target)?;
110    if k.paired || k.at.elapsed() >= PAIR_WINDOW {
111        return None;
112    }
113    k.paired = true;
114    Some((k.how, k.label.clone()))
115}
116
117/// Words that mean a dialog is about a secret. Such a dialog is never
118/// answered for the agent: it only ever turns an accept into a question (§5.3).
119fn about_a_secret(message: &str) -> bool {
120    let m = message.to_ascii_lowercase();
121    let words: Vec<&str> = m.split(|c: char| !c.is_ascii_alphanumeric()).filter(|s| !s.is_empty()).collect();
122    let word = |w: &str| words.contains(&w);
123    ["password", "passcode", "passphrase", "pin", "otp", "cvv", "cvc", "2fa", "mfa"].iter().any(|w| word(w))
124        || ["security code", "verification code", "one-time", "one time code", "secret"].iter().any(|p| m.contains(p))
125}
126
127/// The policy (§5.1). `paired` is the click the dialog follows, if any;
128/// `covered` says whether Auto-approve covers the site that showed it.
129pub(crate) fn decide(kind: DialogKind, message: &str, paired: Option<(How, &str)>, covered: bool) -> Decision {
130    match kind {
131        DialogKind::Alert => Decision::Accept("it only informs".to_string()),
132        DialogKind::Prompt => Decision::Cancel("it asks for typed text, which isn't answered for an agent".to_string()),
133        DialogKind::Confirm | DialogKind::BeforeUnload => match paired {
134            None => Decision::Ask("the page asked on its own, not right after a click of yours".to_string()),
135            Some((How::Approved, _)) => {
136                Decision::Ask("the user approved your click, not the page's question that followed it".to_string())
137            }
138            Some((How::Auto, _)) if !covered => {
139                Decision::Ask("it came from a site auto-approve doesn't cover".to_string())
140            }
141            Some((How::Auto, _)) if crate::server::browser_bypass::is_payment(message) => {
142                Decision::Ask("it is about a payment".to_string())
143            }
144            Some((How::Auto, _)) if about_a_secret(message) => Decision::Ask("it is about a secret".to_string()),
145            Some((How::Auto, label)) => Decision::Accept(format!("auto-approve, right after your click on {label:?}")),
146        },
147    }
148}
149
150fn log() -> std::sync::MutexGuard<'static, HashMap<String, VecDeque<Value>>> {
151    static L: OnceLock<Mutex<HashMap<String, VecDeque<Value>>>> = OnceLock::new();
152    L.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
153}
154
155pub(crate) fn record(agent: &str, target: &str, kind: &str, message: &str, decision: &str, reason: &str) {
156    tracing::info!(agent_id = %agent, target = %target, kind = %kind, decision = %decision, reason = %reason, "[browser-dialog] page dialog");
157    if agent.is_empty() {
158        return;
159    }
160    let mut l = log();
161    let q = l.entry(agent.to_string()).or_default();
162    if q.len() >= LOG_MAX {
163        q.pop_front();
164    }
165    q.push_back(json!({
166        "pane": target, "kind": kind, "message": message, "decision": decision, "reason": reason,
167        "at": chrono::Utc::now().timestamp_millis(),
168    }));
169}
170
171/// One Audit row for a download the host saved into an agent's workspace without a dialog, or refused: the
172/// site (the pane's page), the file and its size, as the host worded them in `message`. The agent is
173/// `standing` for it: the person's setting allowed it, nothing was asked. Nothing was opened or run.
174fn audit_download(state: &AppState, agent: &str, pane: &str, saved: bool, message: &str) {
175    if agent.is_empty() {
176        return;
177    }
178    let url = state
179        .mstore
180        .get::<crate::backend::obj::Block>(pane)
181        .ok()
182        .flatten()
183        .and_then(|b| b.meta.get("url").and_then(Value::as_str).map(str::to_string))
184        .unwrap_or_default();
185    let site = agentmux_common::allowed_origins::target_origin(&url).unwrap_or_else(|| "a page".to_string());
186    let summary = format!("{site} sent a download to the pane {agent} is driving");
187    let (answer, error) = if saved {
188        (format!("saved {message}; not opened"), None)
189    } else {
190        (format!("not saved: {message}"), Some(message))
191    };
192    state.reactive_handler.log_sensitive_op_audit(
193        Some(agent),
194        agent,
195        "browser_download",
196        saved,
197        error,
198        &uuid::Uuid::new_v4().to_string(),
199        Some(&summary),
200        Some(&summary),
201        Some(&answer),
202        Some("low"),
203        true,
204    );
205}
206
207/// Dialogs the host said ended (navigation, close) while srv was asking or
208/// about to ask about them: their question's outcome isn't the person's
209/// answer, and the host has nothing left to answer. Bounded: an id stays
210/// only until its question notices, or until it is old.
211fn ended() -> std::sync::MutexGuard<'static, VecDeque<String>> {
212    static E: OnceLock<Mutex<VecDeque<String>>> = OnceLock::new();
213    E.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
214}
215
216fn mark_ended(id: &str) {
217    let mut e = ended();
218    if e.len() >= 64 {
219        e.pop_front();
220    }
221    e.push_back(id.to_string());
222}
223
224/// Whether dialog `id` ended; forgets it once asked.
225fn take_ended(id: &str) -> bool {
226    let mut e = ended();
227    let Some(i) = e.iter().position(|x| x == id) else { return false };
228    e.remove(i);
229    true
230}
231
232/// The dialogs `agent`'s panes showed since it last asked, oldest first.
233pub(crate) fn drain(agent: &str) -> Vec<Value> {
234    log().remove(agent).map(Vec::from).unwrap_or_default()
235}
236
237fn clip(s: &str) -> String {
238    let s = s.trim();
239    if s.chars().count() <= MESSAGE_MAX {
240        return s.to_string();
241    }
242    let mut out: String = s.chars().take(MESSAGE_MAX).collect();
243    out.push('…');
244    out
245}
246
247/// Tell the host how a parked dialog was answered.
248async fn answer_host(state: &AppState, id: &str, accept: bool) {
249    let Ok(host) = get_host_ipc(state).await else { return };
250    if proxy_ack(state, &host, "dialog_answer", json!({ "id": id, "accept": accept })).await.is_err() {
251        tracing::warn!(id = %id, "[browser-dialog] couldn't answer the host; its own timer will cancel the dialog");
252    }
253}
254
255/// What the agent reads about a file chooser the page opened: what it asked for, and its title.
256fn chooser_message(ask: &str, title: &str) -> String {
257    if title.is_empty() {
258        format!("the page asked to {ask}")
259    } else {
260        format!("the page asked to {ask}: {title}")
261    }
262}
263
264/// Why the chooser was cancelled, and what to do. Only a file the agent puts in an input with `set_files`
265/// goes up; a folder has no such door from a pane the agent drives. (A Save As is never cancelled: a download opens it.)
266fn chooser_reason(ask: &str) -> String {
267    if ask == "choose a file" || ask == "choose several files" {
268        "AgentMux doesn't open the system file chooser in a pane you drive. Use Browser set_files with the page's file input to attach files from your workspace".to_string()
269    } else {
270        format!("AgentMux doesn't open the system file chooser in a pane you drive, and a page can't {ask} from one")
271    }
272}
273
274/// A page's own file chooser: kept for the agent when its grant has the uploads power, else cancelled
275/// by the host, and the agent is told what to do instead. Answers the host's `decision`.
276fn chooser_decision(state: &AppState, agent: &str, target: &str, banner_at: &str, ask: &str, title: &str, origin: &str) -> &'static str {
277    let said = chooser_message(ask, title);
278    if crate::server::browser_chooser::holds(state, target, agent, origin, ask) {
279        record(agent, target, "file_chooser", &said, "held", &crate::server::browser_chooser::held_reason());
280        return "hold";
281    }
282    record(agent, target, "file_chooser", &said, "cancelled", &chooser_reason(ask));
283    crate::server::browser_chooser::tell_person(state, banner_at, ask);
284    "cancel"
285}
286
287/// What the agent reads about a refusal the host reports, and what to do about it. `shown` is only a scheme or a host.
288fn notice_words(notice: &str, shown: &str) -> (String, &'static str) {
289    match notice {
290        "external_protocol" => (
291            format!("a navigation to a {shown}: address was refused"),
292            "AgentMux only loads web pages in a pane, and never hands an address to a program on the computer (mailto:, zoommtg: and the like) or opens a local file by address. If the task needs one, tell the person; don't look for another way in",
293        ),
294        "certificate_error" => (
295            format!("{shown} has a certificate that isn't trusted"),
296            "AgentMux doesn't continue past a certificate warning, and nothing the agent can do clicks through it. Tell the person which site and why you need it",
297        ),
298        // `shown` is the host's own words: `<name> (<size>) to <path>`, or why nothing was saved.
299        "download_saved" => (
300            format!("saved {shown}"),
301            "AgentMux saved it into your workspace's downloads folder without a dialog; it was not opened and nothing was made executable",
302        ),
303        "download_refused" => (
304            format!("a download was not saved: {shown}"),
305            "nothing was written to disk; if the file is needed, tell the person",
306        ),
307        "auth_expired" => (
308            format!("the sign-in prompt for {shown} timed out after 5 minutes without an answer"),
309            "The person is asked for a username and password in the app; nothing the agent can do answers it. Load the page again to ask again, or tell the person you need it",
310        ),
311        // A sign-in prompt (HTTP Basic or Digest) the site raised. `shown` is the site and the realm's name, never a value.
312        "auth_required" => (
313            format!("{shown} asks for a sign-in and the page waits for it, blank until it is answered"),
314            "No saved sign-in of this pane's profile could be used. If Vault list shows a login for this site and realm, ask for it with Vault share (the entry and a reason) from a tab of your own profile, then load the page again. Otherwise the person can type it into the prompt shown in the pane, or save one in Vault; nothing the agent can do types it. The prompt gives up after 5 minutes. Tell the person which site you need",
315        ),
316        "auth_waiting_approval" => (
317            format!("{shown} asks for a sign-in; this profile has a saved one, and the person is asked to approve using it"),
318            "The browser types it itself and you never see it. The page stays blank until the person answers (it gives up after 5 minutes); you are told what happens next. Tell the person if it is urgent",
319        ),
320        "auth_answered" => (
321            format!("{shown}: the saved sign-in was used"),
322            "The page loads if the site accepts it. If the site refuses it you are told, and nothing else is tried",
323        ),
324        "auth_refused" => (
325            format!("{shown} refused the saved sign-in"),
326            "The saved password is probably out of date. Nothing was changed or deleted and the page shows the site's own 401. Tell the person to update that sign-in in Vault",
327        ),
328        "auth_denied" => (
329            format!("the person did not approve using the saved sign-in for {shown}"),
330            "The page shows the site's own 401. Don't ask again unless the person says to",
331        ),
332        _ => (format!("the host refused something: {shown}"), "the host refused it"),
333    }
334}
335
336/// What the log says became of a notice: saved or answered are not refusals, and waiting is not either.
337fn notice_decision(notice: &str) -> &'static str {
338    match notice {
339        "download_saved" => "saved",
340        "auth_answered" => "answered",
341        "auth_waiting_approval" => "waiting",
342        _ => "blocked",
343    }
344}
345
346/// `POST /api/v1/host/browser_dialog` — the host parked a page's dialog in an
347/// agent-driven pane and asks what to do (dialogs spec §4.2). Body
348/// `{id, target, kind, message, origin}`; answers `accept`, `cancel`, or
349/// `parked` (the person is asked; the answer goes to the host's
350/// `dialog_answer` later). `{id, target, ended: true}`: the dialog ended on
351/// its own (navigation, close), so a question about it comes down. `suppressed`:
352/// the host cancelled it as one of a flood, and only reports it. Host only.
353pub(crate) async fn handle_host_browser_dialog(
354    State(state): State<AppState>,
355    headers: axum::http::HeaderMap,
356    Json(body): Json<Value>,
357) -> impl IntoResponse {
358    if !from_host(&state, &headers).await {
359        return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can report a page's dialog".to_string());
360    }
361    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
362    let flag = |k: &str| body.get(k).and_then(|v| v.as_bool()) == Some(true);
363    let (id, target) = (s("id"), s("target"));
364    let (banner_at, window) = banner_for(&target);
365    let agent = crate::server::browser_owner::owner_of(&banner_at).unwrap_or_default();
366    let answered = |decision: &str| (StatusCode::OK, Json(json!({ "ok": true, "data": { "decision": decision } }))).into_response();
367    let message = clip(&s("message"));
368    let kind_str = s("kind");
369    if flag("ended") {
370        mark_ended(&id);
371        browser_attention::cancel_kind_for(&banner_at, Kind::Dialog);
372        // The host doesn't keep which kind it was.
373        record(&agent, &target, "dialog", &message, "ended", "the page navigated or closed before it was answered");
374        return answered("ok");
375    }
376    if let Some(ask) = body.get("chooser").and_then(|v| v.as_str()) {
377        return answered(chooser_decision(&state, &agent, &target, &banner_at, ask, &message, &s("origin")));
378    }
379    if let Some(notice) = body.get("notice").and_then(|v| v.as_str()) {
380        // Something the host refused in the pane (a link to a program, an untrusted certificate): the agent is told.
381        let (what, reason) = notice_words(notice, &message);
382        let saved = notice == "download_saved";
383        record(&agent, &target, notice, &what, notice_decision(notice), reason);
384        if notice.starts_with("download_") {
385            audit_download(&state, &agent, &banner_at, saved, &message);
386            // A download is also an action in the pane's log, with the person's header.
387            let how = if saved { crate::server::browser_actions::How::Allowed } else { crate::server::browser_actions::How::Refused(message.clone()) };
388            crate::server::browser_actions::note(&banner_at, &agent, crate::server::browser_actions::Kind::Download).detail(&message).how(how).record(&state);
389        }
390        return answered("cancel");
391    }
392    if flag("suppressed") {
393        record(&agent, &target, &kind_str, &message, "cancelled", "the page showed more than 5 dialogs in 10 seconds");
394        return answered("cancel");
395    }
396    let Some(kind) = DialogKind::parse(&kind_str) else {
397        return answered("cancel");
398    };
399    let origin = s("origin");
400    let paired = pair(&target);
401    let covered = crate::server::browser_bypass::active_for(&banner_at, &agent).is_some_and(|g| g.covers(&origin));
402    let reason = match decide(kind, &message, paired.as_ref().map(|(h, l)| (*h, l.as_str())), covered) {
403        Decision::Accept(why) => {
404            record(&agent, &target, kind.as_str(), &message, "accepted", &why);
405            return answered("accept");
406        }
407        Decision::Cancel(why) => {
408            record(&agent, &target, kind.as_str(), &message, "cancelled", &why);
409            return answered("cancel");
410        }
411        Decision::Ask(why) => why,
412    };
413    record(&agent, &target, kind.as_str(), &message, "asking the user", &reason);
414    let st = state.clone();
415    let site = agentmux_common::allowed_origins::target_origin(&origin).unwrap_or(origin);
416    tokio::spawn(async move {
417        if take_ended(&id) {
418            return;
419        }
420        let asked = browser_attention::ask(
421            &st,
422            &banner_at,
423            &agent,
424            Kind::Dialog,
425            json!({
426                "what": "answer a question from the page",
427                "message": message, "origin": site, "dialogKind": kind.as_str(), "window": window,
428            }),
429            ASK_TIMEOUT,
430        )
431        .await;
432        // Ended under the question: it was recorded as such, and the host
433        // has dropped it.
434        if take_ended(&id) {
435            return;
436        }
437        let (accept, decision, why) = match &asked {
438            Ok((Answer::Yes | Answer::YesAlways | Answer::YesAsking, _)) => (true, "accepted", "the user answered OK".to_string()),
439            Ok((Answer::Cancelled, _)) => (false, "cancelled", "the user answered Cancel, or took the pane over".to_string()),
440            Ok((Answer::TimedOut, _)) => (false, "cancelled", "the user didn't answer within 10 minutes".to_string()),
441            Err(e) => (false, "cancelled", format!("couldn't ask the user: {e}")),
442        };
443        answer_host(&st, &id, accept).await;
444        record(&agent, &target, kind.as_str(), &message, decision, &why);
445        // The pane stays paused until the host has the answer.
446        drop(asked);
447    });
448    answered("parked")
449}
450
451/// `POST /api/v1/ui/browser/dialogs` — the page dialogs the calling agent's
452/// panes showed since it last asked, and what became of each. Its `Browser`
453/// tool reads it after every action, so the agent hears of each one; it works
454/// while a pane is paused, which is when it matters.
455pub(crate) async fn handle_ui_browser_dialogs(
456    State(state): State<AppState>,
457    caller: Option<axum::Extension<crate::server::caller::Caller>>,
458    Json(req): Json<agentmux_common::api_types::UiBrowserDialogsRequest>,
459) -> impl IntoResponse {
460    if let Err(e) = verified_block_id(&state, caller.as_deref(), &req.auth) {
461        return err_response(StatusCode::UNAUTHORIZED, e);
462    }
463    (StatusCode::OK, Json(json!({ "ok": true, "data": { "dialogs": drain(&req.auth.agent_id), "zooms": crate::server::browser_zoom::notes(&state, &req.auth.agent_id).await } }))).into_response()
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn alerts_are_accepted_and_prompts_cancelled() {
472        assert!(matches!(decide(DialogKind::Alert, "Saved", None, false), Decision::Accept(_)));
473        assert!(matches!(decide(DialogKind::Prompt, "Name?", Some((How::Auto, "Go")), true), Decision::Cancel(_)));
474    }
475
476    #[test]
477    fn a_confirm_is_accepted_only_after_an_auto_approved_click_on_a_covered_site() {
478        let auto = Some((How::Auto, "Delete"));
479        assert!(matches!(decide(DialogKind::Confirm, "Are you sure?", auto, true), Decision::Accept(_)));
480        assert!(matches!(decide(DialogKind::BeforeUnload, "", auto, true), Decision::Accept(_)));
481        // On its own, after a person-approved click, or off the granted sites: asks.
482        assert!(matches!(decide(DialogKind::Confirm, "Are you sure?", None, true), Decision::Ask(_)));
483        assert!(matches!(decide(DialogKind::Confirm, "Are you sure?", Some((How::Approved, "Delete")), true), Decision::Ask(_)));
484        assert!(matches!(decide(DialogKind::Confirm, "Are you sure?", auto, false), Decision::Ask(_)));
485    }
486
487    #[test]
488    fn money_and_secrets_always_ask() {
489        let auto = Some((How::Auto, "Confirm"));
490        assert!(matches!(decide(DialogKind::Confirm, "Pay $40 now?", auto, true), Decision::Ask(_)));
491        assert!(matches!(decide(DialogKind::Confirm, "Send your password to support?", auto, true), Decision::Ask(_)));
492        assert!(matches!(decide(DialogKind::Confirm, "Enter the verification code we sent", auto, true), Decision::Ask(_)));
493        // "pin" as a word only: "shipping" isn't about a secret.
494        assert!(matches!(decide(DialogKind::Confirm, "Delete this shipping address?", auto, true), Decision::Accept(_)));
495    }
496
497    #[test]
498    fn one_click_pairs_with_one_dialog() {
499        note_click("dlg-test-pane-1", "Click \"Delete\"", How::Auto);
500        assert_eq!(pair("dlg-test-pane-1"), Some((How::Auto, "Click \"Delete\"".to_string())));
501        assert_eq!(pair("dlg-test-pane-1"), None, "a second confirm isn't the click's");
502        assert_eq!(pair("dlg-test-pane-2"), None, "another pane's click doesn't count");
503    }
504
505    #[test]
506    fn a_click_too_long_ago_doesnt_pair() {
507        note_click("dlg-test-pane-3", "Delete", How::Auto);
508        clicks().get_mut("dlg-test-pane-3").unwrap().at -= PAIR_WINDOW;
509        assert_eq!(pair("dlg-test-pane-3"), None);
510    }
511
512    #[test]
513    fn the_log_is_drained_per_agent_and_bounded() {
514        for i in 0..(LOG_MAX + 3) {
515            record("dlg-test-agent", "p", "alert", &format!("m{i}"), "accepted", "it only informs");
516        }
517        record("dlg-test-other", "p", "alert", "x", "accepted", "it only informs");
518        let got = drain("dlg-test-agent");
519        assert_eq!(got.len(), LOG_MAX);
520        assert_eq!(got[0]["message"], "m3", "the oldest go first");
521        assert!(drain("dlg-test-agent").is_empty());
522        assert_eq!(drain("dlg-test-other").len(), 1);
523    }
524
525    #[test]
526    fn an_ended_dialog_is_noticed_once() {
527        mark_ended("dlg-test-ended-1");
528        assert!(take_ended("dlg-test-ended-1"));
529        assert!(!take_ended("dlg-test-ended-1"));
530        assert!(!take_ended("dlg-test-never"));
531    }
532
533    #[tokio::test]
534    async fn a_download_is_one_audit_row_with_the_site_the_file_and_its_size() {
535        let state = crate::server::tests::test_state();
536        let agent = format!("dl-agent-{}", uuid::Uuid::new_v4().simple());
537        audit_download(&state, &agent, "no-such-pane", true, "report.pdf (13 bytes) to /w/downloads/report.pdf");
538        audit_download(&state, &agent, "no-such-pane", false, "big.iso is 900 MB, over the 500 MB limit");
539        audit_download(&state, "", "no-such-pane", true, "ignored (1 byte) to /x");
540        let mut mine: Vec<_> = state.reactive_handler.get_audit_log(200).into_iter().filter(|r| r.target_agent == agent).collect();
541        mine.sort_by_key(|r| !r.success);
542        assert_eq!(mine.len(), 2, "one row per download, none for a pane with no agent");
543        let saved = &mine[0];
544        assert_eq!(saved.standing, Some(true));
545        assert_eq!(saved.level.as_deref(), Some("low"));
546        let answer = saved.answer.as_deref().unwrap();
547        assert!(answer.contains("report.pdf (13 bytes)") && answer.ends_with("not opened"), "{answer}");
548        assert!(saved.prompt.as_deref().unwrap().contains("sent a download"));
549        assert!(!mine[1].success && mine[1].answer.as_deref().unwrap().contains("over the 500 MB limit"));
550    }
551
552    #[test]
553    fn a_saved_or_refused_download_is_told_to_the_agent_in_the_host_s_words() {
554        let (what, why) = notice_words("download_saved", "report.pdf (13 bytes) to /w/downloads/report.pdf");
555        assert_eq!(what, "saved report.pdf (13 bytes) to /w/downloads/report.pdf");
556        assert!(why.contains("without a dialog") && why.contains("not opened"), "{why}");
557        let (what, why) = notice_words("download_refused", "report.pdf is 900 MB, over the 500 MB limit");
558        assert!(what.contains("not saved") && what.contains("over the 500 MB limit") && why.contains("tell the person"), "{what} / {why}");
559    }
560
561    #[test]
562    fn a_refused_link_or_certificate_tells_the_agent_what_to_do_instead() {
563        let (what, why) = notice_words("external_protocol", "mailto");
564        assert!(what.contains("mailto:") && why.contains("tell the person") && !what.contains("program"), "{what} / {why}");
565        let (what, why) = notice_words("certificate_error", "expired.example");
566        assert!(what.contains("expired.example") && why.contains("certificate warning"), "{what} / {why}");
567        let (what, why) = notice_words("auth_expired", "intranet.example:8080");
568        assert!(what.contains("intranet.example:8080") && what.contains("5 minutes") && why.contains("Load the page again"), "{what} / {why}");
569    }
570
571    #[test]
572    fn a_sign_in_prompt_tells_the_agent_which_site_and_what_happened_to_it() {
573        let site = "intranet.example:8080 (realm \"staff\")";
574        let (what, why) = notice_words("auth_required", site);
575        assert!(what.contains(site) && what.contains("blank") && why.contains("Vault") && why.contains("nothing the agent can do"), "{what} / {why}");
576        let (what, why) = notice_words("auth_waiting_approval", site);
577        assert!(what.contains(site) && what.contains("approve") && why.contains("never see"), "{what} / {why}");
578        assert!(notice_words("auth_answered", site).0.contains("saved sign-in was used"));
579        let (what, why) = notice_words("auth_refused", site);
580        assert!(what.contains("refused") && why.contains("out of date") && why.contains("Nothing was changed"), "{what} / {why}");
581        assert!(notice_words("auth_denied", site).0.contains("did not approve"));
582        assert_eq!(notice_decision("auth_answered"), "answered");
583        assert_eq!(notice_decision("auth_waiting_approval"), "waiting");
584        assert_eq!(notice_decision("auth_refused"), "blocked");
585        assert_eq!(notice_decision("download_saved"), "saved");
586    }
587
588    #[test]
589    fn a_cancelled_file_chooser_tells_the_agent_what_to_do_instead() {
590        assert_eq!(chooser_message("choose a file", ""), "the page asked to choose a file");
591        assert_eq!(chooser_message("choose several files", "Upload photos"), "the page asked to choose several files: Upload photos");
592        assert!(chooser_reason("choose a file").contains("Browser set_files"));
593        assert!(chooser_reason("choose several files").contains("Browser set_files"));
594        let folder = chooser_reason("choose a folder");
595        assert!(!folder.contains("set_files") && folder.contains("can't choose a folder"), "{folder}");
596    }
597
598    #[test]
599    fn long_page_text_is_clipped() {
600        let long = "x".repeat(MESSAGE_MAX + 50);
601        assert_eq!(clip(&long).chars().count(), MESSAGE_MAX + 1);
602        assert_eq!(clip("  short  "), "short");
603    }
604}