Skip to main content

agentmux_srv/server/
browser_actions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an agent did in a browser pane it drives, and the person's Pause
5//! (docs/specs/SPEC_AGENT_DRIVEN_BROWSER_PANES_2026_10_07.md §5.5,
6//! PLAN_BROWSER_DRIVER_FIXES_2026_10_17.md §5).
7//!
8//! The log is a ring of the last [`RING`] entries per pane, in memory only:
9//! srv restarting clears it, closing the pane drops it, and Take over keeps
10//! it, so the person can still read what happened. The newest [`PUBLISHED`]
11//! are mirrored to the pane's `browser:actions` meta key (srv-only, like
12//! `browser:bypass`) for the header's Log. An entry never holds what was
13//! typed: a fill names its field, never the value, secret or not. The one
14//! exception is a line typed into a web terminal under the person's grant:
15//! the Log keeps it, masked and cut short, as their record of what ran.
16//!
17//! Pause is the person's quick, reversible brake, where Take over is final:
18//! while a pane is paused, every agent call that resolves it is refused, and
19//! an Auto-approve grant's clock stands still. Only the person pauses or
20//! resumes, through the host (`/api/v1/host/browser_pause`), so no agent can
21//! lift a pause on itself.
22
23use std::collections::{HashMap, VecDeque};
24use std::sync::{Mutex, OnceLock};
25use std::time::{Duration, Instant};
26
27use axum::extract::State;
28use axum::http::StatusCode;
29use axum::response::{IntoResponse, Response};
30use axum::Json;
31use serde::Serialize;
32use serde_json::{json, Value};
33
34use crate::server::ui_handlers::{banner_for, err_response, from_host, verified_block_id};
35use crate::server::AppState;
36
37/// Block meta key the header's Log reads: `{count, entries}`.
38pub(crate) const ACTIONS_META_KEY: &str = "browser:actions";
39/// Block meta key the header reads to show a pane is paused.
40pub(crate) const PAUSED_META_KEY: &str = "browser:paused";
41
42/// Entries kept per pane.
43pub(crate) const RING: usize = 200;
44/// Entries mirrored to the pane's meta: the header shows the newest.
45pub(crate) const PUBLISHED: usize = 50;
46
47/// What was done. Kebab-case on the wire (`auto-approve-on`).
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "kebab-case")]
50pub(crate) enum Kind {
51    Navigate,
52    Back,
53    Forward,
54    Reload,
55    Click,
56    Fill,
57    Select,
58    Check,
59    Key,
60    Upload,
61    /// Typed into a web terminal under the person's grant.
62    Terminal,
63    /// A secret the page showed, saved into the Vault (`Browser` `capture`).
64    Capture,
65    Eval,
66    Handoff,
67    AutoApproveOn,
68    AutoApproveOff,
69    Pause,
70    Resume,
71    /// An agent began driving a pane it did not open.
72    TookControl,
73    /// An agent let a pane go.
74    Released,
75    /// A download its pane saved into the agent's workspace without a dialog, or refused to.
76    Download,
77}
78
79/// How it went: who let it through, or why it didn't happen.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub(crate) enum How {
82    /// Nothing needed asking.
83    Allowed,
84    /// The person approved it in the pane's banner.
85    Approved,
86    /// Made without asking under the person's Auto-approve.
87    AutoApproved,
88    Declined,
89    Refused(String),
90    TimedOut,
91    /// The person's own doing (Pause, Resume, Auto-approve from the header).
92    ByUser,
93}
94
95impl How {
96    fn label(&self) -> String {
97        match self {
98            How::Allowed => "allowed".into(),
99            How::Approved => "approved".into(),
100            How::AutoApproved => "auto-approved".into(),
101            How::Declined => "declined".into(),
102            How::Refused(why) => format!("refused: {}", short_reason(why)),
103            How::TimedOut => "timed out".into(),
104            How::ByUser => "by the user".into(),
105        }
106    }
107
108    /// A hand-off's or a request's answer.
109    pub(crate) fn from_answer(a: crate::server::browser_attention::Answer) -> How {
110        use crate::server::browser_attention::Answer;
111        match a {
112            Answer::Yes | Answer::YesAlways | Answer::YesAsking => How::Approved,
113            Answer::Cancelled => How::Declined,
114            Answer::TimedOut => How::TimedOut,
115        }
116    }
117}
118
119#[derive(Debug, Clone, PartialEq, Serialize)]
120pub(crate) struct Entry {
121    /// Milliseconds since the Unix epoch.
122    pub ts: i64,
123    pub agent: String,
124    pub kind: Kind,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub url: Option<String>,
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub target: Option<String>,
129    pub how: String,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub detail: Option<String>,
132}
133
134#[derive(Default)]
135struct Log {
136    entries: VecDeque<Entry>,
137    /// Every entry the pane ever had, for the header's count.
138    count: u64,
139}
140
141#[derive(Default)]
142struct Table {
143    logs: HashMap<String, Log>,
144    /// Paused panes, since when, and the state to clear the header's
145    /// `browser:paused` with when Take over (which has no `AppState`) ends it.
146    paused: HashMap<String, (Instant, AppState)>,
147}
148
149fn table() -> std::sync::MutexGuard<'static, Table> {
150    static T: OnceLock<Mutex<Table>> = OnceLock::new();
151    T.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
152}
153
154/// `s` trimmed and cut to `n` characters.
155fn clip(s: &str, n: usize) -> String {
156    // The Log is mirrored to the pane's header, the host log and the agent's own `log` read: a
157    // label the page chose (a button named with a card number) is masked before it is kept.
158    let masked = agentmux_common::pii_mask::mask_bounded(s.trim(), n.saturating_mul(4).max(400));
159    let s = masked.trim();
160    if s.chars().count() <= n {
161        return s.to_string();
162    }
163    let mut out: String = s.chars().take(n.saturating_sub(1)).collect();
164    out.push('…');
165    out
166}
167
168/// A refusal's gist for the log: its first clause.
169fn short_reason(why: &str) -> String {
170    let cut = [": ", ". ", "; "].iter().filter_map(|sep| why.find(sep)).min().unwrap_or(why.len());
171    clip(&why[..cut], 100)
172}
173
174/// Add `e` to `pane`'s ring, dropping the oldest past [`RING`].
175fn add(pane: &str, e: Entry) {
176    let mut t = table();
177    let log = t.logs.entry(pane.to_string()).or_default();
178    log.entries.push_back(e);
179    log.count += 1;
180    while log.entries.len() > RING {
181        log.entries.pop_front();
182    }
183}
184
185/// `pane`'s entries, oldest first, and how many it ever had.
186pub(crate) fn entries(pane: &str) -> (u64, Vec<Entry>) {
187    table().logs.get(pane).map_or((0, Vec::new()), |l| (l.count, l.entries.iter().cloned().collect()))
188}
189
190/// One entry being described; [`Note::record`] adds it. Built by the
191/// handlers, one line each.
192#[must_use]
193pub(crate) struct Note {
194    target_pane: String,
195    agent: String,
196    kind: Kind,
197    url: Option<String>,
198    target: Option<String>,
199    detail: Option<String>,
200    how: Option<How>,
201}
202
203/// Describe `agent`'s `kind` on `pane` (a pane or a popup window id).
204pub(crate) fn note(pane: &str, agent: &str, kind: Kind) -> Note {
205    Note { target_pane: pane.to_string(), agent: agent.to_string(), kind, url: None, target: None, detail: None, how: None }
206}
207
208impl Note {
209    /// An act request: click, fill, select or check, on its ref. A fill's
210    /// text is never kept; a select's option and a check's state are.
211    pub(crate) fn act(pane: &str, req: &agentmux_common::api_types::UiBrowserActRequest) -> Note {
212        let kind = match req.action.as_str() {
213            "fill" => Kind::Fill,
214            "select" => Kind::Select,
215            "check" => Kind::Check,
216            _ => Kind::Click,
217        };
218        let n = note(pane, &req.auth.agent_id, kind).target(&req.ref_);
219        match kind {
220            Kind::Select => n.detail(&format!("option {:?}", clip(req.option.as_deref().unwrap_or(""), 80))),
221            Kind::Check => n.detail(if req.checked == Some(false) { "uncheck" } else { "check" }),
222            _ => n,
223        }
224    }
225
226    /// A fill into a password, code, card, bank or ID field: the log says which kind and that the agent
227    /// gave the value, never the value or its length.
228    pub(crate) fn secret_fill(self, answer: &Value) -> Self {
229        match answer.pointer("/after/secret_fill").and_then(|v| v.as_str()) {
230            Some(kind) => self.detail(&format!("{kind} field, filled from the agent's text")),
231            None => self,
232        }
233    }
234
235    pub(crate) fn url(mut self, url: &str) -> Self {
236        self.url = Some(clip(url, 500)).filter(|u| !u.is_empty());
237        self
238    }
239
240    pub(crate) fn target(mut self, target: &str) -> Self {
241        self.target = Some(clip(target, 120)).filter(|t| !t.is_empty());
242        self
243    }
244
245    pub(crate) fn detail(mut self, detail: &str) -> Self {
246        self.detail = Some(clip(detail, 200)).filter(|d| !d.is_empty());
247        self
248    }
249
250    pub(crate) fn how(mut self, how: How) -> Self {
251        self.how = Some(how);
252        self
253    }
254
255    /// The committing click a `needs_approval` describes: its label (from
256    /// `Click "…"`) and the page it is on, keeping the ref as detail.
257    pub(crate) fn asked(self, ask: &Value) -> Self {
258        let what = ask.get("what").and_then(|v| v.as_str()).unwrap_or("");
259        let label = what.strip_prefix("Click ").unwrap_or(what).to_string();
260        let page = ask.get("page").and_then(|v| v.as_str()).unwrap_or("").to_string();
261        let r = self.target.clone().map(|r| format!("ref {r}")).unwrap_or_default();
262        self.target(&label).url(&page).detail(&r)
263    }
264
265    fn entry(&self, how: How, window_url: Option<String>) -> Entry {
266        Entry {
267            ts: chrono::Utc::now().timestamp_millis(),
268            agent: self.agent.clone(),
269            kind: self.kind,
270            url: self.url.clone().or(window_url),
271            target: self.target.clone(),
272            how: how.label(),
273            detail: self.detail.clone(),
274        }
275    }
276
277    /// Add the entry (as `Allowed` unless [`Note::how`] said otherwise) to
278    /// the pane's log and show it in the header. Only a pane an agent drives
279    /// has a log: an agent's own pane, which these routes also reach, has none.
280    pub(crate) fn record(self, state: &AppState) {
281        let how = self.how.clone().unwrap_or(How::Allowed);
282        self.record_as(state, how);
283    }
284
285    fn record_as(self, state: &AppState, how: How) {
286        // A popup window's actions go in its opener's log, with its address.
287        let (pane, window_url) = banner_for(&self.target_pane);
288        self.audit_for_a_session(state, &pane, &how, window_url.as_deref());
289        if crate::server::browser_owner::owner_of(&pane).is_none() {
290            return;
291        }
292        add(&pane, self.entry(how, window_url));
293        publish(state, &pane);
294    }
295
296    /// A background session has no window the person watches, so what an agent does in it also goes to the Audit: the
297    /// agent, the kind of step, how it went and the site (never a typed value, a label or a reason).
298    fn audit_for_a_session(&self, state: &AppState, pane: &str, how: &How, window_url: Option<&str>) {
299        if !crate::server::pane_openers::is_background(pane) {
300            return;
301        }
302        // A step by the person is theirs, not the agent's.
303        let agent = (*how != How::ByUser).then_some(self.agent.as_str());
304        let url = self.url.as_deref().or(window_url);
305        crate::server::browser_sessions::audit_step(state, agent, &audit_words(self.kind, how), pane, url);
306    }
307
308    /// Record a host call's result and answer the agent with it: `how` (or
309    /// `Allowed`) when it went through, `refused: <why>` when it didn't.
310    pub(crate) fn outcome(self, state: &AppState, r: Result<Value, (StatusCode, String)>) -> Response {
311        match r {
312            Ok(data) => {
313                self.record(state);
314                (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
315            }
316            Err((code, e)) => {
317                self.record_as(state, How::Refused(e.clone()));
318                err_response(code, e)
319            }
320        }
321    }
322
323    /// Record a call that didn't go through (as `how`, else `refused: msg`)
324    /// and answer the agent with `msg`.
325    pub(crate) fn fail(self, state: &AppState, code: StatusCode, msg: String) -> Response {
326        let how = self.how.clone().unwrap_or_else(|| How::Refused(msg.clone()));
327        self.record_as(state, how);
328        err_response(code, msg)
329    }
330}
331
332/// What an Audit row says of a step: its kind and how it went, and nothing the page or the agent wrote (a refusal's reason
333/// can name an address or a label).
334fn audit_words(kind: Kind, how: &How) -> String {
335    let step = serde_json::to_value(kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
336    match how {
337        How::Refused(_) => format!("{step} (refused)"),
338        other => format!("{step} ({})", other.label()),
339    }
340}
341
342/// Mirror `pane`'s newest entries to its meta, for the header's Log.
343fn publish(state: &AppState, pane: &str) {
344    let value = {
345        let t = table();
346        t.logs.get(pane).map_or(Value::Null, |l| {
347            let skip = l.entries.len().saturating_sub(PUBLISHED);
348            json!({ "count": l.count, "entries": l.entries.iter().skip(skip).collect::<Vec<_>>() })
349        })
350    };
351    let mut meta = crate::backend::obj::MetaMapType::new();
352    meta.insert(ACTIONS_META_KEY.to_string(), value);
353    if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, pane, &meta) {
354        tracing::debug!(pane = %pane, error = %e, "[browser-actions] header log not updated");
355    }
356}
357
358/// Is `pane` paused: by the person's Pause on it, or by "Pause all agent
359/// browsing" while an agent drives it?
360pub(crate) fn is_paused(pane: &str) -> bool {
361    paused_by(paused_alone(pane), crate::server::browser_pause_all::is_on(), crate::server::browser_owner::owner_of(pane).is_some())
362}
363
364/// The global switch pauses a pane an agent drives, never the agent's own pane
365/// or one nobody drives; a pane's own Pause holds whoever drives it.
366fn paused_by(alone: bool, all_on: bool, driven: bool) -> bool {
367    alone || (all_on && driven)
368}
369
370/// Did the person pause `pane` itself (its own Pause, not the global switch)?
371pub(crate) fn paused_alone(pane: &str) -> bool {
372    table().paused.contains_key(pane)
373}
374
375/// For `target_block_id`: refuse every agent call on a pane the person paused.
376pub(crate) fn not_paused(pane: &str) -> Result<(), (StatusCode, String)> {
377    let pane = banner_for(pane).0;
378    if !is_paused(&pane) {
379        return Ok(());
380    }
381    if paused_alone(&pane) {
382        return Err((
383            StatusCode::CONFLICT,
384            "the user paused this pane; your calls on it wait until they resume it (this one wasn't made): try again later, or ask them in chat".to_string(),
385        ));
386    }
387    Err((StatusCode::CONFLICT, format!("{} (this one wasn't made)", crate::server::browser_pause_all::refusal())))
388}
389
390/// Pause (`on`) or resume `pane`. Returns whether that changed anything.
391/// An Auto-approve grant's clock stops with it, and runs again on resume.
392pub(crate) fn set_paused(state: &AppState, pane: &str, on: bool) -> bool {
393    let held = {
394        let mut t = table();
395        match (on, t.paused.get(pane).map(|(since, _)| *since)) {
396            (true, None) => {
397                t.paused.insert(pane.to_string(), (Instant::now(), state.clone()));
398                None
399            }
400            (false, Some(since)) => {
401                t.paused.remove(pane);
402                Some(since.elapsed())
403            }
404            _ => return false,
405        }
406    };
407    // A pane resumed while "Pause all agent browsing" is on stays held.
408    crate::server::browser_bypass::hold_clock(state, pane, is_paused(pane));
409    let agent = crate::server::browser_owner::owner_of(pane).unwrap_or_default();
410    let n = note(pane, &agent, if on { Kind::Pause } else { Kind::Resume }).how(How::ByUser);
411    match held {
412        Some(d) => n.detail(&format!("after {}", held_for(d))).record(state),
413        None => n.record(state),
414    }
415    tracing::info!(pane = %pane, paused = on, "[browser-actions] the user {} the agent", if on { "paused" } else { "resumed" });
416    publish_paused(state, pane, is_paused(pane));
417    true
418}
419
420/// "Pause all agent browsing" was turned on or off (already in force for
421/// [`is_paused`]), by `by` (None: the person): hold or release every grant's
422/// clock, and show it on each driven pane's header and Log, as the one who did it.
423pub(crate) fn pause_all_changed(state: &AppState, on: bool, by: Option<&str>) {
424    crate::server::browser_bypass::hold_all(state);
425    for pane in crate::server::browser_owner::owned_panes() {
426        publish_paused(state, &pane, is_paused(&pane));
427        let agent = crate::server::browser_owner::owner_of(&pane).unwrap_or_default();
428        let (how, detail) = match by {
429            None => (How::ByUser, "all agent browsing".to_string()),
430            Some(who) => (How::Allowed, format!("all agent browsing, by {who}")),
431        };
432        note(&pane, &agent, if on { Kind::Pause } else { Kind::Resume }).how(how).detail(&detail).record(state);
433    }
434}
435
436fn publish_paused(state: &AppState, pane: &str, on: bool) {
437    let mut meta = crate::backend::obj::MetaMapType::new();
438    meta.insert(PAUSED_META_KEY.to_string(), if on { json!(true) } else { Value::Null });
439    if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, pane, &meta) {
440        tracing::debug!(pane = %pane, error = %e, "[browser-actions] header pause not updated");
441    }
442}
443
444fn held_for(d: Duration) -> String {
445    match d.as_secs() {
446        s if s < 60 => format!("{s} s"),
447        s => format!("{} min", s / 60),
448    }
449}
450
451/// Where an Auto-approve grant's end moves to when its clock ran from
452/// `paused_at` to `now` while paused: later by exactly the paused time, both
453/// as an `Instant` and as the header's epoch milliseconds.
454pub(crate) fn resumed_clock(expires: Instant, expires_at_ms: i64, paused_at: Instant, now: Instant) -> (Instant, i64) {
455    let held = now.saturating_duration_since(paused_at);
456    (expires + held, expires_at_ms + held.as_millis() as i64)
457}
458
459/// The agent no longer drives `pane` (Take over): the pause goes with it,
460/// and so does the header's `browser:paused`, or a later driver's strip would
461/// read as paused. The log stays.
462pub(crate) fn forget_pause(pane: &str) {
463    // Taken out under the lock, published after releasing it: publishing
464    // writes the block, and nothing else should wait on this table meanwhile.
465    let removed = table().paused.remove(pane);
466    if let Some((_, state)) = removed {
467        publish_paused(&state, pane, false);
468    }
469}
470
471/// `pane` was closed: its log and pause go.
472pub(crate) fn drop_pane(pane: &str) {
473    let mut t = table();
474    t.logs.remove(pane);
475    t.paused.remove(pane);
476}
477
478/// Clear the log and pause saved with panes that srv no longer has them for.
479/// Called when the host registers: neither survives srv restarting, and the
480/// header, which reads the saved meta, must not show a stale one.
481pub(crate) fn reset_strips(state: &AppState) {
482    let blocks = match state.mstore.get_all::<crate::backend::obj::Block>() {
483        Ok(b) => b,
484        Err(e) => {
485            tracing::warn!(error = %e, "[browser-actions] couldn't list panes to clear stale logs");
486            return;
487        }
488    };
489    let set = |b: &crate::backend::obj::Block, key: &str| b.meta.get(key).is_some_and(|v| !v.is_null());
490    for b in blocks {
491        let has_log = table().logs.contains_key(&b.oid);
492        let paused = is_paused(&b.oid);
493        let mut meta = crate::backend::obj::MetaMapType::new();
494        if set(&b, ACTIONS_META_KEY) && !has_log {
495            meta.insert(ACTIONS_META_KEY.to_string(), Value::Null);
496        }
497        if set(&b, PAUSED_META_KEY) && !paused {
498            meta.insert(PAUSED_META_KEY.to_string(), Value::Null);
499        }
500        if !meta.is_empty() {
501            if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, &b.oid, &meta) {
502                tracing::debug!(pane = %b.oid, error = %e, "[browser-actions] stale log not cleared");
503            }
504        }
505    }
506}
507
508/// `POST /api/v1/ui/browser/actions` — backs Browser's `log`: the pane's
509/// action log, for the agent that drives it (or its own pane). Read-only.
510/// Resolved without `target_block_id`, so it works while the pane is paused
511/// or waiting on the person.
512pub(crate) async fn handle_ui_browser_actions(
513    State(state): State<AppState>,
514    caller: Option<axum::Extension<crate::server::caller::Caller>>,
515    Json(req): Json<agentmux_common::api_types::UiBrowserActionsRequest>,
516) -> impl IntoResponse {
517    let own = match verified_block_id(&state, caller.as_deref(), &req.auth) {
518        Ok(b) => b,
519        Err(e) => return err_response(StatusCode::UNAUTHORIZED, e),
520    };
521    let asked = req.pane.as_deref().map(str::trim).filter(|p| !p.is_empty()).unwrap_or(&own).to_string();
522    let pane = banner_for(&asked).0;
523    let yours = pane == own
524        || crate::server::browser_owner::owner_of(&pane).is_some_and(|o| o.eq_ignore_ascii_case(&req.auth.agent_id));
525    if !yours {
526        return err_response(
527            StatusCode::FORBIDDEN,
528            format!("pane {asked:?} isn't a browser pane you drive: you can read the log of your own panes only"),
529        );
530    }
531    let (count, entries) = entries(&pane);
532    let data = json!({ "pane": pane, "paused": is_paused(&pane), "count": count, "entries": entries });
533    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
534}
535
536/// `POST /api/v1/host/browser_pause` — the person's Pause and Resume in an
537/// agent-driven pane's header, relayed by the CEF host. Only the host can
538/// call it: an agent holding the instance auth key gets 403, so no agent can
539/// resume itself. Body `{block_id, paused}`.
540pub(crate) async fn handle_host_browser_pause(
541    State(state): State<AppState>,
542    headers: axum::http::HeaderMap,
543    Json(body): Json<Value>,
544) -> impl IntoResponse {
545    if !from_host(&state, &headers).await {
546        return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can pause or resume an agent".to_string());
547    }
548    let block_id = body.get("block_id").and_then(|v| v.as_str()).unwrap_or("").trim();
549    let Some(on) = body.get("paused").and_then(|v| v.as_bool()) else {
550        return err_response(StatusCode::BAD_REQUEST, "say whether to pause (`paused`: true or false)".to_string());
551    };
552    let pane = banner_for(block_id).0;
553    if !matches!(state.mstore.get::<crate::backend::obj::Block>(&pane), Ok(Some(_))) {
554        return err_response(StatusCode::NOT_FOUND, "the pane is gone".to_string());
555    }
556    if on && crate::server::browser_owner::owner_of(&pane).is_none() {
557        return err_response(StatusCode::CONFLICT, "no agent drives this pane any more".to_string());
558    }
559    set_paused(&state, &pane, on);
560    (StatusCode::OK, Json(json!({ "ok": true, "data": { "paused": is_paused(&pane) } }))).into_response()
561}
562
563/// An approved click's result, saying it was the user's approval that let
564/// it through and how long they took: the agent can't see the banner or a
565/// clock, and once reported "no banner appeared" for a click the user had
566/// approved (form-filling fixes plan §2.5).
567pub(crate) fn approved_by_user(r: Result<Value, (StatusCode, String)>, waited: Duration) -> Result<Value, (StatusCode, String)> {
568    r.map(|mut data| {
569        if let Some(o) = data.as_object_mut() {
570            o.insert("approved_by_user".to_string(), json!(true));
571            o.insert("waited_ms".to_string(), json!(waited.as_millis() as u64));
572        }
573        data
574    })
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    #[test]
582    fn a_session_step_is_audited_by_its_kind_and_how_it_went_and_never_by_what_the_page_said() {
583        assert_eq!(audit_words(Kind::Navigate, &How::Allowed), "navigate (allowed)");
584        assert_eq!(audit_words(Kind::Click, &How::Approved), "click (approved)");
585        assert_eq!(audit_words(Kind::Fill, &How::AutoApproved), "fill (auto-approved)");
586        // A refusal's reason can name an address or a label: only that it was refused is kept.
587        assert_eq!(audit_words(Kind::Navigate, &How::Refused("evil.test/?token=abc is not on this pane's list".into())), "navigate (refused)");
588    }
589
590    #[test]
591    fn a_label_the_page_chose_is_logged_without_a_card_number() {
592        let shown = clip("Pay with 4111 1111 1111 1111 (CVV 123)", 120);
593        assert!(!shown.contains("4111") && shown.contains("[card number hidden]") && shown.contains("[code hidden]"), "{shown}");
594        assert_eq!(clip("  Submit order  ", 120), "Submit order");
595        assert_eq!(clip(&"a".repeat(300), 10).chars().count(), 10);
596    }
597
598    #[test]
599    fn an_approved_click_says_the_user_approved_it_and_after_how_long() {
600        let data = approved_by_user(Ok(json!({ "after": { "tag": "button" } })), Duration::from_millis(12_300)).unwrap();
601        assert_eq!(data["approved_by_user"], true);
602        assert_eq!(data["waited_ms"], 12_300);
603        assert_eq!(data["after"]["tag"], "button");
604        let refused = approved_by_user(Err((StatusCode::BAD_GATEWAY, "gone".into())), Duration::ZERO);
605        assert_eq!(refused.unwrap_err().1, "gone");
606    }
607
608    fn entry(n: usize) -> Entry {
609        note("x", "naki", Kind::Click).target(&format!("e{n}")).entry(How::Allowed, None)
610    }
611
612    #[test]
613    fn the_ring_keeps_the_newest_two_hundred() {
614        for n in 0..250 {
615            add("ba-ring", entry(n));
616        }
617        let (count, kept) = entries("ba-ring");
618        assert_eq!(count, 250);
619        assert_eq!(kept.len(), RING);
620        assert_eq!(kept[0].target.as_deref(), Some("e50"));
621        assert_eq!(kept[RING - 1].target.as_deref(), Some("e249"));
622        drop_pane("ba-ring");
623        assert_eq!(entries("ba-ring"), (0, Vec::new()));
624    }
625
626    #[test]
627    fn a_fill_never_keeps_the_value() {
628        let req: agentmux_common::api_types::UiBrowserActRequest = serde_json::from_value(json!({
629            "agent_id": "naki", "ts_secs": 1, "sig": "s", "pane": "p", "ref": "e7", "action": "fill",
630            "text": "hunter2-secret-value",
631        }))
632        .unwrap();
633        let n = Note::act("p", &req);
634        let e = n.entry(How::Allowed, None);
635        assert_eq!(e.kind, Kind::Fill);
636        assert_eq!(e.target.as_deref(), Some("e7"));
637        let wire = serde_json::to_string(&e).unwrap();
638        assert!(!wire.contains("hunter2"), "{wire}");
639        // A failed fill's refusal reason comes from the host, never the text.
640        let e = note("p", "naki", Kind::Fill).target("e7").entry(How::Refused("a secret field: use handoff".into()), None);
641        assert_eq!(e.how, "refused: a secret field");
642    }
643
644    #[test]
645    fn a_fill_into_a_secret_field_logs_its_kind_and_never_the_value() {
646        let answer = json!({ "after": { "value": "[secret: hidden]", "secret_fill": "taxpayer ID" } });
647        let e = note("p", "qtest", Kind::Fill).target("e7").secret_fill(&answer).entry(How::Allowed, Some("https://appstoreconnect.apple.com/".into()));
648        assert_eq!(e.detail.as_deref(), Some("taxpayer ID field, filled from the agent's text"));
649        assert_eq!(e.agent, "qtest");
650        let wire = serde_json::to_string(&e).unwrap();
651        assert!(!wire.contains("hidden"), "{wire}");
652        // an ordinary fill adds nothing
653        let plain = note("p", "qtest", Kind::Fill).target("e7").secret_fill(&json!({ "after": { "value": "x" } }));
654        assert_eq!(plain.entry(How::Allowed, None).detail, None);
655    }
656
657    #[test]
658    fn each_pane_has_its_own_log() {
659        add("ba-one", entry(1));
660        add("ba-two", entry(2));
661        add("ba-two", entry(3));
662        assert_eq!(entries("ba-one").1.len(), 1);
663        assert_eq!(entries("ba-two").1.len(), 2);
664        drop_pane("ba-one");
665        assert_eq!(entries("ba-one").0, 0);
666        assert_eq!(entries("ba-two").1.len(), 2, "closing one pane leaves the other's log");
667        drop_pane("ba-two");
668    }
669
670    #[test]
671    fn hows_and_kinds_read_as_the_log_shows_them() {
672        assert_eq!(How::AutoApproved.label(), "auto-approved");
673        assert_eq!(How::TimedOut.label(), "timed out");
674        assert_eq!(How::Refused("off the pane's sites. Ask the user".into()).label(), "refused: off the pane's sites");
675        assert_eq!(serde_json::to_value(Kind::AutoApproveOn).unwrap(), json!("auto-approve-on"));
676        let e = note("p", "naki", Kind::Click)
677            .target("e3")
678            .asked(&json!({ "what": "Click \"Delete draft\"", "page": "https://github.com/x" }))
679            .entry(How::Approved, None);
680        assert_eq!(e.target.as_deref(), Some("\"Delete draft\""));
681        assert_eq!(e.url.as_deref(), Some("https://github.com/x"));
682        assert_eq!(e.detail.as_deref(), Some("ref e3"));
683    }
684
685    #[test]
686    fn the_global_switch_refuses_a_pane_an_agent_drives_and_says_so() {
687        use crate::server::browser_pause_all::force_for_test;
688        crate::server::browser_owner::record("ba-global-driven", "some-agent");
689        force_for_test(Some(true));
690        let (code, msg) = not_paused("ba-global-driven").unwrap_err();
691        assert_eq!(code, StatusCode::CONFLICT);
692        assert!(msg.contains("paused all agent browsing"), "{msg}");
693        assert!(is_paused("ba-global-driven"));
694        // The agent's own pane, which nobody drives as a browser, is not held.
695        assert!(not_paused("ba-global-agent-pane").is_ok());
696        force_for_test(Some(false));
697        assert!(not_paused("ba-global-driven").is_ok());
698        force_for_test(None);
699        crate::server::browser_owner::forget("ba-global-driven");
700    }
701
702    #[test]
703    fn pausing_everything_holds_the_panes_an_agent_drives_and_no_others() {
704        assert!(paused_by(false, true, true));
705        assert!(!paused_by(false, true, false), "an agent's own pane is not a browser it drives");
706        assert!(!paused_by(false, false, true));
707        assert!(paused_by(true, false, false), "a pane's own Pause holds without the switch");
708        assert!(paused_by(true, true, true), "resuming one pane doesn't resume it while the switch is on");
709    }
710
711    #[test]
712    fn pausing_moves_the_grants_end_by_the_paused_time() {
713        let t0 = Instant::now();
714        let expires = t0 + Duration::from_secs(15 * 60);
715        // Paused 5 minutes in, resumed 25 minutes later: 10 minutes were
716        // left, and 10 minutes are left after resuming.
717        let paused_at = t0 + Duration::from_secs(5 * 60);
718        let now = paused_at + Duration::from_secs(25 * 60);
719        let (end, end_ms) = resumed_clock(expires, 1_000_000, paused_at, now);
720        assert_eq!(end, expires + Duration::from_secs(25 * 60));
721        assert_eq!(end - now, Duration::from_secs(10 * 60));
722        assert_eq!(end_ms, 1_000_000 + 25 * 60 * 1000);
723        // A resume can't move the end back.
724        assert_eq!(resumed_clock(expires, 5, now, paused_at), (expires, 5));
725    }
726
727    #[tokio::test]
728    async fn a_paused_pane_refuses_and_a_resumed_one_does_not() {
729        table().paused.insert("ba-paused".into(), (Instant::now(), crate::server::tests::test_state()));
730        let (code, msg) = not_paused("ba-paused").unwrap_err();
731        assert_eq!(code, StatusCode::CONFLICT);
732        assert!(msg.starts_with("the user paused this pane"), "{msg}");
733        forget_pause("ba-paused");
734        assert!(not_paused("ba-paused").is_ok());
735    }
736}