Skip to main content

agentmux_launcher/notify/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! OS notification **Presenter** — `docs/specs/SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24.md` §3.2, §6.
5//!
6//! The srv Router decides *whether* to notify and publishes `notification` /
7//! `notification:retract` on its event bus. This module is the launcher's
8//! subscriber: it keeps a WebSocket to srv (the launcher's first), renders
9//! each notification with the platform backend, and reports the user's
10//! click/dismiss back as `notify.ack`.
11//!
12//! Why the launcher (spec §3.2): it outlives host restarts, stays up with no
13//! window in background mode, owns the tray, and — on macOS — is the bundle's
14//! main executable. Click callbacks need a live process; this is the
15//! longest-lived one.
16//!
17//! ## Lifecycle
18//!
19//! `start` once srv is up; `update_endpoint` whenever srv is respawned (new
20//! port + auth key); `shutdown` before the launcher exits, which clears every
21//! toast this app put in the notification center — a click on a toast from a
22//! dead instance could do nothing useful (Phase 1 has no cold-start
23//! activation, spec §6.1).
24
25use agentmux_common::AUTH_KEY_HEADER;
26use std::sync::{Arc, OnceLock};
27
28use futures_util::{SinkExt, StreamExt};
29use serde::Deserialize;
30use tokio::sync::{mpsc, watch};
31use tokio_tungstenite::tungstenite::{ClientRequestBuilder, Message};
32
33#[cfg(target_os = "windows")]
34mod windows;
35#[cfg(target_os = "linux")]
36mod linux;
37
38/// Mirrors srv's `OsNotification` (`crates/srv-core/src/backend/notify/policy.rs`).
39/// Unknown fields are ignored so srv can grow the payload first.
40#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
41pub struct Notification {
42    pub id: String,
43    pub kind: String,
44    pub priority: String,
45    pub title: String,
46    #[serde(default)]
47    pub body: Option<String>,
48    /// What the agent is working on — a small line under the body
49    /// (`SPEC_OS_NOTIFICATIONS_RICH_CONTENT_AND_CLICK_TO_PANE_2026_09_25.md`
50    /// §1.3). Absent from an older srv, and when the agent has none.
51    #[serde(default)]
52    pub summary: Option<String>,
53    /// Buttons the toast offers. Absent from an older srv, and for every
54    /// notification but a pending shutdown. The id is one of a closed set
55    /// (`keep`); the label is app text, never an agent's.
56    #[serde(default)]
57    pub actions: Vec<NotifyAction>,
58    /// A live countdown to tick, where the platform can show one. Absent from
59    /// an older srv.
60    #[serde(default)]
61    pub countdown: Option<Countdown>,
62    pub tag: String,
63}
64
65impl Notification {
66    pub fn is_attention(&self) -> bool {
67        self.priority == "attention"
68    }
69
70    /// The label of the cancel button (Keep running, or a sensitive operation's veto), when the toast offers one.
71    pub fn keep_label(&self) -> Option<&str> {
72        self.actions.iter().find(|a| a.id == "keep").map(|a| a.label.as_str())
73    }
74
75    /// The label of the do-it-now button (Close now, ...), when the toast offers one.
76    pub fn now_label(&self) -> Option<&str> {
77        self.actions.iter().find(|a| a.id == "now").map(|a| a.label.as_str())
78    }
79
80    /// The buttons the toast offers, in order: (`UserAction` id, label). Only the two ids srv sends.
81    pub fn buttons(&self) -> Vec<(&'static str, &str)> {
82        [("keep", self.keep_label()), ("now", self.now_label())].into_iter().filter_map(|(id, label)| Some((id, label?))).collect()
83    }
84}
85
86/// A button on a toast (srv's `NotifyAction`).
87#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
88pub struct NotifyAction {
89    pub id: String,
90    pub label: String,
91}
92
93/// srv's `Countdown`: time left when shown (relative, so clock skew never
94/// matters) and the title with `{n}` where the whole seconds go.
95#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
96pub struct Countdown {
97    pub remaining_ms: i64,
98    pub title_template: String,
99}
100
101/// One tick of a countdown, for a backend that can redraw a live toast.
102#[derive(Clone, Debug, PartialEq)]
103pub struct CountdownUpdate {
104    /// "Closing QTimer in 9 s".
105    pub title: String,
106    /// 1.0 when it starts, 0.0 when the time is up: the bar drains.
107    pub fraction_left: f64,
108    /// "9 s".
109    pub seconds_text: String,
110}
111
112/// The whole seconds left, rounded up, never negative.
113fn seconds_left(remaining_ms: i64) -> i64 {
114    (remaining_ms.max(0) + 999) / 1000
115}
116
117/// `template` with `{n}` replaced by `value`. Only the last `{n}`: the
118/// template ends with the app's own placeholder, and an agent name earlier in
119/// it can't take its place.
120fn fill_countdown(template: &str, value: &str) -> String {
121    match template.rfind("{n}") {
122        Some(i) => format!("{}{}{}", &template[..i], value, &template[i + 3..]),
123        None => template.to_string(),
124    }
125}
126
127/// What the toast shows with `remaining_ms` of `total_ms` left. Pure.
128pub fn countdown_update(template: &str, remaining_ms: i64, total_ms: i64) -> CountdownUpdate {
129    let secs = seconds_left(remaining_ms);
130    let fraction_left = if total_ms <= 0 { 0.0 } else { (remaining_ms.max(0) as f64 / total_ms as f64).clamp(0.0, 1.0) };
131    CountdownUpdate {
132        title: fill_countdown(template, &secs.to_string()),
133        fraction_left,
134        seconds_text: format!("{secs} s"),
135    }
136}
137
138/// What the user did — on a toast (reported by a backend) or in the tray's
139/// notification menu (`tray_request`).
140#[derive(Clone, Debug, PartialEq, Eq)]
141pub enum UserAction {
142    Clicked(String),
143    Dismissed(String),
144    /// The cancel button on a toast (by notification id): Keep running, or a sensitive operation's veto.
145    Keep(String),
146    /// The do-it-now button on a toast (by notification id): Close now, ...
147    Now(String),
148    /// Set `notify:pause:until` (epoch ms; 0 = resume).
149    SetPause(i64),
150    /// Set `app:startatlogin` (the tray's check item; `start_at_login`).
151    SetStartAtLogin(bool),
152}
153
154/// A platform notification surface.
155pub trait Presenter: Send + Sync {
156    fn show(&self, n: &Notification);
157    fn retract(&self, tag: &str);
158    fn clear_all(&self);
159    /// Redraw the live toast `tag` for one tick of its countdown. Only a
160    /// backend that can show a countdown does anything.
161    fn update(&self, _tag: &str, _update: &CountdownUpdate) {}
162}
163
164/// No platform backend (macOS today — needs a signed bundle and a Mac to
165/// verify, spec §6.2): log and drop.
166struct NullPresenter;
167impl Presenter for NullPresenter {
168    fn show(&self, n: &Notification) {
169        crate::logging::log(&format!("notify: no OS backend on this platform; dropping '{}'", n.kind));
170    }
171    fn retract(&self, _tag: &str) {}
172    fn clear_all(&self) {}
173}
174
175#[derive(Clone, Debug, PartialEq, Eq)]
176struct Endpoint {
177    ws: String,
178    auth_key: String,
179    /// What srv accepts as the launcher's proof on a press that skips or stops a wait: the host
180    /// registration secret this launcher made for srv, which no agent has (`SrvSpawnResult`).
181    proof: String,
182}
183
184struct Handle {
185    endpoint: watch::Sender<Option<Endpoint>>,
186    presenter: Arc<dyn Presenter>,
187}
188
189/// The launcher's reducer state — where a clicked toast's window is looked up
190/// (backend window id → label → HWND).
191pub type LauncherState = Arc<tokio::sync::Mutex<crate::state::State>>;
192
193static HANDLE: OnceLock<Handle> = OnceLock::new();
194
195/// The user-action channel exists from first use, not from `start`: the tray
196/// (and its Pause/Resume/Open menu) comes up before srv does, and a pick made
197/// in that window must queue until the presenter connects rather than vanish
198/// (ReAgent P2 on #3654). `start` takes the receiver.
199type ActionChannel = (mpsc::UnboundedSender<UserAction>, std::sync::Mutex<Option<mpsc::UnboundedReceiver<UserAction>>>);
200static ACTIONS: OnceLock<ActionChannel> = OnceLock::new();
201
202fn actions() -> &'static ActionChannel {
203    ACTIONS.get_or_init(|| {
204        let (tx, rx) = mpsc::unbounded_channel();
205        (tx, std::sync::Mutex::new(Some(rx)))
206    })
207}
208
209fn make_presenter(actions: mpsc::UnboundedSender<UserAction>, data_dir: &std::path::Path) -> Arc<dyn Presenter> {
210    #[cfg(target_os = "windows")]
211    {
212        match windows::WindowsPresenter::spawn(actions, data_dir) {
213            Ok(p) => return Arc::new(p),
214            Err(e) => crate::logging::log(&format!("notify: Windows toast backend unavailable: {e}")),
215        }
216    }
217    #[cfg(target_os = "linux")]
218    {
219        let _ = data_dir;
220        return Arc::new(linux::LinuxPresenter::spawn(actions));
221    }
222    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
223    let _ = (actions, data_dir);
224    #[allow(unreachable_code)]
225    Arc::new(NullPresenter)
226}
227
228/// Start the presenter. Idempotent: a second call only updates the endpoint.
229pub fn start(
230    ws_endpoint: &str,
231    auth_key: &str,
232    proof: &str,
233    data_dir: std::path::PathBuf,
234    dir_hash: String,
235    state: LauncherState,
236) {
237    let ep = Endpoint { ws: ws_endpoint.to_string(), auth_key: auth_key.to_string(), proof: proof.to_string() };
238    if let Some(h) = HANDLE.get() {
239        let _ = h.endpoint.send(Some(ep));
240        return;
241    }
242    let act_tx = actions().0.clone();
243    let Some(act_rx) = actions().1.lock().unwrap_or_else(|e| e.into_inner()).take() else {
244        return;
245    };
246    let presenter = make_presenter(act_tx, &data_dir);
247    // A fresh launcher owns nothing on screen yet — anything left over from a
248    // previous (crashed) run points at a dead instance.
249    presenter.clear_all();
250    let (ep_tx, ep_rx) = watch::channel(Some(ep));
251    if HANDLE.set(Handle { endpoint: ep_tx, presenter: presenter.clone() }).is_err() {
252        return;
253    }
254    tokio::spawn(run(ep_rx, act_rx, presenter, data_dir, dir_hash, state));
255}
256
257/// srv was respawned: reconnect to its new endpoint. The toasts on screen
258/// name ids the new srv never issued — clear them rather than leave clicks
259/// that can't find their pane (rich-content spec §3.3 F).
260pub fn update_endpoint(ws_endpoint: &str, auth_key: &str, proof: &str) {
261    if let Some(h) = HANDLE.get() {
262        h.presenter.clear_all();
263        let _ = h.endpoint.send(Some(Endpoint { ws: ws_endpoint.to_string(), auth_key: auth_key.to_string(), proof: proof.to_string() }));
264    }
265}
266
267/// The tray's notification menu (spec §4.2): open an attention item exactly
268/// as its toast click would, or pause/resume. Non-blocking; callable from the
269/// tray thread.
270pub fn tray_request(action: crate::tray::notify_menu::NotifyMenuAction) {
271    use crate::tray::notify_menu::{resolve_pause, NotifyMenuAction};
272    let ua = match action {
273        NotifyMenuAction::Open(id) => {
274            // The menu pick made us foreground-eligible; hand that to the host
275            // so it can raise its window.
276            #[cfg(target_os = "windows")]
277            unsafe {
278                let _ = ::windows::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(
279                    ::windows::Win32::UI::WindowsAndMessaging::ASFW_ANY,
280                );
281            }
282            UserAction::Clicked(id)
283        }
284        NotifyMenuAction::Pause(choice) => UserAction::SetPause(resolve_pause(choice, chrono::Local::now())),
285        NotifyMenuAction::Resume => UserAction::SetPause(0),
286    };
287    // Queues even before `start` — delivered once the presenter connects.
288    let _ = actions().0.send(ua);
289}
290
291/// Write `app:startatlogin` through srv, like any settings change, so the
292/// Settings page and the OS login entry follow it (`start_at_login`). Queues
293/// until the session is up.
294pub fn request_start_at_login(on: bool) {
295    let _ = actions().0.send(UserAction::SetStartAtLogin(on));
296}
297
298/// Launcher is exiting: remove our toasts from the notification center.
299pub fn shutdown() {
300    if let Some(h) = HANDLE.get() {
301        h.presenter.clear_all();
302    }
303}
304
305/// `host:port` (srv's ESTART form) or a full URL → the `/ws` URL.
306pub fn ws_url(endpoint: &str) -> String {
307    let base = endpoint.trim_end_matches('/');
308    let base = if base.starts_with("ws://") || base.starts_with("wss://") {
309        base.to_string()
310    } else {
311        format!("ws://{base}")
312    };
313    format!("{base}/ws")
314}
315
316/// What an incoming srv frame means to the presenter.
317#[derive(Debug, PartialEq, Eq)]
318pub enum Frame {
319    Show(Notification),
320    Retract(String),
321    State(crate::tray::notify_menu::NotifyTrayState),
322    /// A full-config broadcast: the value of `app:startatlogin` (`None` = unset).
323    StartAtLogin(Option<bool>),
324    Response { reqid: String, ack: AckResponse },
325    Other,
326}
327
328/// srv's `notify.ack` answer (`NotifyAckResult`).
329#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
330pub struct AckResponse {
331    #[serde(default)]
332    pub has_window: Option<bool>,
333    #[serde(default)]
334    pub window_id: Option<String>,
335    #[serde(default)]
336    pub workspace_id: Option<String>,
337}
338
339/// What a click makes the launcher do (rich-content spec §3.3 C, D, F).
340#[derive(Debug, PartialEq, Eq)]
341pub enum ClickPlan {
342    /// Raise this open window (backend window id); its frontend selects the
343    /// pane from `notification:activate`.
344    Raise(String),
345    /// The pane's workspace is open in no window: open one on it.
346    OpenWorkspace(String),
347    /// No window at all (background mode, or the pane is gone): open one.
348    OpenWindow,
349    Nothing,
350}
351
352/// Pure: srv decided the target; this only maps its answer to an action.
353pub fn click_plan(ack: &AckResponse) -> ClickPlan {
354    if let Some(w) = ack.window_id.as_ref().filter(|w| !w.is_empty()) {
355        return ClickPlan::Raise(w.clone());
356    }
357    if let Some(ws) = ack.workspace_id.as_ref().filter(|w| !w.is_empty()) {
358        return ClickPlan::OpenWorkspace(ws.clone());
359    }
360    if ack.has_window == Some(false) {
361        return ClickPlan::OpenWindow;
362    }
363    ClickPlan::Nothing
364}
365
366/// The host window showing backend window `window_id`: `(label, hwnd, iconic)`.
367pub fn window_for(state: &crate::state::State, window_id: &str) -> Option<(String, Option<u64>, bool)> {
368    let label = state.backend_window_ids.iter().find(|(_, w)| w.as_str() == window_id).map(|(l, _)| l.clone())?;
369    let mirror = state.windows.get(&label);
370    Some((label, mirror.and_then(|m| m.hwnd), mirror.is_some_and(|m| m.iconic)))
371}
372
373/// Parse one srv WS text frame. Events arrive as
374/// `{"eventtype":"rpc","data":{"command":"eventrecv","data":<MuxEvent>}}`;
375/// RPC responses as `{"eventtype":"rpc","data":{"resid":..,"data":..}}`.
376pub fn parse_frame(text: &str) -> Frame {
377    let Ok(v) = serde_json::from_str::<serde_json::Value>(text) else {
378        return Frame::Other;
379    };
380    let Some(data) = v.get("data") else { return Frame::Other };
381    if let Some(resid) = data.get("resid").and_then(|r| r.as_str()) {
382        return Frame::Response {
383            reqid: resid.to_string(),
384            ack: data.get("data").and_then(|d| serde_json::from_value(d.clone()).ok()).unwrap_or_default(),
385        };
386    }
387    if data.get("command").and_then(|c| c.as_str()) != Some("eventrecv") {
388        return Frame::Other;
389    }
390    let Some(ev) = data.get("data") else { return Frame::Other };
391    match ev.get("event").and_then(|e| e.as_str()) {
392        Some("notification") => ev
393            .get("data")
394            .and_then(|d| serde_json::from_value::<Notification>(d.clone()).ok())
395            .map(Frame::Show)
396            .unwrap_or(Frame::Other),
397        Some("notification:state") => ev
398            .get("data")
399            .and_then(|d| serde_json::from_value(d.clone()).ok())
400            .map(Frame::State)
401            .unwrap_or(Frame::Other),
402        Some("config") => ev
403            .get("data")
404            .and_then(|d| d.get("fullconfig"))
405            .and_then(|c| c.get("settings"))
406            .map(|s| Frame::StartAtLogin(s.get(crate::start_at_login::SETTINGS_KEY).and_then(|v| v.as_bool())))
407            .unwrap_or(Frame::Other),
408        Some("notification:retract") => ev
409            .get("data")
410            .and_then(|d| d.get("tag"))
411            .and_then(|t| t.as_str())
412            .map(|t| Frame::Retract(t.to_string()))
413            .unwrap_or(Frame::Other),
414        _ => Frame::Other,
415    }
416}
417
418/// The data of a `notify.ack`: a body click, a dismissal, or (`action`) a
419/// button. The id is the notification's; what a button does is decided in srv
420/// from its own record, never from this. A button carries `proof`: any client with the
421/// instance key can send an ack, and srv does what skips or stops a wait only for the launcher.
422fn ack_params(id: &str, clicked: bool, action: Option<&str>, proof: &str) -> serde_json::Value {
423    let mut data = serde_json::json!({ "id": id, "clicked": clicked });
424    if let Some(action) = action {
425        data["action"] = serde_json::Value::String(action.to_string());
426        if !proof.is_empty() {
427            data["proof"] = serde_json::Value::String(proof.to_string());
428        }
429    }
430    data
431}
432
433/// The tasks ticking live toasts' countdowns, by toast tag. One a second until
434/// the time is up; stopped when the toast is retracted or replaced, and all of
435/// them when the session ends.
436#[derive(Default)]
437struct Countdowns {
438    tasks: std::collections::HashMap<String, tokio::task::JoinHandle<()>>,
439}
440
441impl Countdowns {
442    fn start(&mut self, presenter: &Arc<dyn Presenter>, n: &Notification) {
443        self.stop(&n.tag);
444        let Some(c) = n.countdown.clone().filter(|c| c.remaining_ms > 0) else { return };
445        let (presenter, tag) = (presenter.clone(), n.tag.clone());
446        let started = std::time::Instant::now();
447        let task = tokio::spawn(async move {
448            let mut tick = tokio::time::interval(std::time::Duration::from_secs(1));
449            tick.tick().await; // the show itself drew the first frame
450            loop {
451                tick.tick().await;
452                let elapsed = started.elapsed().as_millis() as i64;
453                let remaining = c.remaining_ms - elapsed;
454                presenter.update(&tag, &countdown_update(&c.title_template, remaining, c.remaining_ms));
455                if remaining <= 0 {
456                    return;
457                }
458            }
459        });
460        self.tasks.insert(n.tag.clone(), task);
461    }
462
463    fn stop(&mut self, tag: &str) {
464        if let Some(task) = self.tasks.remove(tag) {
465            task.abort();
466        }
467    }
468}
469
470impl Drop for Countdowns {
471    fn drop(&mut self) {
472        for (_, task) in self.tasks.drain() {
473            task.abort();
474        }
475    }
476}
477
478fn rpc(command: &str, reqid: Option<&str>, data: serde_json::Value) -> String {
479    let mut msg = serde_json::json!({ "command": command, "data": data });
480    if let Some(r) = reqid {
481        msg["reqid"] = serde_json::Value::String(r.to_string());
482    }
483    serde_json::json!({ "wscommand": "rpc", "message": msg }).to_string()
484}
485
486async fn run(
487    mut ep_rx: watch::Receiver<Option<Endpoint>>,
488    mut act_rx: mpsc::UnboundedReceiver<UserAction>,
489    presenter: Arc<dyn Presenter>,
490    data_dir: std::path::PathBuf,
491    dir_hash: String,
492    state: LauncherState,
493) {
494    let mut backoff_ms = 500u64;
495    loop {
496        let ep = ep_rx.borrow_and_update().clone();
497        let Some(ep) = ep else {
498            if ep_rx.changed().await.is_err() {
499                return;
500            }
501            continue;
502        };
503        match session(&ep, &mut ep_rx, &mut act_rx, &presenter, &data_dir, &dir_hash, &state).await {
504            SessionEnd::EndpointChanged => {
505                backoff_ms = 500;
506                continue;
507            }
508            SessionEnd::Closed(reason) => {
509                crate::logging::log(&format!("notify: srv connection ended ({reason}); retrying in {backoff_ms}ms"));
510            }
511        }
512        tokio::select! {
513            _ = tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)) => {}
514            r = ep_rx.changed() => if r.is_err() { return; },
515        }
516        backoff_ms = (backoff_ms * 2).min(30_000);
517    }
518}
519
520enum SessionEnd {
521    EndpointChanged,
522    Closed(String),
523}
524
525async fn session(
526    ep: &Endpoint,
527    ep_rx: &mut watch::Receiver<Option<Endpoint>>,
528    act_rx: &mut mpsc::UnboundedReceiver<UserAction>,
529    presenter: &Arc<dyn Presenter>,
530    data_dir: &std::path::Path,
531    dir_hash: &str,
532    state: &LauncherState,
533) -> SessionEnd {
534    let uri: tokio_tungstenite::tungstenite::http::Uri = match ws_url(&ep.ws).parse() {
535        Ok(u) => u,
536        Err(e) => return SessionEnd::Closed(format!("bad endpoint: {e}")),
537    };
538    // Header auth (`X-AuthKey`), as srv's auth_middleware accepts for /ws.
539    // ClientRequestBuilder generates the handshake headers itself — see
540    // cloud_subscriber.rs for why a hand-built Request fails the handshake.
541    let request = ClientRequestBuilder::new(uri).with_header(AUTH_KEY_HEADER, ep.auth_key.clone());
542    let (ws, _) = match tokio_tungstenite::connect_async(request).await {
543        Ok(s) => s,
544        Err(e) => return SessionEnd::Closed(format!("connect: {e}")),
545    };
546    let (mut write, mut read) = ws.split();
547    for event in ["notification", "notification:retract", "notification:state"] {
548        let sub = rpc("eventsub", None, serde_json::json!({ "event": event, "scopes": [], "allscopes": true }));
549        if let Err(e) = write.send(Message::Text(sub.into())).await {
550            return SessionEnd::Closed(format!("subscribe: {e}"));
551        }
552    }
553    crate::logging::log("notify: subscribed to srv notifications");
554
555    // reqid → was it a click (needs has_window handling)?
556    let mut pending_clicks: std::collections::HashSet<String> = Default::default();
557    // tag → the task ticking that toast's countdown; dropped with the session.
558    let mut countdowns = Countdowns::default();
559
560    loop {
561        tokio::select! {
562            changed = ep_rx.changed() => {
563                if changed.is_err() || ep_rx.borrow().as_ref() != Some(ep) {
564                    return SessionEnd::EndpointChanged;
565                }
566            }
567            action = act_rx.recv() => {
568                let Some(action) = action else { return SessionEnd::Closed("presenter gone".into()) };
569                let (id, clicked, button) = match &action {
570                    UserAction::Clicked(id) => (id.clone(), true, None),
571                    UserAction::Dismissed(id) => (id.clone(), false, None),
572                    UserAction::Keep(id) => (id.clone(), false, Some("keep")),
573                    UserAction::Now(id) => (id.clone(), false, Some("now")),
574                    UserAction::SetPause(until) => {
575                        let msg = rpc("setconfig", Some(&uuid::Uuid::new_v4().to_string()), serde_json::json!({ "notify:pause:until": until }));
576                        if let Err(e) = write.send(Message::Text(msg.into())).await {
577                            return SessionEnd::Closed(format!("send setconfig: {e}"));
578                        }
579                        continue;
580                    }
581                    UserAction::SetStartAtLogin(on) => {
582                        let msg = rpc("setconfig", Some(&uuid::Uuid::new_v4().to_string()), serde_json::json!({ crate::start_at_login::SETTINGS_KEY: on }));
583                        if let Err(e) = write.send(Message::Text(msg.into())).await {
584                            return SessionEnd::Closed(format!("send setconfig: {e}"));
585                        }
586                        continue;
587                    }
588                };
589                let reqid = uuid::Uuid::new_v4().to_string();
590                if clicked {
591                    pending_clicks.insert(reqid.clone());
592                }
593                let msg = rpc("notify.ack", Some(&reqid), ack_params(&id, clicked, button, &ep.proof));
594                if let Err(e) = write.send(Message::Text(msg.into())).await {
595                    return SessionEnd::Closed(format!("send ack: {e}"));
596                }
597            }
598            msg = read.next() => {
599                let text = match msg {
600                    Some(Ok(Message::Text(t))) => t.to_string(),
601                    Some(Ok(Message::Close(_))) | None => return SessionEnd::Closed("closed by srv".into()),
602                    Some(Ok(_)) => continue,
603                    Some(Err(e)) => return SessionEnd::Closed(format!("read: {e}")),
604                };
605                match parse_frame(&text) {
606                    Frame::Show(n) => {
607                        presenter.show(&n);
608                        countdowns.start(&presenter, &n);
609                    }
610                    Frame::Retract(tag) => {
611                        countdowns.stop(&tag);
612                        presenter.retract(&tag);
613                    }
614                    Frame::State(state) => crate::tray::notify_menu::set(state),
615                    Frame::StartAtLogin(v) => crate::start_at_login::observe(v),
616                    Frame::Response { reqid, ack } => {
617                        if pending_clicks.remove(&reqid) {
618                            let plan = click_plan(&ack);
619                            crate::logging::log(&format!("notify: click → {plan:?}"));
620                            let window = match &plan {
621                                ClickPlan::Raise(w) => window_for(&*state.lock().await, w),
622                                _ => None,
623                            };
624                            let (dd, dh) = (data_dir.to_path_buf(), dir_hash.to_string());
625                            tokio::task::spawn_blocking(move || carry_out_click(plan, window, &dd, &dh));
626                        }
627                    }
628                    Frame::Other => {}
629                }
630            }
631        }
632    }
633}
634
635/// Raise first, in this process: the toast click made the launcher the
636/// foreground-eligible process, and that right is what a raise needs —
637/// waiting for the pane selection to go srv → renderer → host first can
638/// lose it (rich-content spec §3.3 C, F4). Every branch logs.
639fn carry_out_click(
640    plan: ClickPlan,
641    window: Option<(String, Option<u64>, bool)>,
642    data_dir: &std::path::Path,
643    dir_hash: &str,
644) {
645    use crate::second_instance::{forward_host_cmd_with_args, forward_open_new_window, ForwardError};
646    let log_err = |what: &str, r: Result<(), ForwardError>| {
647        if let Err(ForwardError::Transient(e) | ForwardError::Fatal(e)) = r {
648            crate::logging::log(&format!("notify: {what} for click failed: {e}"));
649        }
650    };
651    match plan {
652        ClickPlan::Raise(window_id) => {
653            let Some((label, hwnd, iconic)) = window else {
654                // The window reported itself to srv but the launcher hasn't
655                // mapped it (yet): let the host raise it by its frontend's own
656                // request instead — the frontend calls focus_window itself.
657                crate::logging::log(&format!("notify: click window {window_id} not in the launcher's mirror"));
658                return;
659            };
660            if hwnd.is_some_and(|h| raise_hwnd(h, iconic)) {
661                return;
662            }
663            crate::logging::log(&format!("notify: raising {label} directly failed; asking the host"));
664            log_err("focus_window", forward_host_cmd_with_args(data_dir, dir_hash, "focus_window", serde_json::json!({ "label": label })));
665            if let Some(h) = hwnd {
666                flash_hwnd(h);
667            }
668        }
669        ClickPlan::OpenWorkspace(workspace_id) => log_err(
670            "open_new_window {workspace_id}",
671            forward_host_cmd_with_args(data_dir, dir_hash, "open_new_window", serde_json::json!({ "workspace_id": workspace_id })),
672        ),
673        ClickPlan::OpenWindow => log_err("open_new_window", forward_open_new_window(data_dir, dir_hash)),
674        ClickPlan::Nothing => {}
675    }
676}
677
678/// Restore if minimized, then bring to the foreground. False when Windows
679/// refused the foreground change.
680#[cfg(target_os = "windows")]
681fn raise_hwnd(hwnd: u64, iconic: bool) -> bool {
682    use windows_sys::Win32::UI::WindowsAndMessaging::{IsIconic, SetForegroundWindow, ShowWindow, SW_RESTORE};
683    let h = hwnd as usize as windows_sys::Win32::Foundation::HWND;
684    unsafe {
685        if iconic || IsIconic(h) != 0 {
686            ShowWindow(h, SW_RESTORE);
687        }
688        SetForegroundWindow(h) != 0
689    }
690}
691
692#[cfg(not(target_os = "windows"))]
693fn raise_hwnd(_hwnd: u64, _iconic: bool) -> bool {
694    false
695}
696
697/// Windows' own fallback when the foreground change is refused: flash the
698/// taskbar button so the user at least sees where to go.
699#[cfg(target_os = "windows")]
700fn flash_hwnd(hwnd: u64) {
701    use windows_sys::Win32::UI::WindowsAndMessaging::{FlashWindowEx, FLASHWINFO, FLASHW_ALL, FLASHW_TIMERNOFG};
702    let info = FLASHWINFO {
703        cbSize: std::mem::size_of::<FLASHWINFO>() as u32,
704        hwnd: hwnd as usize as windows_sys::Win32::Foundation::HWND,
705        dwFlags: FLASHW_ALL | FLASHW_TIMERNOFG,
706        uCount: 3,
707        dwTimeout: 0,
708    };
709    unsafe {
710        FlashWindowEx(&info);
711    }
712}
713
714#[cfg(not(target_os = "windows"))]
715fn flash_hwnd(_hwnd: u64) {}
716
717#[cfg(test)]
718mod tests {
719    use super::*;
720
721    #[test]
722    fn click_plan_follows_srvs_answer() {
723        let ack = |window: Option<&str>, ws: Option<&str>, has: Option<bool>| AckResponse {
724            has_window: has,
725            window_id: window.map(Into::into),
726            workspace_id: ws.map(Into::into),
727        };
728        assert_eq!(click_plan(&ack(Some("w1"), None, Some(true))), ClickPlan::Raise("w1".into()));
729        assert_eq!(click_plan(&ack(None, Some("ws1"), Some(false))), ClickPlan::OpenWorkspace("ws1".into()));
730        assert_eq!(click_plan(&ack(None, None, Some(false))), ClickPlan::OpenWindow);
731        // An older srv: only has_window.
732        assert_eq!(click_plan(&ack(None, None, Some(true))), ClickPlan::Nothing);
733        assert_eq!(click_plan(&ack(Some(""), Some(""), None)), ClickPlan::Nothing);
734    }
735
736    #[test]
737    fn window_for_maps_backend_id_to_label_hwnd_and_minimized() {
738        let mut s = crate::state::State::default();
739        s.backend_window_ids.insert("main".into(), "wid-1".into());
740        assert_eq!(window_for(&s, "wid-1"), Some(("main".into(), None, false)), "label known before its HWND");
741        assert_eq!(window_for(&s, "wid-2"), None);
742    }
743
744    #[test]
745    fn ws_url_forms() {
746        assert_eq!(ws_url("127.0.0.1:5000"), "ws://127.0.0.1:5000/ws");
747        assert_eq!(ws_url("ws://127.0.0.1:5000/"), "ws://127.0.0.1:5000/ws");
748    }
749
750    #[test]
751    fn parses_notification_event() {
752        let f = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification","data":{
753            "id":"n1-1","kind":"input_waiting","priority":"attention","block_id":"b1","agent_name":"lark",
754            "title":"lark needs your input","body":"Which branch?","tag":"abcdef0123456789","created_at_ms":1}}}}"#;
755        match parse_frame(f) {
756            Frame::Show(n) => {
757                assert_eq!(n.id, "n1-1");
758                assert!(n.is_attention());
759                assert_eq!(n.body.as_deref(), Some("Which branch?"));
760                assert_eq!(n.tag, "abcdef0123456789");
761            }
762            other => panic!("unexpected {other:?}"),
763        }
764    }
765
766    #[test]
767    fn parses_retract_and_response_and_ignores_others() {
768        let r = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification:retract","data":{"id":"n1","tag":"t1"}}}}"#;
769        assert_eq!(parse_frame(r), Frame::Retract("t1".into()));
770        let resp = r#"{"eventtype":"rpc","data":{"resid":"q1","data":{"has_window":false}}}"#;
771        assert_eq!(
772            parse_frame(resp),
773            Frame::Response { reqid: "q1".into(), ack: AckResponse { has_window: Some(false), ..Default::default() } }
774        );
775        let resp = r#"{"eventtype":"rpc","data":{"resid":"q2","data":{"has_window":true,"known":true,"window_id":"w1"}}}"#;
776        assert_eq!(
777            parse_frame(resp),
778            Frame::Response {
779                reqid: "q2".into(),
780                ack: AckResponse { has_window: Some(true), window_id: Some("w1".into()), workspace_id: None }
781            }
782        );
783        let st = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification:state","data":{"attention":[{"id":"n1","block_id":"b1","title":"lark needs your input"}],"paused_until_ms":5}}}}"#;
784        match parse_frame(st) {
785            Frame::State(s) => {
786                assert_eq!(s.attention.len(), 1);
787                assert_eq!(s.paused_until_ms, 5);
788            }
789            other => panic!("unexpected {other:?}"),
790        }
791        let cfg = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"config","data":{}}}}"#;
792        assert_eq!(parse_frame(cfg), Frame::Other);
793        let with = |settings: &str| {
794            format!(r#"{{"eventtype":"rpc","data":{{"command":"eventrecv","data":{{"event":"config","data":{{"fullconfig":{{"settings":{settings}}}}}}}}}}}"#)
795        };
796        assert_eq!(parse_frame(&with(r#"{"app:startatlogin":true}"#)), Frame::StartAtLogin(Some(true)));
797        assert_eq!(parse_frame(&with(r#"{"app:startatlogin":false}"#)), Frame::StartAtLogin(Some(false)));
798        assert_eq!(parse_frame(&with(r#"{"term:fontsize":12}"#)), Frame::StartAtLogin(None));
799        assert_eq!(parse_frame(r#"{"type":"ping","stime":1}"#), Frame::Other);
800        assert_eq!(parse_frame("garbage"), Frame::Other);
801    }
802
803    /// End-to-end over a real socket: a fake srv checks the auth header and
804    /// subscriptions, pushes a notification + retract, and receives the ack
805    /// the presenter's click produces.
806    #[tokio::test]
807    async fn session_round_trip_against_fake_srv() {
808        use std::sync::Mutex;
809        use tokio::net::TcpListener;
810        use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
811
812        #[derive(Default)]
813        struct Fake {
814            calls: Mutex<Vec<String>>,
815        }
816        impl Presenter for Fake {
817            fn show(&self, n: &Notification) {
818                self.calls.lock().unwrap().push(format!("show:{}", n.id));
819            }
820            fn retract(&self, tag: &str) {
821                self.calls.lock().unwrap().push(format!("retract:{tag}"));
822            }
823            fn clear_all(&self) {}
824        }
825
826        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
827        let addr = listener.local_addr().unwrap();
828        let (got_tx, mut got_rx) = mpsc::unbounded_channel::<serde_json::Value>();
829        tokio::spawn(async move {
830            let (sock, _) = listener.accept().await.unwrap();
831            let mut ws = tokio_tungstenite::accept_hdr_async(sock, |req: &Request, resp: Response| {
832                assert_eq!(req.uri().path(), "/ws");
833                assert_eq!(req.headers().get("X-AuthKey").unwrap(), "k1");
834                Ok(resp)
835            })
836            .await
837            .unwrap();
838            // Three eventsubs first.
839            for _ in 0..3 {
840                let m = ws.next().await.unwrap().unwrap();
841                got_tx.send(serde_json::from_str(m.to_text().unwrap()).unwrap()).unwrap();
842            }
843            let show = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification","data":{"id":"n1","kind":"turn_completed","priority":"normal","title":"lark finished","body":null,"tag":"t1"}}}}"#;
844            ws.send(Message::Text(show.into())).await.unwrap();
845            let retract = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification:retract","data":{"id":"n1","tag":"t1"}}}}"#;
846            ws.send(Message::Text(retract.into())).await.unwrap();
847            // The ack produced by the simulated click.
848            let m = ws.next().await.unwrap().unwrap();
849            got_tx.send(serde_json::from_str(m.to_text().unwrap()).unwrap()).unwrap();
850        });
851
852        let fake = Arc::new(Fake::default());
853        let presenter: Arc<dyn Presenter> = fake.clone();
854        let (_ep_tx, ep_rx) = watch::channel(Some(Endpoint { ws: addr.to_string(), auth_key: "k1".into(), proof: "p1".into() }));
855        let (act_tx, act_rx) = mpsc::unbounded_channel();
856        let dir = std::env::temp_dir();
857        let state: LauncherState = Default::default();
858        tokio::spawn(run(ep_rx, act_rx, presenter, dir, "h".into(), state));
859
860        let sub1 = got_rx.recv().await.unwrap();
861        let sub2 = got_rx.recv().await.unwrap();
862        let sub3 = got_rx.recv().await.unwrap();
863        assert_eq!(sub3["message"]["data"]["event"], "notification:state");
864        assert_eq!(sub1["message"]["command"], "eventsub");
865        assert_eq!(sub1["message"]["data"]["event"], "notification");
866        assert_eq!(sub2["message"]["data"]["event"], "notification:retract");
867
868        // Wait until show + retract reached the presenter, then click.
869        for _ in 0..100 {
870            if fake.calls.lock().unwrap().len() >= 2 {
871                break;
872            }
873            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
874        }
875        assert_eq!(*fake.calls.lock().unwrap(), vec!["show:n1".to_string(), "retract:t1".to_string()]);
876        act_tx.send(UserAction::Clicked("n1".into())).unwrap();
877        let ack = got_rx.recv().await.unwrap();
878        assert_eq!(ack["message"]["command"], "notify.ack");
879        assert_eq!(ack["message"]["data"]["id"], "n1");
880        assert_eq!(ack["message"]["data"]["clicked"], true);
881        assert!(ack["message"]["reqid"].is_string());
882    }
883
884    #[test]
885    fn rpc_envelope_shape() {
886        let v: serde_json::Value = serde_json::from_str(&rpc("notify.ack", Some("r1"), serde_json::json!({"id":"n1","clicked":true}))).unwrap();
887        assert_eq!(v["wscommand"], "rpc");
888        assert_eq!(v["message"]["command"], "notify.ack");
889        assert_eq!(v["message"]["reqid"], "r1");
890        assert_eq!(v["message"]["data"]["clicked"], true);
891    }
892
893    #[test]
894    fn a_notification_with_buttons_and_a_countdown_parses_and_an_older_srv_still_does() {
895        let f = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification","data":{
896            "id":"n1","kind":"shutdown_pending","priority":"attention","title":"Closing QTimer in 15 s",
897            "body":"AgentY asked to close it.","tag":"t1",
898            "actions":[{"id":"keep","label":"Keep running"}],
899            "countdown":{"remaining_ms":15000,"title_template":"Closing QTimer in {n} s"}}}}}"#;
900        let Frame::Show(n) = parse_frame(f) else { panic!("not a show") };
901        assert_eq!(n.keep_label(), Some("Keep running"));
902        assert_eq!(n.countdown, Some(Countdown { remaining_ms: 15_000, title_template: "Closing QTimer in {n} s".into() }));
903        // Without either field (every other notification, or an older srv).
904        let plain = r#"{"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"notification","data":{
905            "id":"n2","kind":"turn_completed","priority":"normal","title":"lark finished","tag":"t2"}}}}"#;
906        let Frame::Show(p) = parse_frame(plain) else { panic!("not a show") };
907        assert!(p.actions.is_empty() && p.countdown.is_none() && p.keep_label().is_none());
908    }
909
910    #[test]
911    fn the_countdown_counts_whole_seconds_down_and_drains_the_bar() {
912        let t = "Closing QTimer in {n} s";
913        let at = |remaining: i64| countdown_update(t, remaining, 15_000);
914        assert_eq!((at(15_000).title.as_str(), at(15_000).fraction_left, at(15_000).seconds_text.as_str()), ("Closing QTimer in 15 s", 1.0, "15 s"));
915        assert_eq!(at(14_001).title, "Closing QTimer in 15 s", "rounded up, so it never reads 0 with time left");
916        assert_eq!(at(9_000).title, "Closing QTimer in 9 s");
917        assert_eq!(at(1).title, "Closing QTimer in 1 s");
918        let done = at(0);
919        assert_eq!((done.title.as_str(), done.fraction_left, done.seconds_text.as_str()), ("Closing QTimer in 0 s", 0.0, "0 s"));
920        assert_eq!(at(-400).fraction_left, 0.0, "never negative");
921        assert_eq!(countdown_update(t, 5_000, 0).fraction_left, 0.0, "no total, no bar");
922        assert!((at(7_500).fraction_left - 0.5).abs() < 1e-9);
923    }
924
925    /// An agent's name can't take the placeholder's place: the last `{n}` is ours.
926    #[test]
927    fn only_the_last_placeholder_is_filled() {
928        assert_eq!(countdown_update("Closing {n} in {n} s", 3_000, 15_000).title, "Closing {n} in 3 s");
929        assert_eq!(countdown_update("no placeholder", 3_000, 15_000).title, "no placeholder");
930    }
931
932    #[test]
933    fn a_button_press_acks_with_its_action_and_a_click_does_not() {
934        assert_eq!(ack_params("n1", true, None, "p"), serde_json::json!({ "id": "n1", "clicked": true }), "a click carries no proof");
935        assert_eq!(
936            ack_params("n1", false, Some("keep"), "p"),
937            serde_json::json!({ "id": "n1", "clicked": false, "action": "keep", "proof": "p" })
938        );
939        assert_eq!(
940            ack_params("n1", false, Some("now"), "p"),
941            serde_json::json!({ "id": "n1", "clicked": false, "action": "now", "proof": "p" })
942        );
943        assert_eq!(ack_params("n1", false, Some("now"), ""), serde_json::json!({ "id": "n1", "clicked": false, "action": "now" }));
944    }
945
946    /// The ticker redraws a live toast once a second and stops with its retract.
947    #[tokio::test]
948    async fn a_countdown_toast_is_redrawn_each_second_until_retracted() {
949        use std::sync::Mutex;
950        #[derive(Default)]
951        struct Rec(Mutex<Vec<(String, CountdownUpdate)>>);
952        impl Presenter for Rec {
953            fn show(&self, _: &Notification) {}
954            fn retract(&self, _: &str) {}
955            fn clear_all(&self) {}
956            fn update(&self, tag: &str, u: &CountdownUpdate) {
957                self.0.lock().unwrap().push((tag.to_string(), u.clone()));
958            }
959        }
960        let rec = Arc::new(Rec::default());
961        let presenter: Arc<dyn Presenter> = rec.clone();
962        let n = Notification {
963            id: "n1".into(),
964            tag: "t1".into(),
965            countdown: Some(Countdown { remaining_ms: 2_200, title_template: "Closing QTimer in {n} s".into() }),
966            ..Default::default()
967        };
968        let mut countdowns = Countdowns::default();
969        countdowns.start(&presenter, &n);
970        // Real time: a redraw at 1 s and 2 s, and the third only at 3 s. Loose on
971        // the count so a loaded machine can't fail it, strict on what matters.
972        tokio::time::sleep(std::time::Duration::from_millis(2_500)).await;
973        let seen = rec.0.lock().unwrap().clone();
974        assert!((1..=2).contains(&seen.len()), "about one redraw a second, none at the show itself: {seen:?}");
975        assert!(seen.iter().all(|(tag, _)| tag == "t1"));
976        assert_eq!(seen[0].1.title, "Closing QTimer in 2 s", "1.2 s left rounds up to 2");
977        countdowns.stop("t1");
978        let after_stop = rec.0.lock().unwrap().len();
979        tokio::time::sleep(std::time::Duration::from_millis(1_500)).await;
980        assert_eq!(rec.0.lock().unwrap().len(), after_stop, "nothing after the retract");
981        // A notification with no countdown starts no ticker.
982        countdowns.start(&presenter, &Notification { tag: "t2".into(), ..Default::default() });
983        assert!(countdowns.tasks.is_empty());
984    }
985}