agentmux_srv/server/
browser_agent_calls.rs1use std::collections::HashMap;
17use std::sync::{Mutex, OnceLock};
18use std::time::{Duration, Instant};
19
20pub(crate) const AGENT_CLICK_WINDOW: Duration = Duration::from_secs(10);
24
25const 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
37pub(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
52pub(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
62pub(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 note_at(&mut m, "fresh", t + AGENT_CLICK_WINDOW);
107 assert!(m.contains_key("fresh"));
108 assert!(m.len() <= MAX_NOTED);
109 }
110}