Skip to main content

agentmux_srv_core/backend/
user_attention.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "An agent is waiting for you", announced by srv for the calls to action it
5//! holds open: a browser hand-off or approval, an SSH consent or other host
6//! question, a widget install
7//! (docs/reports/REPORT_AGENT_ATTENTION_CTA_CONTRAST_AND_TONE_2026_10_10.md ยง2).
8//!
9//! Each one publishes `userattention` with `active: true` when it starts and
10//! `active: false` when it ends, however it ends: the guard's `Drop` sends
11//! the end. The frontend's waiting-for-you registry turns them into the
12//! waiting tone, the tab flash and the OS notification for the pane, in the
13//! windows that show it (`window_ids`; empty means every window).
14
15use std::collections::HashMap;
16use std::sync::{Arc, Mutex, OnceLock};
17
18use super::mps::Broker;
19use super::storage::store::Store;
20
21/// Every kind a call to action can carry. The status bar's summary gives each one a part and a place to answer it
22/// (`frontend/app/statusbar/summary-kinds.ts`); a test there reads this list, so a new kind has to be given both.
23pub const KINDS: [&str; 7] = ["browser", "consent", "confirm", "vault", "widget", "upgrade", "desktop"];
24
25/// One call to action srv holds open: the `userattention` event's payload
26/// (`mps_events::UserAttention`), and a row of `notify.attention`'s list.
27#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
28#[ts(export, export_to = "../../../frontend/types/rpc/")]
29pub struct UserAttentionEvent {
30    pub key: String,
31    /// The pane it's in; empty for none.
32    pub block_id: String,
33    /// One of [`KINDS`]: `browser`, `consent`, `confirm` (a pane asks the person about their own click), `vault`,
34    /// `widget`, `upgrade` or `desktop`.
35    pub kind: String,
36    pub text: String,
37    /// The windows showing it; empty means every window.
38    pub window_ids: Vec<String>,
39    #[ts(type = "number")]
40    pub since_ms: u64,
41    /// True while it's open; false once, when it ends.
42    pub active: bool,
43}
44
45/// The announcements open now, for a window that starts while one is.
46fn open() -> &'static Mutex<HashMap<String, UserAttentionEvent>> {
47    static OPEN: OnceLock<Mutex<HashMap<String, UserAttentionEvent>>> = OnceLock::new();
48    OPEN.get_or_init(Default::default)
49}
50
51/// Every open announcement (`active: true`), oldest first.
52pub fn open_requests() -> Vec<UserAttentionEvent> {
53    let mut v: Vec<UserAttentionEvent> = open().lock().unwrap_or_else(|p| p.into_inner()).values().cloned().collect();
54    v.sort_by_key(|a| a.since_ms);
55    v
56}
57
58/// The request is open while this lives.
59pub struct Asking {
60    broker: Arc<Broker>,
61    payload: UserAttentionEvent,
62}
63
64impl Asking {
65    /// Announces a call to action in pane `block_id` (empty: no pane) of
66    /// kind `kind` (`browser`, `consent`, `widget`, `confirm`), described by `text`.
67    pub fn start(broker: &Arc<Broker>, store: &Store, block_id: &str, kind: &str, text: &str) -> Self {
68        debug_assert!(KINDS.contains(&kind), "user attention kind {kind:?} is not in KINDS: give it a part in the status bar summary");
69        let window_ids = if block_id.is_empty() {
70            Vec::new()
71        } else {
72            super::notify::router::resolve_click_target(store, block_id).map(|t| t.window_ids).unwrap_or_default()
73        };
74        let payload = UserAttentionEvent {
75            key: uuid::Uuid::new_v4().to_string(),
76            block_id: block_id.to_string(),
77            kind: kind.to_string(),
78            text: text.chars().take(200).collect::<String>(),
79            window_ids,
80            since_ms: agentmux_common::time::now_ms_u64(),
81            active: true,
82        };
83        open().lock().unwrap_or_else(|p| p.into_inner()).insert(payload.key.clone(), payload.clone());
84        publish(broker, &payload, true);
85        Self { broker: broker.clone(), payload }
86    }
87}
88
89impl Drop for Asking {
90    fn drop(&mut self) {
91        open().lock().unwrap_or_else(|p| p.into_inner()).remove(&self.payload.key);
92        publish(&self.broker, &self.payload, false);
93    }
94}
95
96fn publish(broker: &Broker, payload: &UserAttentionEvent, active: bool) {
97    let event = UserAttentionEvent { active, ..payload.clone() };
98    broker.publish_event::<super::mps_events::UserAttention>(&event, vec![], 0);
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::backend::mps::EVENT_USER_ATTENTION;
105    use serde_json::{json, Value};
106    use std::path::Path;
107
108    #[test]
109    fn announces_the_start_and_always_the_end() {
110        let seen = Arc::new(std::sync::Mutex::new(Vec::<Value>::new()));
111        let broker = Arc::new(Broker::new());
112        let log = seen.clone();
113        broker.add_observer(Arc::new(move |ev| {
114            if ev.event == EVENT_USER_ATTENTION {
115                log.lock().unwrap().push(ev.data.clone().unwrap_or_default());
116            }
117        }));
118        let store = Store::open(Path::new(":memory:")).unwrap();
119        {
120            let _asking = Asking::start(&broker, &store, "", "consent", "Agent access to area54");
121            let s = seen.lock().unwrap();
122            assert_eq!(s.len(), 1);
123            assert_eq!((s[0]["active"].clone(), s[0]["kind"].clone()), (json!(true), json!("consent")));
124            assert_eq!(s[0]["window_ids"], json!([]), "no pane: every window");
125            let key = s[0]["key"].clone();
126            assert!(open_requests().iter().any(|a| json!(a.key) == key && a.active), "listed while open");
127        }
128        assert!(open_requests().iter().all(|a| json!(a.key) != seen.lock().unwrap()[0]["key"]), "gone once ended");
129        let s = seen.lock().unwrap();
130        assert_eq!(s.len(), 2, "the end is announced when it's dropped");
131        assert_eq!(s[1]["active"], json!(false));
132        assert_eq!(s[1]["key"], s[0]["key"]);
133    }
134}