Skip to main content

agentmux_srv/server/
browser_agent_calls.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! When an agent last drove each browser pane, from srv's own record, so a
5//! click in a pane can be told from the person's and the agent's.
6//!
7//! A pane an agent limited to some sites (`browser_allowlist`) stops its page
8//! going anywhere else, which is right for what the agent does there and wrong
9//! for the person: an email link clicked in such a pane opens a popup that
10//! inherited the limit, and the first redirect hop off the list left a blank
11//! pane (the Microsoft sign-in from a Gmail pane, #18229). The agent's own
12//! clicks are real input events too, so the page can't say who clicked; srv can:
13//! every `Browser` call resolves its pane through `ui_handlers::target_block_id`,
14//! which notes it here. Kept in memory, like ownership.
15
16use std::collections::HashMap;
17use std::sync::{Mutex, OnceLock};
18use std::time::{Duration, Instant};
19
20/// How long after an agent's last call on a pane a click there may still be the
21/// agent's. A click that opens a window does it within the page's own handler,
22/// well inside this; a person's click after the agent has gone quiet is theirs.
23pub(crate) const AGENT_CLICK_WINDOW: Duration = Duration::from_secs(10);
24
25/// More panes than anyone has open: past it the oldest notes go.
26const MAX_NOTED: usize = 512;
27
28fn calls() -> &'static Mutex<HashMap<String, Instant>> {
29    static CALLS: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
30    CALLS.get_or_init(Default::default)
31}
32
33fn lock() -> std::sync::MutexGuard<'static, HashMap<String, Instant>> {
34    calls().lock().unwrap_or_else(|p| p.into_inner())
35}
36
37/// An agent called `Browser` on `pane` (the pane whose banner holds, for a popup window).
38pub(crate) fn note(pane: &str) {
39    note_at(&mut lock(), pane, Instant::now());
40}
41
42fn note_at(map: &mut HashMap<String, Instant>, pane: &str, now: Instant) {
43    if map.len() >= MAX_NOTED && !map.contains_key(pane) {
44        map.retain(|_, at| now.saturating_duration_since(*at) < AGENT_CLICK_WINDOW);
45        if map.len() >= MAX_NOTED {
46            return;
47        }
48    }
49    map.insert(pane.to_string(), now);
50}
51
52/// `pane` closed: nothing to remember.
53pub(crate) fn forget(pane: &str) {
54    lock().remove(pane);
55}
56
57fn agent_was_there(map: &HashMap<String, Instant>, pane: &str, now: Instant) -> bool {
58    map.get(pane)
59        .is_some_and(|at| now.saturating_duration_since(*at) < AGENT_CLICK_WINDOW)
60}
61
62/// Did the person open the popup `opener`'s page asked for? A click (`user_gesture`)
63/// while no agent had called `Browser` on the pane within [`AGENT_CLICK_WINDOW`].
64/// When both are possible it counts as the agent's, so the limit stays.
65pub(crate) fn person_clicked(opener: &str, user_gesture: bool) -> bool {
66    user_gesture && !agent_was_there(&lock(), opener, Instant::now())
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn a_click_right_after_the_agents_call_is_the_agents() {
75        let mut m = HashMap::new();
76        let t = Instant::now();
77        note_at(&mut m, "p", t);
78        assert!(agent_was_there(&m, "p", t + Duration::from_secs(2)));
79        assert!(!agent_was_there(&m, "p", t + AGENT_CLICK_WINDOW));
80        assert!(!agent_was_there(&m, "other", t));
81    }
82
83    #[test]
84    fn a_click_with_no_agent_call_on_the_pane_is_the_persons_only_when_it_is_a_click() {
85        assert!(person_clicked("never-driven-pane", true));
86        assert!(!person_clicked("never-driven-pane", false));
87    }
88
89    #[test]
90    fn a_call_makes_the_next_click_the_agents_until_it_goes_quiet() {
91        note("driven-pane");
92        assert!(!person_clicked("driven-pane", true));
93        forget("driven-pane");
94        assert!(person_clicked("driven-pane", true));
95    }
96
97    #[test]
98    fn the_notes_stay_bounded() {
99        let mut m = HashMap::new();
100        let t = Instant::now();
101        for i in 0..MAX_NOTED + 50 {
102            note_at(&mut m, &format!("p{i}"), t);
103        }
104        assert_eq!(m.len(), MAX_NOTED);
105        // Once they have gone quiet, new panes fit again.
106        note_at(&mut m, "fresh", t + AGENT_CLICK_WINDOW);
107        assert!(m.contains_key("fresh"));
108        assert!(m.len() <= MAX_NOTED);
109    }
110}