Skip to main content

agentmux_srv/server/
browser_handoffs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What became of each hand-off an agent asked the person for, so an agent whose call ended
5//! before the person answered (its session ended, the call timed out on its side) can still
6//! ask (`Browser handoff_status`, docs/specs/SPEC_BROWSER_RETAKE_AND_COMMANDEER_2026_11_04.md ยง1.5).
7//!
8//! In memory, like the owner map: a day, the newest few hundred. A hand-off whose call ended
9//! before an answer is `abandoned`: its banner went down with the call, so nobody can answer it.
10
11use std::collections::HashMap;
12use std::sync::{Mutex, OnceLock};
13use std::time::{Duration, Instant};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub(crate) enum State {
17    Pending,
18    Done,
19    Cancelled,
20    TimedOut,
21    Abandoned,
22}
23
24impl State {
25    pub(crate) fn as_str(self) -> &'static str {
26        match self {
27            State::Pending => "pending",
28            State::Done => "done",
29            State::Cancelled => "cancelled",
30            State::TimedOut => "timed_out",
31            State::Abandoned => "abandoned",
32        }
33    }
34
35    /// The state the person's answer (or the lack of one) leaves a hand-off in.
36    pub(crate) fn of_answer(a: crate::server::browser_attention::Answer) -> State {
37        use crate::server::browser_attention::Answer;
38        match a {
39            Answer::Yes | Answer::YesAlways | Answer::YesAsking => State::Done,
40            Answer::Cancelled => State::Cancelled,
41            Answer::TimedOut => State::TimedOut,
42        }
43    }
44}
45
46struct Entry {
47    pane: String,
48    agent: String,
49    state: State,
50    started: Instant,
51    ended: Option<Instant>,
52}
53
54/// One hand-off as an agent reads it.
55#[derive(Debug, PartialEq, Eq)]
56pub(crate) struct Status {
57    pub id: String,
58    pub pane: String,
59    pub state: State,
60    pub started_secs_ago: u64,
61    /// When the person answered, or the hand-off ended without them; None while pending.
62    pub ended_secs_ago: Option<u64>,
63    /// How long it stayed open: from the banner going up to the answer (or the end); None while pending.
64    pub open_secs: Option<u64>,
65}
66
67/// What the Log and the answer say of how a hand-off ended: who answered, and how long the banner was up.
68/// An answer within seconds is worth an agent's doubt (it can't tell an early Done from a request that closed
69/// itself), so the time is always in it.
70pub(crate) fn ended_words(settled: crate::server::browser_attention::Settled, open: Duration) -> String {
71    use crate::server::browser_attention::Answer;
72    let span = agentmux_common::time::span_words(open.as_secs());
73    if settled.by_agent {
74        return format!("the agent took it back after {span}");
75    }
76    match settled.answer {
77        Answer::Yes | Answer::YesAlways | Answer::YesAsking => format!("the person clicked Done after {span}"),
78        Answer::Cancelled => format!("the person clicked Cancel after {span}"),
79        Answer::TimedOut => format!("nobody answered in {span}"),
80    }
81}
82
83const KEPT: usize = 256;
84const KEPT_FOR: Duration = Duration::from_secs(24 * 60 * 60);
85
86fn entries() -> &'static Mutex<HashMap<String, Entry>> {
87    static E: OnceLock<Mutex<HashMap<String, Entry>>> = OnceLock::new();
88    E.get_or_init(Default::default)
89}
90
91/// A hand-off being waited on. Dropped without [`Tracked::finish`] (the call ended first), it reads as abandoned.
92pub(crate) struct Tracked {
93    id: String,
94    finished: bool,
95}
96
97impl Tracked {
98    pub(crate) fn start(id: &str, pane: &str, agent: &str) -> Tracked {
99        let mut map = entries().lock().unwrap_or_else(|p| p.into_inner());
100        map.retain(|_, e| e.started.elapsed() < KEPT_FOR);
101        if map.len() >= KEPT {
102            if let Some(oldest) = map.iter().min_by_key(|(_, e)| e.started).map(|(k, _)| k.clone()) {
103                map.remove(&oldest);
104            }
105        }
106        map.insert(
107            id.to_string(),
108            Entry { pane: pane.to_string(), agent: agent.to_string(), state: State::Pending, started: Instant::now(), ended: None },
109        );
110        Tracked { id: id.to_string(), finished: false }
111    }
112
113    pub(crate) fn finish(mut self, state: State) {
114        settle(&self.id, state);
115        self.finished = true;
116    }
117}
118
119impl Drop for Tracked {
120    fn drop(&mut self) {
121        if !self.finished {
122            settle(&self.id, State::Abandoned);
123        }
124    }
125}
126
127fn settle(id: &str, state: State) {
128    let mut map = entries().lock().unwrap_or_else(|p| p.into_inner());
129    if let Some(e) = map.get_mut(id).filter(|e| e.state == State::Pending) {
130        e.state = state;
131        e.ended = Some(Instant::now());
132    }
133}
134
135/// `agent`'s hand-off `id`, or, with no id, its newest one on `pane`. Another agent's hand-off is never shown.
136pub(crate) fn status(agent: &str, id: Option<&str>, pane: Option<&str>) -> Option<Status> {
137    let map = entries().lock().unwrap_or_else(|p| p.into_inner());
138    let mine = |e: &Entry| e.agent.eq_ignore_ascii_case(agent) && e.started.elapsed() < KEPT_FOR;
139    let (id, e) = match id {
140        Some(id) => map.get_key_value(id).filter(|(_, e)| mine(*e))?,
141        None => map.iter().filter(|(_, e)| mine(*e) && pane.is_none_or(|p| e.pane == p)).max_by_key(|(_, e)| e.started)?,
142    };
143    Some(Status {
144        id: id.clone(),
145        pane: e.pane.clone(),
146        state: e.state,
147        started_secs_ago: e.started.elapsed().as_secs(),
148        ended_secs_ago: e.ended.map(|t| t.elapsed().as_secs()),
149        open_secs: e.ended.map(|t| t.saturating_duration_since(e.started).as_secs()),
150    })
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    fn fresh() -> (String, String, String) {
158        let n = uuid::Uuid::new_v4().to_string();
159        (format!("h-{n}"), format!("pane-{n}"), format!("agent-{n}"))
160    }
161
162    #[test]
163    fn a_handoff_is_pending_until_it_is_answered() {
164        let (id, pane, agent) = fresh();
165        let t = Tracked::start(&id, &pane, &agent);
166        let s = status(&agent, Some(&id), None).unwrap();
167        assert_eq!((s.state, s.ended_secs_ago), (State::Pending, None));
168        t.finish(State::Done);
169        let s = status(&agent, Some(&id), None).unwrap();
170        assert_eq!(s.state, State::Done);
171        assert!(s.ended_secs_ago.is_some());
172        assert!(s.open_secs.is_some(), "how long it stayed open is kept with the answer");
173        assert_eq!(status(&agent, Some(&id), None).unwrap().open_secs, s.open_secs);
174    }
175
176    #[test]
177    fn a_pending_handoff_has_no_open_time_yet() {
178        let (id, pane, agent) = fresh();
179        let _t = Tracked::start(&id, &pane, &agent);
180        assert_eq!(status(&agent, Some(&id), None).unwrap().open_secs, None);
181    }
182
183    #[test]
184    fn the_end_of_a_handoff_says_who_answered_and_after_how_long() {
185        use crate::server::browser_attention::Answer;
186        let words = |a: Answer, s| ended_words(a.into(), Duration::from_secs(s));
187        assert_eq!(words(Answer::Yes, 3), "the person clicked Done after 3 s");
188        assert_eq!(words(Answer::Cancelled, 40), "the person clicked Cancel after 40 s");
189        assert_eq!(words(Answer::TimedOut, 15 * 60), "nobody answered in 15 min");
190        // An agent that took its own request back is not the person's Cancel.
191        let taken_back = crate::server::browser_attention::Settled { answer: Answer::Cancelled, by_agent: true };
192        assert_eq!(ended_words(taken_back, Duration::from_secs(12)), "the agent took it back after 12 s");
193    }
194
195    #[test]
196    fn a_call_that_ended_first_reads_as_abandoned() {
197        let (id, pane, agent) = fresh();
198        drop(Tracked::start(&id, &pane, &agent));
199        assert_eq!(status(&agent, Some(&id), None).unwrap().state, State::Abandoned);
200    }
201
202    #[test]
203    fn the_first_end_stands() {
204        let (id, pane, agent) = fresh();
205        let t = Tracked::start(&id, &pane, &agent);
206        settle(&id, State::Cancelled);
207        t.finish(State::Done);
208        assert_eq!(status(&agent, Some(&id), None).unwrap().state, State::Cancelled);
209    }
210
211    #[test]
212    fn by_pane_it_is_the_newest_and_only_the_agents_own() {
213        let (id, pane, agent) = fresh();
214        let older = Tracked::start(&id, &pane, &agent);
215        older.finish(State::Cancelled);
216        let newer_id = format!("{id}-2");
217        let newer = Tracked::start(&newer_id, &pane, &agent);
218        assert_eq!(status(&agent, None, Some(&pane)).unwrap().id, newer_id);
219        assert!(status("someone-else", None, Some(&pane)).is_none(), "another agent's hand-off is not shown");
220        assert!(status("someone-else", Some(&newer_id), None).is_none());
221        assert!(status(&agent, None, Some("no-such-pane")).is_none());
222        newer.finish(State::TimedOut);
223    }
224
225    #[test]
226    fn an_answer_maps_to_a_state() {
227        use crate::server::browser_attention::Answer;
228        assert_eq!(State::of_answer(Answer::Yes), State::Done);
229        assert_eq!(State::of_answer(Answer::Cancelled), State::Cancelled);
230        assert_eq!(State::of_answer(Answer::TimedOut), State::TimedOut);
231        assert_eq!(State::TimedOut.as_str(), "timed_out");
232    }
233}