Skip to main content

agentmux_srv_core/backend/notify/
policy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pure notification policy — `SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24.md` §5.
5//!
6//! `PolicyState::step(input, now_ms, &settings) -> Vec<Action>` is the whole
7//! decision surface: no clocks, no I/O, no broker. `router.rs` owns the side
8//! effects (publishing, the tick task). Keeping it pure is what makes the
9//! debounce / dedupe / focus-gate / retract rules table-testable.
10//!
11//! Phase 1: kinds `InputWaiting` / `TurnCompleted` / `TurnErrored` / `Test`,
12//! per-kind enable, debounce, dedupe-by-group, focus gate, retract.
13//! Phase 2: `AgentCrashed` / `MessageNeedsReview` / `Summary`, pause, rate
14//! limits folding into a summary, and a tray state snapshot (§4.2, §5.1).
15
16use std::collections::HashMap;
17
18/// Closed set of notification kinds. A source cannot invent a new visual
19/// treatment — every kind has an app-controlled title template (§9.1).
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, ts_rs::TS)]
21#[serde(rename_all = "snake_case")]
22#[ts(export, export_to = "../../../frontend/types/rpc/")]
23pub enum NotifyKind {
24    InputWaiting,
25    TurnCompleted,
26    TurnErrored,
27    /// srv-observed `agentfailure` (not a user stop).
28    AgentCrashed,
29    /// A jekt that requires a human's review before the agent acts
30    /// (`ESCALATE=required`). Body is fixed text — never message content.
31    MessageNeedsReview,
32    /// Something other than the user asked to shut the agent down; the user
33    /// has 30 s to keep it (SPEC_AGENT_SELF_QUIT_2026_09_24.md §6.5).
34    ShutdownPending,
35    /// Rate-limit overflow digest (§5.1 step 6).
36    Summary,
37    Test,
38    /// This channel's MuxBus sign-in stopped working, so agents stopped
39    /// getting cloud messages (`muxbus::delivery_status`). About no agent;
40    /// once per episode.
41    CloudSignedOut,
42    /// Agents on one account are out of quota (a weekly or unknown limit, not
43    /// a session limit) or need a sign-in: one per account episode
44    /// (`server::account_episodes`). About no agent; its key is the
45    /// account's (`account:<hash>`), never the account itself.
46    AccountUnavailable,
47    /// A job failed: one per incident, not per run (`jobs::incidents`,
48    /// SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3.4). Its key is the job's
49    /// (`job:<id>`); the job's name stands where an agent's would.
50    JobFailed,
51    /// A Vault entry's expiry date is near or here: 14 days, 3 days and on the
52    /// day, once each (`vault::expiry`, SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md
53    /// §15.2). Its key is the entry's (`vault:<id>`); the entry's label stands
54    /// where an agent's name would.
55    VaultExpiring,
56    /// A drone's Notify block told the operator something (`drone::executor::blocks::notify`,
57    /// SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md §4.2). Its key is `drone:<id>`, one per notification;
58    /// the block's own title stands where an agent's name would. Follows the master switch,
59    /// quiet hours and pause only: it has no per-kind setting yet.
60    DroneNote,
61}
62
63impl NotifyKind {
64    /// `notify:os:<suffix>` per-kind enable key (§8).
65    pub fn setting_suffix(self) -> Option<&'static str> {
66        match self {
67            NotifyKind::InputWaiting => Some("inputwaiting"),
68            NotifyKind::TurnCompleted => Some("turncompleted"),
69            NotifyKind::TurnErrored => Some("turnerrored"),
70            NotifyKind::AgentCrashed => Some("agentcrashed"),
71            NotifyKind::MessageNeedsReview => Some("messageneedsreview"),
72            NotifyKind::CloudSignedOut => Some("cloudsignedout"),
73            NotifyKind::AccountUnavailable => Some("accountunavailable"),
74            NotifyKind::JobFailed => Some("jobfailed"),
75            NotifyKind::VaultExpiring => Some("vaultexpiring"),
76            NotifyKind::DroneNote => None,
77            // Follows the master switch only: a shutdown the user can still
78            // stop must not be silenceable per kind.
79            NotifyKind::ShutdownPending => None,
80            NotifyKind::Summary | NotifyKind::Test => None,
81        }
82    }
83
84    /// Debounce before a notification may be shown (§5.1 step 5). Lets the
85    /// user's own imminent action (answering, starting the next turn) cancel
86    /// it before it ever interrupts them.
87    pub fn delay_ms(self) -> i64 {
88        match self {
89            NotifyKind::InputWaiting => 6_000,
90            // Same window as TurnErrored so the two coalesce into one toast.
91            NotifyKind::TurnCompleted | NotifyKind::TurnErrored | NotifyKind::AgentCrashed => 10_000,
92            NotifyKind::MessageNeedsReview => 2_000,
93            // The window is short: tell the user at once.
94            // The episode's scan already waited for the failure to settle.
95            NotifyKind::ShutdownPending | NotifyKind::CloudSignedOut | NotifyKind::AccountUnavailable | NotifyKind::JobFailed | NotifyKind::VaultExpiring | NotifyKind::DroneNote => 0,
96            NotifyKind::Summary | NotifyKind::Test => 0,
97        }
98    }
99
100    pub fn priority(self) -> Priority {
101        match self {
102            NotifyKind::InputWaiting
103            | NotifyKind::AgentCrashed
104            | NotifyKind::MessageNeedsReview
105            | NotifyKind::ShutdownPending
106            | NotifyKind::CloudSignedOut
107            | NotifyKind::AccountUnavailable
108            | NotifyKind::JobFailed
109            // Recorded as sent when it is emitted, so it must not be gated out.
110            | NotifyKind::VaultExpiring => Priority::Attention,
111            _ => Priority::Normal,
112        }
113    }
114
115    /// Coalescing key: at most one live notification per (block, family).
116    pub fn group_key(self, block_id: &str) -> String {
117        match self {
118            NotifyKind::InputWaiting => format!("input:{block_id}"),
119            // AgentCrashed shares the turn group: one failure, one toast.
120            NotifyKind::TurnCompleted | NotifyKind::TurnErrored | NotifyKind::AgentCrashed => {
121                format!("turn:{block_id}")
122            }
123            NotifyKind::MessageNeedsReview => format!("review:{block_id}"),
124            NotifyKind::ShutdownPending => format!("shutdown:{block_id}"),
125            NotifyKind::Summary => "summary".to_string(),
126            NotifyKind::Test => "test".to_string(),
127            NotifyKind::CloudSignedOut => "cloud".to_string(),
128            // One per account, or per job: the key already names it.
129            NotifyKind::AccountUnavailable | NotifyKind::JobFailed | NotifyKind::VaultExpiring | NotifyKind::DroneNote => block_id.to_string(),
130        }
131    }
132
133    /// Kinds about one agent carry its summary line; the digest and the test
134    /// toast are about no agent.
135    fn has_summary(self) -> bool {
136        !matches!(
137            self,
138            NotifyKind::Summary
139                | NotifyKind::Test
140                | NotifyKind::CloudSignedOut
141                | NotifyKind::AccountUnavailable
142                | NotifyKind::JobFailed
143                | NotifyKind::VaultExpiring
144                | NotifyKind::DroneNote
145        )
146    }
147
148    /// Within one group, a later event must not replace a more informative
149    /// earlier one: srv's `AgentCrashed` (with a reason) outranks the
150    /// renderer's generic `TurnErrored`, which often arrives just after it.
151    fn rank(self) -> u8 {
152        match self {
153            NotifyKind::AgentCrashed => 2,
154            _ => 1,
155        }
156    }
157}
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
160#[serde(rename_all = "snake_case")]
161#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "NotifyPriority")]
162pub enum Priority {
163    Attention,
164    Normal,
165}
166
167/// `notify:os:when` (§6.0).
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub enum When {
170    Unfocused,
171    Always,
172    Never,
173}
174
175/// `notify:os:preview` (§9.2).
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub enum Preview {
178    Full,
179    Redacted,
180    None,
181}
182
183/// Resolved settings snapshot the policy reads. Built by the router from
184/// `settings.json` on every step (cheap; the config watcher holds it in memory).
185#[derive(Clone, Debug)]
186pub struct Settings {
187    pub enabled: bool,
188    pub when: When,
189    pub preview: Preview,
190    pub kind_enabled: HashMap<NotifyKind, bool>,
191    /// `notify:pause:until` — epoch ms; toasts are held back until then.
192    pub pause_until_ms: i64,
193    /// `notify:pause:allowattention` — let Attention through while paused.
194    pub pause_allow_attention: bool,
195    /// End of the quiet-hours window we're currently inside (epoch ms), or 0.
196    /// Behaves like a pause, but is NOT shown as one in the tray (it isn't
197    /// something "Resume" can undo — it's a schedule).
198    pub quiet_until_ms: i64,
199    /// `notify:os:summary` — show what the agent is on (its status line or held task) as a line.
200    pub show_summary: bool,
201    /// `notify:os:turncompleted:external` — also notify when a turn something
202    /// other than the user started finishes (a jekt, a service notice, a
203    /// schedule, a background task). Off: such a turn ends quietly unless it
204    /// needs the user (a question, a failure), which notifies as always.
205    pub external_turns: bool,
206}
207
208impl Default for Settings {
209    fn default() -> Self {
210        Settings {
211            enabled: true,
212            when: When::Unfocused,
213            preview: Preview::Redacted,
214            kind_enabled: HashMap::new(),
215            pause_until_ms: 0,
216            pause_allow_attention: false,
217            quiet_until_ms: 0,
218            show_summary: true,
219            external_turns: false,
220        }
221    }
222}
223
224/// Rate limits (§5.1 step 6). Attention is exempt from the per-block limit
225/// (an agent that finished and then immediately asks something must still
226/// reach you) but not from the global one.
227pub const PER_BLOCK_WINDOW_MS: i64 = 30_000;
228pub const GLOBAL_WINDOW_MS: i64 = 60_000;
229pub const GLOBAL_MAX: usize = 4;
230
231impl Settings {
232    fn kind_on(&self, kind: NotifyKind) -> bool {
233        *self.kind_enabled.get(&kind).unwrap_or(&true)
234    }
235
236    /// The summary line is decoration: off with its own setting, and with
237    /// preview=none like the body (rich-content spec §1.2).
238    fn summary_on(&self) -> bool {
239        self.show_summary && self.preview != Preview::None
240    }
241}
242
243/// What one frontend window last reported about focus.
244#[derive(Clone, Debug, Default, PartialEq, Eq)]
245pub struct FocusReport {
246    pub window_focused: bool,
247    pub block_id: Option<String>,
248    /// The reporting window's own `Window` oid (rich-content spec §3.3 A):
249    /// what makes "is that window open" answerable. `None` from an older
250    /// frontend.
251    pub window_id: Option<String>,
252}
253
254/// A request from a source. `agent_name` / `body` are already resolved and
255/// sanitized by the router — the policy never sees untrusted free text it
256/// would render as a title.
257#[derive(Clone, Debug, PartialEq, Eq)]
258pub struct Request {
259    pub kind: NotifyKind,
260    pub block_id: String,
261    pub agent_name: String,
262    pub body: Option<String>,
263    /// What the agent is on: its own fresh status line, else its held task's number and title,
264    /// sanitized (`toast_line`). Never the ambient title.
265    pub summary: Option<String>,
266    /// For `ShutdownPending`: when the window ends and what happens then.
267    pub shutdown: Option<ShutdownInfo>,
268}
269
270/// What a pending shutdown's notification needs beyond the agent's name: it
271/// says what will happen, counts down, and offers Keep running
272/// (docs/specs/SPEC_STOP_AN_AGENT_ONE_WAY_AND_SHUTDOWN_TOAST_2026_10_23.md §3.8).
273#[derive(Clone, Debug, PartialEq, Eq)]
274pub struct ShutdownInfo {
275    /// Epoch ms the user's window ends.
276    pub deadline_ms: i64,
277    /// `PendingView::effect`: `stop`, `close_tab` or `close_pane`.
278    pub effect: &'static str,
279    /// The agent's session is running (the button says "Keep running"), not
280    /// already stopped ("Keep open").
281    pub running: bool,
282    /// The request this notification is about. Kept with the live notification
283    /// so its Keep running button can only cancel this request, never a later
284    /// one for the same block (#5397).
285    pub request_id: String,
286    /// The two buttons' words when the countdown has its own (a sensitive operation); absent, the agent close's.
287    pub labels: Option<(String, String)>,
288}
289
290#[derive(Clone, Debug)]
291pub enum Input {
292    /// A source says something notification-worthy happened.
293    Emit(Request),
294    /// The condition behind a family cleared for a block (question answered,
295    /// new turn started) — cancel pending, retract shown.
296    Resolve { block_id: String, family: Family },
297    /// A frontend window's focus changed.
298    Focus { conn_id: String, report: FocusReport },
299    /// A frontend window went away.
300    Disconnect { conn_id: String },
301    /// The user acted on a notification (clicked it / dismissed it).
302    Ack { id: String, clicked: bool },
303    /// Time passed; release any debounced notification that is now due.
304    Tick,
305}
306
307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub enum Family {
309    Input,
310    Turn,
311    /// A pending external shutdown was kept or went ahead (§6.5).
312    Shutdown,
313    /// This channel's MuxBus sign-in works again, or the user signed out.
314    Cloud,
315    /// An account episode ended (`server::account_episodes`).
316    Account,
317    /// A failing job recovered (`jobs::incidents`).
318    Job,
319}
320
321impl Family {
322    fn matches(self, kind: NotifyKind) -> bool {
323        match self {
324            Family::Input => kind == NotifyKind::InputWaiting,
325            Family::Turn => {
326                matches!(kind, NotifyKind::TurnCompleted | NotifyKind::TurnErrored | NotifyKind::AgentCrashed)
327            }
328            Family::Shutdown => kind == NotifyKind::ShutdownPending,
329            Family::Cloud => kind == NotifyKind::CloudSignedOut,
330            Family::Account => kind == NotifyKind::AccountUnavailable,
331            Family::Job => matches!(kind, NotifyKind::JobFailed | NotifyKind::DroneNote),
332        }
333    }
334}
335
336/// One shown Attention item, for the tray's "needs you" submenu. Titles are
337/// app-controlled templates, so they are safe to show in a native menu.
338#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
339#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "NotifyAttentionItem")]
340pub struct AttentionItem {
341    pub id: String,
342    pub block_id: String,
343    pub title: String,
344    /// Lets surfaces treat kinds differently — e.g. only `InputWaiting`
345    /// flashes the taskbar (spec Phase 4).
346    pub kind: NotifyKind,
347}
348
349/// Snapshot the tray renders (§4.2).
350#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
351#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "NotifyTrayState")]
352pub struct TrayState {
353    pub attention: Vec<AttentionItem>,
354    #[ts(type = "number")]
355    pub paused_until_ms: i64,
356}
357
358/// A button on a toast. `id` is one of a closed set (`keep`); `label` is one of
359/// two app strings.
360#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
361#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "NotifyAction")]
362pub struct NotifyAction {
363    pub id: String,
364    pub label: String,
365}
366
367/// What a presenter needs to tick a toast's countdown without asking srv again:
368/// time left now (relative, so clock skew never matters) and the title with
369/// `{n}` where the whole seconds go.
370#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
371#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "NotifyCountdown")]
372pub struct Countdown {
373    #[ts(type = "number")]
374    pub remaining_ms: i64,
375    pub title_template: String,
376}
377
378/// The payload Presenters render. Every string here is app-controlled or
379/// router-sanitized. Exported to TS as `OsNotification` so it can't shadow the
380/// DOM's global `Notification`.
381#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
382#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "OsNotification")]
383pub struct Notification {
384    pub id: String,
385    pub kind: NotifyKind,
386    pub priority: Priority,
387    pub block_id: String,
388    pub agent_name: String,
389    pub title: String,
390    pub body: Option<String>,
391    /// What the agent is working on — a small third line under the body
392    /// (rich-content spec §1). Absent when the agent has none.
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    #[ts(optional)]
395    pub summary: Option<String>,
396    /// Buttons the toast offers. App-controlled ids and labels, never text
397    /// from an agent. Absent for every kind but a pending shutdown.
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    #[ts(optional)]
400    pub actions: Option<Vec<NotifyAction>>,
401    /// A live countdown the presenter ticks, where the OS can show one.
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    #[ts(optional)]
404    pub countdown: Option<Countdown>,
405    /// Stable per group: OS toast replace/remove key (≤16 chars, Win10-safe).
406    pub tag: String,
407    #[ts(type = "number")]
408    pub created_at_ms: i64,
409}
410
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub enum Action {
413    Show(Notification),
414    Retract { id: String, tag: String },
415    Activate { id: String, block_id: String },
416}
417
418#[derive(Clone, Debug)]
419struct Live {
420    notification: Notification,
421    /// For a pending shutdown: the request it belongs to (`ShutdownInfo`), and
422    /// how much its effect does (`effect_rank`), so a stale emission can't
423    /// replace a stronger one.
424    request_id: Option<String>,
425    effect_rank: u8,
426    due_at_ms: i64,
427    shown: bool,
428    /// Replaces a toast of the same group that was already on screen — it
429    /// swaps one toast for another rather than adding one, so the per-block
430    /// limit doesn't apply.
431    replaces_shown: bool,
432}
433
434#[derive(Default)]
435pub struct PolicyState {
436    /// group_key → the one live (pending or shown) notification for it.
437    live: HashMap<String, Live>,
438    focus: HashMap<String, FocusReport>,
439    /// The connection whose window most recently reported being focused —
440    /// where a click with no pane of its own raises (§3.3 F).
441    last_focused_conn: Option<String>,
442    next_seq: u64,
443    /// block_id → last time a toast for it was shown (per-block limit).
444    last_shown: HashMap<String, i64>,
445    /// Show times inside the global window.
446    recent: std::collections::VecDeque<i64>,
447    /// Notifications folded into the current summary.
448    summarized: u32,
449}
450
451/// Title from a closed template set (§9.1). Only the agent name is
452/// interpolated, and it arrives pre-sanitized.
453pub fn title_for(kind: NotifyKind, agent_name: &str) -> String {
454    match kind {
455        NotifyKind::InputWaiting => format!("{agent_name} has a question"),
456        NotifyKind::TurnCompleted => format!("{agent_name} finished"),
457        NotifyKind::TurnErrored => format!("{agent_name} stopped with an error"),
458        NotifyKind::AgentCrashed => format!("{agent_name} stopped unexpectedly"),
459        NotifyKind::MessageNeedsReview => format!("A message for {agent_name} needs your review"),
460        NotifyKind::ShutdownPending => format!("{agent_name} will shut down soon"),
461        // Count-bearing; see `summary_title`.
462        NotifyKind::Summary => "More agent updates".to_string(),
463        NotifyKind::Test => "AgentMux notifications are working".to_string(),
464        NotifyKind::CloudSignedOut => "AgentMux is signed out of MuxBus".to_string(),
465        NotifyKind::AccountUnavailable => "An account can't run your agents".to_string(),
466        NotifyKind::JobFailed => format!("Job failed: {agent_name}"),
467        NotifyKind::VaultExpiring => format!("Expiring in the Vault: {agent_name}"),
468        NotifyKind::DroneNote => agent_name.to_string(),
469    }
470}
471
472/// `ShutdownInfo::effect` of a sensitive operation's countdown
473/// (`SPEC_SUPER_AGENT_2026_10_25.md` §5): it shares the shutdown toast, with its own two words.
474pub const SENSITIVE_EFFECT: &str = "sensitive";
475
476/// A pending shutdown's title with `{n}` for the seconds left
477/// (spec §3.8): "Closing QTimer in {n} s". The name arrives pre-sanitized.
478pub fn shutdown_title_template(effect: &str, agent_name: &str) -> String {
479    // A sensitive operation counting down: `agent_name` is what will happen ("Upgrade AgentMux").
480    if effect == SENSITIVE_EFFECT {
481        return format!("{agent_name} in {{n}} s");
482    }
483    let verb = if effect == "stop" { "Stopping" } else { "Closing" };
484    format!("{verb} {agent_name} in {{n}} s")
485}
486
487/// How much a shutdown's effect does, to order emissions for one request.
488fn effect_rank(effect: &str) -> u8 {
489    match effect {
490        "close_pane" => 2,
491        "close_tab" => 1,
492        _ => 0,
493    }
494}
495
496/// `template` with its last `{n}` replaced by the seconds: the one that is ours.
497/// An agent's name earlier in it may hold `{n}` too; the launcher fills the
498/// same one (`fill_countdown`), so the first frame and the ticked ones agree.
499pub fn fill_seconds(template: &str, secs: i64) -> String {
500    match template.rfind("{n}") {
501        Some(i) => format!("{}{}{}", &template[..i], secs, &template[i + 3..]),
502        None => template.to_string(),
503    }
504}
505
506/// Whole seconds left, rounded up, never negative.
507pub fn seconds_left(remaining_ms: i64) -> i64 {
508    (remaining_ms.max(0) + 999) / 1000
509}
510
511/// The two button labels (spec §3.1): "Keep running" for an agent whose
512/// session is running, "Keep open" for one that is already stopped.
513pub fn keep_label(running: bool) -> &'static str {
514    if running { "Keep running" } else { "Keep open" }
515}
516
517pub fn summary_title(count: u32) -> String {
518    if count == 1 {
519        "1 more agent update".to_string()
520    } else {
521        format!("{count} more agent updates")
522    }
523}
524
525/// 16 hex chars of FNV-1a over the group key — stable across restarts,
526/// short enough for every Windows toast Tag limit.
527pub fn tag_for(group_key: &str) -> String {
528    let mut h: u64 = 0xcbf29ce484222325;
529    for b in group_key.as_bytes() {
530        h ^= *b as u64;
531        h = h.wrapping_mul(0x100000001b3);
532    }
533    format!("{h:016x}")
534}
535
536impl PolicyState {
537    pub fn new() -> Self {
538        Self::default()
539    }
540
541    /// Any window focused at all?
542    pub(crate) fn app_focused(&self) -> bool {
543        self.focus.values().any(|f| f.window_focused)
544    }
545
546    /// Is the user looking at exactly this block right now?
547    fn looking_at(&self, block_id: &str) -> bool {
548        self.focus
549            .values()
550            .any(|f| f.window_focused && f.block_id.as_deref() == Some(block_id))
551    }
552
553    /// Whether any frontend window is connected (for click-with-no-window).
554    pub fn has_window(&self) -> bool {
555        !self.focus.is_empty()
556    }
557
558    /// Whether a connected frontend reports being window `window_id`.
559    pub fn window_open(&self, window_id: &str) -> bool {
560        self.focus.values().any(|f| f.window_id.as_deref() == Some(window_id))
561    }
562
563    /// The window a click should raise when it names none of its own: the
564    /// most recently focused one, else any connected window with an id.
565    pub fn raise_window(&self) -> Option<String> {
566        self.last_focused_conn
567            .as_ref()
568            .and_then(|c| self.focus.get(c))
569            .and_then(|f| f.window_id.clone())
570            .or_else(|| {
571                let mut ids: Vec<&String> = self.focus.values().filter_map(|f| f.window_id.as_ref()).collect();
572                ids.sort();
573                ids.first().map(|s| (*s).clone())
574            })
575    }
576
577    /// §6.0 gate, evaluated at the moment a notification becomes due.
578    fn should_show(&self, n: &Notification, s: &Settings) -> bool {
579        if n.kind == NotifyKind::Test {
580            return true;
581        }
582        if self.looking_at(&n.block_id) {
583            return false;
584        }
585        match s.when {
586            When::Never => false,
587            When::Always => true,
588            // Unfocused: OS toast only when the app isn't foreground — except
589            // Attention, which still reaches a user looking at another pane.
590            When::Unfocused => !self.app_focused() || n.priority == Priority::Attention,
591        }
592    }
593
594    pub fn step(&mut self, input: Input, now_ms: i64, s: &Settings) -> Vec<Action> {
595        let mut out = Vec::new();
596        match input {
597            Input::Emit(req) => {
598                let is_test = req.kind == NotifyKind::Test;
599                if !is_test && (!s.enabled || !s.kind_on(req.kind)) {
600                    return out;
601                }
602                let group = req.kind.group_key(&req.block_id);
603                let effect_rank = req.shutdown.as_ref().map_or(0, |i| effect_rank(i.effect));
604                if let Some(existing) = self.live.get_mut(&group) {
605                    if existing.notification.kind.rank() > req.kind.rank() {
606                        return out;
607                    }
608                    // Emissions for one request are made on separate threads and
609                    // can arrive out of order: an older, weaker one (still saying
610                    // "Stopping" after the request became a close) must not
611                    // replace the newer (#5397).
612                    if let (Some(have), Some(info)) = (&existing.request_id, &req.shutdown) {
613                        if *have == info.request_id && existing.effect_rank > effect_rank {
614                            return out;
615                        }
616                    }
617                    // The same question reported again — srv detected it, then
618                    // the renderer mounts the pane and reports it too (the one
619                    // kind with two reporters). Idempotent: no retract, no
620                    // re-debounce; only fill a body or summary we didn't have.
621                    // Other kinds are distinct events (a second crash is news)
622                    // and replace as before (Codex P2s on #3662).
623                    if existing.notification.kind == req.kind && req.kind == NotifyKind::InputWaiting {
624                        if existing.notification.body.is_none() && s.preview != Preview::None {
625                            existing.notification.body = req.body;
626                        }
627                        if existing.notification.summary.is_none() && s.summary_on() {
628                            existing.notification.summary = req.summary;
629                        }
630                        return out;
631                    }
632                }
633                let tag = tag_for(&group);
634                // Replace in place: a newer event in the same family supersedes
635                // the older one (e.g. completed → errored), same OS tag.
636                let replaced_shown = self.live.get(&group).map(|l| l.shown).unwrap_or(false);
637                self.next_seq += 1;
638                let id = format!("n{}-{}", now_ms, self.next_seq);
639                let (title, actions, countdown) = match (req.kind, &req.shutdown) {
640                    (NotifyKind::ShutdownPending, Some(info)) => {
641                        let remaining_ms = (info.deadline_ms - now_ms).max(0);
642                        let template = shutdown_title_template(info.effect, &req.agent_name);
643                        (
644                            fill_seconds(&template, seconds_left(remaining_ms)),
645                            // Cancel and do-it-now. A press that skips or stops the wait is proven
646                            // in `notify.ack`, not here: any client holding the key can send one.
647                            Some(super::shutdown_buttons::actions(info)),
648                            Some(Countdown { remaining_ms, title_template: template }),
649                        )
650                    }
651                    _ => (title_for(req.kind, &req.agent_name), None, None),
652                };
653                let notification = Notification {
654                    id,
655                    kind: req.kind,
656                    priority: req.kind.priority(),
657                    block_id: req.block_id,
658                    title,
659                    actions,
660                    countdown,
661                    agent_name: req.agent_name,
662                    body: match s.preview {
663                        Preview::None => None,
664                        _ => req.body,
665                    },
666                    summary: if s.summary_on() && req.kind.has_summary() { req.summary } else { None },
667                    tag,
668                    created_at_ms: now_ms,
669                };
670                // If the old one was on screen and the new one is still
671                // debouncing, pull the stale one now rather than leaving it up.
672                if replaced_shown && req.kind.delay_ms() > 0 {
673                    if let Some(old) = self.live.get(&group) {
674                        out.push(Action::Retract { id: old.notification.id.clone(), tag: old.notification.tag.clone() });
675                    }
676                }
677                self.live.insert(
678                    group,
679                    Live {
680                        notification,
681                        request_id: req.shutdown.as_ref().map(|i| i.request_id.clone()),
682                        effect_rank,
683                        due_at_ms: now_ms + req.kind.delay_ms(),
684                        shown: false,
685                        replaces_shown: replaced_shown,
686                    },
687                );
688                if is_test {
689                    out.extend(self.release_due(now_ms, s));
690                }
691            }
692            Input::Resolve { block_id, family } => {
693                self.drop_where(&mut out, |n| n.block_id == block_id && family.matches(n.kind));
694            }
695            Input::Focus { conn_id, report } => {
696                let looking = report.window_focused.then(|| report.block_id.clone()).flatten();
697                let app_focused = report.window_focused;
698                if app_focused {
699                    self.last_focused_conn = Some(conn_id.clone());
700                }
701                self.focus.insert(conn_id, report);
702                // Back in the app: the digest of what you missed is moot.
703                if app_focused {
704                    self.summarized = 0;
705                    self.drop_where(&mut out, |n| n.kind == NotifyKind::Summary);
706                }
707                // The user just looked at the block: its notifications are moot.
708                if let Some(b) = looking {
709                    self.drop_where(&mut out, |n| n.block_id == b && n.kind != NotifyKind::Test);
710                }
711            }
712            Input::Disconnect { conn_id } => {
713                self.focus.remove(&conn_id);
714                if self.last_focused_conn.as_deref() == Some(conn_id.as_str()) {
715                    self.last_focused_conn = None;
716                }
717            }
718            Input::Ack { id, clicked } => {
719                let group = self
720                    .live
721                    .iter()
722                    .find(|(_, l)| l.notification.id == id)
723                    .map(|(g, _)| g.clone());
724                if let Some(g) = group {
725                    let l = self.live.remove(&g).expect("present");
726                    if l.notification.kind == NotifyKind::Summary {
727                        self.summarized = 0;
728                    }
729                    out.push(Action::Retract { id: l.notification.id.clone(), tag: l.notification.tag.clone() });
730                    if clicked && !l.notification.block_id.is_empty() {
731                        out.push(Action::Activate { id: l.notification.id, block_id: l.notification.block_id });
732                    }
733                }
734            }
735            Input::Tick => out.extend(self.release_due(now_ms, s)),
736        }
737        out
738    }
739
740    fn release_due(&mut self, now_ms: i64, s: &Settings) -> Vec<Action> {
741        let mut out = Vec::new();
742        while self.recent.front().is_some_and(|t| now_ms - *t >= GLOBAL_WINDOW_MS) {
743            self.recent.pop_front();
744        }
745        let mut due: Vec<String> = self
746            .live
747            .iter()
748            .filter(|(_, l)| !l.shown && l.due_at_ms <= now_ms)
749            .map(|(g, _)| g.clone())
750            .collect();
751        // Deterministic order: oldest first, so the limits keep the earliest.
752        due.sort_by_key(|g| (self.live[g].notification.created_at_ms, g.clone()));
753        let mut folded = 0u32;
754        for g in due {
755            let n = self.live[&g].notification.clone();
756            if !self.should_show(&n, s) || self.paused(&n, now_ms, s) {
757                // Gated out at due time → gone for good. Not re-offered later:
758                // a "finished" toast an hour after the user already saw the
759                // pane would be noise.
760                self.live.remove(&g);
761                continue;
762            }
763            if self.rate_limited(&n, now_ms, self.live[&g].replaces_shown) {
764                self.live.remove(&g);
765                folded += 1;
766                continue;
767            }
768            let l = self.live.get_mut(&g).expect("present");
769            l.shown = true;
770            if n.kind != NotifyKind::Test && n.kind != NotifyKind::Summary {
771                self.last_shown.insert(n.block_id.clone(), now_ms);
772                self.recent.push_back(now_ms);
773            }
774            out.push(Action::Show(n));
775        }
776        if folded > 0 {
777            self.summarized += folded;
778            out.extend(self.show_summary(now_ms));
779        }
780        out
781    }
782
783    /// A pending shutdown is never paused or rate-limited: it is the only
784    /// warning that an agent stops in 30 s, so holding it back lets the agent
785    /// stop unannounced. Only the master switch silences it.
786    fn paused(&self, n: &Notification, now_ms: i64, s: &Settings) -> bool {
787        !matches!(n.kind, NotifyKind::Test | NotifyKind::ShutdownPending)
788            && now_ms < s.pause_until_ms.max(s.quiet_until_ms)
789            && !(s.pause_allow_attention && n.priority == Priority::Attention)
790    }
791
792    fn rate_limited(&self, n: &Notification, now_ms: i64, replaces_shown: bool) -> bool {
793        // A Vault reminder is recorded as sent when emitted, and folding it into the
794        // summary would lose it; `vault::expiry` sends at most a few per look.
795        if matches!(n.kind, NotifyKind::Test | NotifyKind::Summary | NotifyKind::ShutdownPending | NotifyKind::VaultExpiring) {
796            return false;
797        }
798        if self.recent.len() >= GLOBAL_MAX {
799            return true;
800        }
801        n.priority != Priority::Attention
802            && !replaces_shown
803            && self.last_shown.get(&n.block_id).is_some_and(|t| now_ms - *t < PER_BLOCK_WINDOW_MS)
804    }
805
806    /// Show (or replace in place) the one summary toast.
807    fn show_summary(&mut self, now_ms: i64) -> Vec<Action> {
808        let group = NotifyKind::Summary.group_key("");
809        self.next_seq += 1;
810        let n = Notification {
811            id: format!("n{}-{}", now_ms, self.next_seq),
812            kind: NotifyKind::Summary,
813            priority: Priority::Normal,
814            block_id: String::new(),
815            agent_name: String::new(),
816            title: summary_title(self.summarized),
817            body: Some("Open AgentMux to catch up.".to_string()),
818            summary: None,
819            actions: None,
820            countdown: None,
821            tag: tag_for(&group),
822            created_at_ms: now_ms,
823        };
824        self.live.insert(group, Live { notification: n.clone(), request_id: None, effect_rank: 0, due_at_ms: now_ms, shown: true, replaces_shown: false });
825        vec![Action::Show(n)]
826    }
827
828    /// What the tray shows: every on-screen Attention notification, oldest
829    /// first, plus the pause deadline.
830    pub fn tray_state(&self, s: &Settings, now_ms: i64) -> TrayState {
831        let mut attention: Vec<&Notification> = self
832            .live
833            .values()
834            .filter(|l| l.shown && l.notification.priority == Priority::Attention)
835            .map(|l| &l.notification)
836            .collect();
837        attention.sort_by_key(|n| (n.created_at_ms, n.id.clone()));
838        TrayState {
839            attention: attention
840                .into_iter()
841                .map(|n| AttentionItem { id: n.id.clone(), block_id: n.block_id.clone(), title: n.title.clone(), kind: n.kind })
842                .collect(),
843            paused_until_ms: if s.pause_until_ms > now_ms { s.pause_until_ms } else { 0 },
844        }
845    }
846
847    fn drop_where(&mut self, out: &mut Vec<Action>, pred: impl Fn(&Notification) -> bool) {
848        let groups: Vec<String> =
849            self.live.iter().filter(|(_, l)| pred(&l.notification)).map(|(g, _)| g.clone()).collect();
850        for g in groups {
851            let l = self.live.remove(&g).expect("present");
852            if l.shown {
853                out.push(Action::Retract { id: l.notification.id, tag: l.notification.tag });
854            }
855        }
856    }
857
858    /// The kind, block and (for a shutdown) request of the live notification
859    /// with this id: what a button press on it is about. Looked up here, never
860    /// read from the press.
861    pub fn live_by_id(&self, id: &str) -> Option<(NotifyKind, String, Option<String>)> {
862        self.live
863            .values()
864            .find(|l| l.notification.id == id)
865            .map(|l| (l.notification.kind, l.notification.block_id.clone(), l.request_id.clone()))
866    }
867
868    /// Number of live (pending or shown) notifications — for tests/diagnostics.
869    #[cfg(test)]
870    pub fn live_len(&self) -> usize {
871        self.live.len()
872    }
873}
874
875#[cfg(test)]
876#[path = "policy_tests.rs"]
877mod tests;