Skip to main content

agentmux_launcher/notify/
linux.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Linux notification backend — `SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24.md` §6.3.
5//!
6//! freedesktop Desktop Notifications (`org.freedesktop.Notifications`) spoken
7//! directly over async zbus on the launcher's Tokio runtime — no libnotify,
8//! no GTK, no blocking D-Bus calls. One task owns the session-bus connection:
9//!
10//! - `Notify` with `replaces_id` = the server id last used for this tag, so a
11//!   same-group update replaces in place (spec §5.3);
12//! - `CloseNotification` for retract / clear-all;
13//! - `ActionInvoked("default")` → click, `NotificationClosed(reason 2)` →
14//!   user dismissal (1 = expired, 3 = closed by us — neither is feedback).
15//!
16//! Clicks only reach a process still on the bus — fine, the launcher lives for
17//! the whole session (and clears its notifications on exit).
18//!
19//! Content safety (§9.1): if the server advertises `body-markup`, the body is
20//! escaped so agent-influenced text can't inject markup. The summary is never
21//! markup per the spec.
22
23use std::collections::HashMap;
24use std::sync::mpsc as std_mpsc;
25
26use futures_util::StreamExt;
27use tokio::sync::mpsc;
28use zbus::zvariant::Value;
29
30use super::{Notification, Presenter, UserAction};
31
32const DEST: &str = "org.freedesktop.Notifications";
33const PATH: &str = "/org/freedesktop/Notifications";
34const IFACE: &str = "org.freedesktop.Notifications";
35
36enum Cmd {
37    Show(Notification),
38    Retract(String),
39    ClearAll(std_mpsc::Sender<()>),
40}
41
42pub struct LinuxPresenter {
43    tx: mpsc::UnboundedSender<Cmd>,
44}
45
46impl LinuxPresenter {
47    pub fn spawn(actions: mpsc::UnboundedSender<UserAction>) -> Self {
48        let (tx, rx) = mpsc::unbounded_channel();
49        tokio::spawn(run(rx, actions));
50        Self { tx }
51    }
52}
53
54impl Presenter for LinuxPresenter {
55    fn show(&self, n: &Notification) {
56        let _ = self.tx.send(Cmd::Show(n.clone()));
57    }
58    fn retract(&self, tag: &str) {
59        let _ = self.tx.send(Cmd::Retract(tag.to_string()));
60    }
61    fn clear_all(&self) {
62        let (done_tx, done_rx) = std_mpsc::channel();
63        if self.tx.send(Cmd::ClearAll(done_tx)).is_ok() {
64            let _ = done_rx.recv_timeout(std::time::Duration::from_secs(2));
65        }
66    }
67}
68
69/// Escape for servers that parse the body as (a subset of) markup.
70pub fn escape_markup(s: &str) -> String {
71    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
72}
73
74/// `(summary, body)` exactly as sent — pure, so the escaping rule is testable.
75/// (The freedesktop "summary" is our title.) The agent's session summary has
76/// no slot of its own on Linux, so it is the body's last line (rich-content
77/// spec §1.3), escaped like the rest of the body.
78pub fn texts(n: &Notification, body_markup: bool) -> (String, String) {
79    let body = [n.body.as_deref(), n.summary.as_deref()].into_iter().flatten().collect::<Vec<_>>().join("\n");
80    (n.title.clone(), if body_markup { escape_markup(&body) } else { body })
81}
82
83/// `(urgency, expire_timeout, resident)` for a notification.
84///
85/// Attention (needs input / crashed / needs review) must not silently expire
86/// before the user sees it (ReAgent P1 on #3668) — so it never expires
87/// (`expire_timeout = 0`) and is `resident` (stays in the list after an
88/// action). It deliberately stays at urgency **1**, not 2: "critical" breaks
89/// through Do Not Disturb on GNOME, which the spec forbids (§5.1, §6.0) —
90/// Windows' High priority doesn't bypass Focus either.
91pub fn delivery(n: &Notification) -> (u8, i32, bool) {
92    if n.is_attention() {
93        (1, 0, true)
94    } else {
95        (1, -1, false)
96    }
97}
98
99/// The `actions` array of a `Notify` call: `default` (the body click) and, when
100/// the toast offers buttons (cancel, do it now) and the server supports actions, those.
101/// Pairs of (key, label), flattened as the spec wants.
102pub fn action_args(n: &Notification, server_has_actions: bool) -> Vec<String> {
103    let mut out = vec!["default".to_string(), "Open".to_string()];
104    if server_has_actions {
105        for (id, label) in n.buttons() {
106            out.push(id.to_string());
107            out.push(label.to_string());
108        }
109    }
110    out
111}
112
113/// Which of our actions a press on a notification we showed names, if it is one
114/// we offered. Anything else on the bus is ignored.
115pub fn pressed(offered: &[String], action: &str, id: &str) -> Option<UserAction> {
116    match action {
117        "default" => Some(UserAction::Clicked(id.to_string())),
118        "keep" if offered.iter().any(|a| a == "keep") => Some(UserAction::Keep(id.to_string())),
119        "now" if offered.iter().any(|a| a == "now") => Some(UserAction::Now(id.to_string())),
120        _ => None,
121    }
122}
123
124/// Map a `NotificationClosed` reason to user feedback: only 2 ("dismissed by
125/// the user") counts.
126pub fn closed_is_user_dismissal(reason: u32) -> bool {
127    reason == 2
128}
129
130async fn run(mut rx: mpsc::UnboundedReceiver<Cmd>, actions: mpsc::UnboundedSender<UserAction>) {
131    let conn = match zbus::Connection::session().await {
132        Ok(c) => c,
133        Err(e) => {
134            crate::logging::log(&format!("notify: no D-Bus session bus ({e}); notifications disabled"));
135            // Keep draining so callers (clear_all's bounded wait) never stall.
136            while let Some(cmd) = rx.recv().await {
137                if let Cmd::ClearAll(done) = cmd {
138                    let _ = done.send(());
139                }
140            }
141            return;
142        }
143    };
144
145    let (body_markup, has_actions) = match conn.call_method(Some(DEST), PATH, Some(IFACE), "GetCapabilities", &()).await {
146        Ok(reply) => {
147            let caps = reply.body().deserialize::<Vec<String>>().unwrap_or_default();
148            (caps.iter().any(|x| x == "body-markup"), caps.iter().any(|x| x == "actions"))
149        }
150        Err(e) => {
151            crate::logging::log(&format!("notify: no notification server ({e})"));
152            (false, false)
153        }
154    };
155
156    // Only the notification server's own signals: without `sender`, any
157    // session-bus client could emit a forged ActionInvoked for one of our
158    // server ids (ReAgent P2 on #3668). The bus resolves the well-known name
159    // to its current owner when matching.
160    let rule = zbus::MatchRule::builder()
161        .msg_type(zbus::message::Type::Signal)
162        .sender(DEST)
163        .and_then(|b| b.path(PATH))
164        .and_then(|b| b.interface(IFACE))
165        .map(|b| b.build());
166    let mut signals = match rule {
167        Ok(rule) => zbus::MessageStream::for_match_rule(rule, &conn, None).await.ok(),
168        Err(_) => None,
169    };
170
171    // tag → (server id, our notification id); server id → our id.
172    let mut by_tag: HashMap<String, (u32, String)> = HashMap::new();
173    let mut by_server: HashMap<u32, String> = HashMap::new();
174    // server id → the action keys we offered on it.
175    let mut offered: HashMap<u32, Vec<String>> = HashMap::new();
176
177    loop {
178        tokio::select! {
179            cmd = rx.recv() => {
180                let Some(cmd) = cmd else { return };
181                match cmd {
182                    Cmd::Show(n) => {
183                        let replaces = by_tag.get(&n.tag).map(|(sid, _)| *sid).unwrap_or(0);
184                        let (summary, body) = texts(&n, body_markup);
185                        let mut hints: HashMap<&str, Value<'_>> = HashMap::new();
186                        hints.insert("desktop-entry", Value::from("agentmux"));
187                        let (urgency, timeout, resident) = delivery(&n);
188                        hints.insert("urgency", Value::from(urgency));
189                        if resident {
190                            hints.insert("resident", Value::from(true));
191                        }
192                        let action_list = action_args(&n, has_actions);
193                        let args = (
194                            "AgentMux",
195                            replaces,
196                            "agentmux",
197                            summary.as_str(),
198                            body.as_str(),
199                            action_list.clone(),
200                            hints,
201                            timeout,
202                        );
203                        match conn.call_method(Some(DEST), PATH, Some(IFACE), "Notify", &args).await {
204                            Ok(reply) => {
205                                if let Ok(sid) = reply.body().deserialize::<u32>() {
206                                    if let Some((old, _)) = by_tag.insert(n.tag.clone(), (sid, n.id.clone())) {
207                                        by_server.remove(&old);
208                                        offered.remove(&old);
209                                    }
210                                    by_server.insert(sid, n.id.clone());
211                                    offered.insert(sid, action_list);
212                                }
213                            }
214                            Err(e) => crate::logging::log(&format!("notify: Notify failed: {e}")),
215                        }
216                    }
217                    Cmd::Retract(tag) => {
218                        if let Some((sid, _)) = by_tag.remove(&tag) {
219                            by_server.remove(&sid);
220                            offered.remove(&sid);
221                            let _ = conn.call_method(Some(DEST), PATH, Some(IFACE), "CloseNotification", &(sid,)).await;
222                        }
223                    }
224                    Cmd::ClearAll(done) => {
225                        for (_, (sid, _)) in by_tag.drain() {
226                            let _ = conn.call_method(Some(DEST), PATH, Some(IFACE), "CloseNotification", &(sid,)).await;
227                        }
228                        by_server.clear();
229                        offered.clear();
230                        let _ = done.send(());
231                    }
232                }
233            }
234            msg = async {
235                match signals.as_mut() {
236                    Some(s) => s.next().await,
237                    None => std::future::pending().await,
238                }
239            } => {
240                let Some(Ok(msg)) = msg else { continue };
241                let header = msg.header();
242                let member = header.member().map(|m| m.as_str().to_string()).unwrap_or_default();
243                match member.as_str() {
244                    "ActionInvoked" => {
245                        if let Ok((sid, action)) = msg.body().deserialize::<(u32, String)>() {
246                            if let Some(id) = by_server.get(&sid) {
247                                let list = offered.get(&sid).map(Vec::as_slice).unwrap_or_default();
248                                if let Some(press) = pressed(list, &action, id) {
249                                    let _ = actions.send(press);
250                                }
251                            }
252                        }
253                    }
254                    "NotificationClosed" => {
255                        if let Ok((sid, reason)) = msg.body().deserialize::<(u32, u32)>() {
256                            if let Some(id) = by_server.remove(&sid) {
257                                offered.remove(&sid);
258                                by_tag.retain(|_, (s, _)| *s != sid);
259                                if closed_is_user_dismissal(reason) {
260                                    let _ = actions.send(UserAction::Dismissed(id));
261                                }
262                            }
263                        }
264                    }
265                    _ => {}
266                }
267            }
268        }
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    fn n(body: Option<&str>) -> Notification {
277        Notification {
278            id: "n1".into(),
279            kind: "input_waiting".into(),
280            priority: "attention".into(),
281            title: "lark has a question".into(),
282            body: body.map(Into::into),
283            summary: None,
284            actions: vec![],
285            countdown: None,
286            tag: "t1".into(),
287        }
288    }
289
290    #[test]
291    fn body_is_escaped_only_for_markup_servers() {
292        let evil = "<a href='x'>click</a> & more";
293        assert_eq!(texts(&n(Some(evil)), true).1, "&lt;a href='x'&gt;click&lt;/a&gt; &amp; more");
294        assert_eq!(texts(&n(Some(evil)), false).1, evil);
295        assert_eq!(texts(&n(None), true), ("lark has a question".to_string(), String::new()));
296    }
297
298    #[test]
299    fn summary_is_the_last_body_line_and_escaped_with_it() {
300        let with = |body: Option<&str>, summary: &str| Notification { summary: Some(summary.into()), ..n(body) };
301        assert_eq!(texts(&with(Some("Which branch?"), "Fix repaint"), false).1, "Which branch?\nFix repaint");
302        assert_eq!(texts(&with(None, "Fix repaint"), false).1, "Fix repaint");
303        assert_eq!(texts(&with(Some("a"), "<b>x</b>"), true).1, "a\n&lt;b&gt;x&lt;/b&gt;");
304    }
305
306    #[test]
307    fn attention_never_expires_but_never_goes_critical() {
308        let mut a = n(None);
309        a.priority = "attention".into();
310        assert_eq!(delivery(&a), (1, 0, true));
311        let mut normal = n(None);
312        normal.priority = "normal".into();
313        assert_eq!(delivery(&normal), (1, -1, false));
314    }
315
316    #[test]
317    fn only_user_dismissal_is_feedback() {
318        assert!(closed_is_user_dismissal(2));
319        assert!(!closed_is_user_dismissal(1)); // expired
320        assert!(!closed_is_user_dismissal(3)); // closed by us
321        assert!(!closed_is_user_dismissal(4));
322    }
323
324    fn closing() -> Notification {
325        Notification {
326            actions: vec![
327                super::super::NotifyAction { id: "keep".into(), label: "Keep running".into() },
328                super::super::NotifyAction { id: "now".into(), label: "Close now".into() },
329            ],
330            ..n(Some("AgentY asked to close it."))
331        }
332    }
333
334    /// The buttons are offered only when the server supports
335    /// actions; the body click is always there.
336    #[test]
337    fn the_buttons_are_actions_only_where_the_server_supports_actions() {
338        assert_eq!(action_args(&closing(), true), vec!["default", "Open", "keep", "Keep running", "now", "Close now"]);
339        assert_eq!(action_args(&closing(), false), vec!["default", "Open"]);
340        assert_eq!(action_args(&n(None), true), vec!["default", "Open"], "no button for any other notification");
341    }
342
343    /// Only an action we offered counts: a forged `keep` for a notification
344    /// that never had the button does nothing.
345    #[test]
346    fn a_press_is_only_what_we_offered() {
347        let offered = action_args(&closing(), true);
348        assert_eq!(pressed(&offered, "keep", "n1"), Some(UserAction::Keep("n1".into())));
349        assert_eq!(pressed(&offered, "now", "n1"), Some(UserAction::Now("n1".into())));
350        assert_eq!(pressed(&offered, "default", "n1"), Some(UserAction::Clicked("n1".into())));
351        assert_eq!(pressed(&offered, "something-else", "n1"), None);
352        let plain = action_args(&n(None), true);
353        assert_eq!(pressed(&plain, "keep", "n2"), None);
354        assert_eq!(pressed(&plain, "now", "n2"), None);
355    }
356}