| 1 | //! Notification policy shared by every host: the typed payload, the |
| 2 | //! delivery-method and category gate, attention (focus) rules, the |
| 3 | //! per-event sound policy and audio cues. |
| 4 | //! |
| 5 | //! This crate owns *what* may notify and *which* sound it selects. The |
| 6 | //! terminal UI owns the *terminal*: `tui::notifications` is the only code that |
| 7 | //! hands a real terminal to [`delivery::notify_with_sinks`], writes the taskbar |
| 8 | //! progress sequence or the window title. Runtime callers that need a delivery |
| 9 | //! (the `notify` tool, headless exec) reach it through `codewhale_runtime::host_terminal`, |
| 10 | //! never by importing the TUI. |
| 11 | //! |
| 12 | //! Known limitation: [`delivery::notify_with_sinks`] builds the escape bytes |
| 13 | //! for every transport but writes only to the sink it is handed; the runtime |
| 14 | //! API's native notification preparation hands it a null sink and never |
| 15 | //! reaches a terminal transport. |
| 16 | |
| 17 | pub mod audio; |
| 18 | pub mod delivery; |
| 19 | pub mod payload; |
| 20 | pub mod sound_policy; |
| 21 | |
| 22 | use std::time::Duration; |
| 23 | |
| 24 | use codewhale_config::notifications::{ |
| 25 | NotificationCondition, NotificationMethod, NotificationsConfig, |
| 26 | }; |
| 27 | use payload::NotificationKind; |
| 28 | |
| 29 | /// Notification delivery method. |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 31 | pub enum Method { |
| 32 | /// Automatically pick the best protocol for the current terminal. |
| 33 | /// See [`delivery::resolve_method`] for the canonical resolution table. |
| 34 | #[default] |
| 35 | Auto, |
| 36 | /// OSC 9 escape: `\x1b]9;<msg>\x07` |
| 37 | Osc9, |
| 38 | /// Plain BEL character: `\x07` |
| 39 | Bel, |
| 40 | /// macOS Notification Center via `osascript`. |
| 41 | /// |
| 42 | /// Only reachable through [`Method::Auto`], and only on the macOS |
| 43 | /// terminals that expose no notification escape of their own (Apple |
| 44 | /// Terminal, the VS Code and JetBrains embedded terminals, plain tmux |
| 45 | /// without `LC_TERMINAL`). iTerm2, WezTerm, Ghostty, and kitty are |
| 46 | /// matched earlier in [`delivery::resolve_method`] and never get here. |
| 47 | /// |
| 48 | /// Known limitation (#4834): `display notification` is a Standard |
| 49 | /// Additions command, so the banner is attributed to the *bundled* |
| 50 | /// host process. `/usr/bin/osascript` is unbundled, so macOS credits |
| 51 | /// `com.apple.ScriptEditor2` — which is what supplies the Script |
| 52 | /// Editor icon and owns the System Settings → Notifications entry |
| 53 | /// (alert style, previews, Do Not Disturb). `display notification` |
| 54 | /// takes no icon parameter; fixing the attribution requires shipping |
| 55 | /// a real `.app` bundle, not a change in this file. |
| 56 | MacOS, |
| 57 | /// Kitty notification protocol (OSC 99) with ST terminator. |
| 58 | /// Uses `ESC ] 99 ; params ST` — no audible beep, unlike BEL. |
| 59 | Kitty, |
| 60 | /// Ghostty notification protocol (OSC 777). |
| 61 | /// Uses `ESC ] 777 ; notify ; title ; message BEL`. |
| 62 | Ghostty, |
| 63 | /// Suppress all notifications. |
| 64 | Off, |
| 65 | } |
| 66 | |
| 67 | /// Truthful result from one notification delivery attempt. |
| 68 | /// |
| 69 | /// Callers that surface a receipt (notably the model-facing `notify` tool) |
| 70 | /// use this instead of claiming a notification was sent when user policy, |
| 71 | /// focus, or the configured delivery method suppressed it. |
| 72 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 73 | pub enum DeliveryOutcome { |
| 74 | /// The notification was handed to the resolved transport. |
| 75 | Delivered(Method), |
| 76 | /// A background OS/audio worker was started; acceptance is unverified. |
| 77 | Dispatched(Method), |
| 78 | /// Banner bytes were sent, but the selected audio could not be dispatched. |
| 79 | DeliveredWithoutSound(Method), |
| 80 | /// A native dispatch was attempted, but selected audio was unavailable. |
| 81 | DispatchedWithoutSound(Method), |
| 82 | /// The bell-only transport has no authorized cue (off or rate limited). |
| 83 | SuppressedBySound, |
| 84 | /// The terminal is still in the foreground, or has only just lost focus. |
| 85 | SuppressedByAttention, |
| 86 | /// The event completed before the configured duration threshold. |
| 87 | SuppressedByThreshold, |
| 88 | /// Notification delivery is explicitly disabled. |
| 89 | SuppressedByMethod, |
| 90 | /// Quiet mode or the per-event allow-list suppressed this category. |
| 91 | SuppressedByGate, |
| 92 | /// The selected terminal protocol produced no transport bytes. |
| 93 | UnsupportedTransport, |
| 94 | /// The terminal transport could not be written. |
| 95 | DeliveryFailed, |
| 96 | } |
| 97 | |
| 98 | impl DeliveryOutcome { |
| 99 | /// Short, stable receipt text for command/tool surfaces. |
| 100 | #[must_use] |
| 101 | pub fn receipt(self) -> &'static str { |
| 102 | match self { |
| 103 | Self::Delivered(_) => "notification sent", |
| 104 | Self::Dispatched(_) => "notification dispatch attempted", |
| 105 | Self::DeliveredWithoutSound(_) => "notification sent; sound unavailable", |
| 106 | Self::DispatchedWithoutSound(_) => "notification dispatch attempted; sound unavailable", |
| 107 | Self::SuppressedBySound => "notification not sent: sound is off or rate limited", |
| 108 | Self::SuppressedByAttention => "notification not sent: attention policy blocked it", |
| 109 | Self::SuppressedByThreshold => "notification not sent: below the duration threshold", |
| 110 | Self::SuppressedByMethod => "notification not sent: notifications are off", |
| 111 | Self::SuppressedByGate => { |
| 112 | "notification not sent: quiet mode or event settings blocked it" |
| 113 | } |
| 114 | Self::UnsupportedTransport => { |
| 115 | "notification not sent: terminal transport is unsupported" |
| 116 | } |
| 117 | Self::DeliveryFailed => "notification not sent: terminal delivery failed", |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // ── Notification gate (#5041) ──────────────────────────────────────── |
| 123 | // |
| 124 | // One policy switchboard between "an event happened" and "the user's |
| 125 | // desktop is interrupted". `[notifications].quiet` silences every |
| 126 | // category; `[notifications.events]` disables individual categories. The |
| 127 | // gate is installed from config by `tui::notifications::settings` and consulted by |
| 128 | // `tui::notifications::notify_done` ahead of every delivery mechanism, so a disabled |
| 129 | // category can never leak through one specific protocol. |
| 130 | |
| 131 | /// Which notification categories may reach the user's desktop. |
| 132 | /// |
| 133 | /// The category set mirrors [`NotificationKind`] one-to-one. Default: |
| 134 | /// everything enabled, quiet off — matching the pre-#5041 behavior. |
| 135 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 136 | pub struct NotificationGate { |
| 137 | /// Suppress every category when `true` (`[notifications].quiet`). |
| 138 | pub quiet: bool, |
| 139 | pub turn_complete: bool, |
| 140 | pub subagent_terminal: bool, |
| 141 | pub approval_needed: bool, |
| 142 | pub input_needed: bool, |
| 143 | pub elevation_needed: bool, |
| 144 | pub model_notify: bool, |
| 145 | } |
| 146 | |
| 147 | impl Default for NotificationGate { |
| 148 | fn default() -> Self { |
| 149 | Self { |
| 150 | quiet: false, |
| 151 | turn_complete: true, |
| 152 | subagent_terminal: true, |
| 153 | approval_needed: true, |
| 154 | input_needed: true, |
| 155 | elevation_needed: true, |
| 156 | model_notify: true, |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | impl NotificationGate { |
| 162 | /// Project the `[notifications]` config block onto a gate. |
| 163 | #[must_use] |
| 164 | pub fn from_config(notif: &NotificationsConfig) -> Self { |
| 165 | Self { |
| 166 | quiet: notif.quiet, |
| 167 | turn_complete: notif.events.turn_complete, |
| 168 | subagent_terminal: notif.events.subagent_terminal, |
| 169 | approval_needed: notif.events.approval_needed, |
| 170 | input_needed: notif.events.input_needed, |
| 171 | elevation_needed: notif.events.elevation_needed, |
| 172 | model_notify: notif.events.model_notify, |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// Whether an event of `kind` may be delivered under this gate. |
| 177 | #[must_use] |
| 178 | pub fn allows(self, kind: NotificationKind) -> bool { |
| 179 | if self.quiet { |
| 180 | return false; |
| 181 | } |
| 182 | match kind { |
| 183 | NotificationKind::TurnComplete => self.turn_complete, |
| 184 | NotificationKind::SubagentTerminal | NotificationKind::BackgroundTerminal => { |
| 185 | self.subagent_terminal |
| 186 | } |
| 187 | NotificationKind::ApprovalNeeded => self.approval_needed, |
| 188 | NotificationKind::InputNeeded => self.input_needed, |
| 189 | NotificationKind::ElevationNeeded => self.elevation_needed, |
| 190 | NotificationKind::ModelNotify => self.model_notify, |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | const QUIET_BIT: u8 = 1 << 0; |
| 195 | const TURN_COMPLETE_BIT: u8 = 1 << 1; |
| 196 | const SUBAGENT_TERMINAL_BIT: u8 = 1 << 2; |
| 197 | const APPROVAL_NEEDED_BIT: u8 = 1 << 3; |
| 198 | const INPUT_NEEDED_BIT: u8 = 1 << 4; |
| 199 | const ELEVATION_NEEDED_BIT: u8 = 1 << 5; |
| 200 | const MODEL_NOTIFY_BIT: u8 = 1 << 6; |
| 201 | |
| 202 | pub const fn to_bits(self) -> u8 { |
| 203 | (self.quiet as u8 * Self::QUIET_BIT) |
| 204 | | (self.turn_complete as u8 * Self::TURN_COMPLETE_BIT) |
| 205 | | (self.subagent_terminal as u8 * Self::SUBAGENT_TERMINAL_BIT) |
| 206 | | (self.approval_needed as u8 * Self::APPROVAL_NEEDED_BIT) |
| 207 | | (self.input_needed as u8 * Self::INPUT_NEEDED_BIT) |
| 208 | | (self.elevation_needed as u8 * Self::ELEVATION_NEEDED_BIT) |
| 209 | | (self.model_notify as u8 * Self::MODEL_NOTIFY_BIT) |
| 210 | } |
| 211 | |
| 212 | pub const fn from_bits(bits: u8) -> Self { |
| 213 | Self { |
| 214 | quiet: bits & Self::QUIET_BIT != 0, |
| 215 | turn_complete: bits & Self::TURN_COMPLETE_BIT != 0, |
| 216 | subagent_terminal: bits & Self::SUBAGENT_TERMINAL_BIT != 0, |
| 217 | approval_needed: bits & Self::APPROVAL_NEEDED_BIT != 0, |
| 218 | input_needed: bits & Self::INPUT_NEEDED_BIT != 0, |
| 219 | elevation_needed: bits & Self::ELEVATION_NEEDED_BIT != 0, |
| 220 | model_notify: bits & Self::MODEL_NOTIFY_BIT != 0, |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Attention delivery policy installed from the resolved notification config. |
| 226 | /// |
| 227 | /// The default is background-only. A newly started TUI is treated as focused |
| 228 | /// until the terminal explicitly reports `FocusLost`, so the safe startup |
| 229 | /// behavior is silence rather than an unexpected banner or bell. |
| 230 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 231 | pub enum AttentionCondition { |
| 232 | Always = 0, |
| 233 | Unfocused = 1, |
| 234 | Never = 2, |
| 235 | } |
| 236 | |
| 237 | pub const DEFAULT_UNFOCUSED_GRACE: Duration = Duration::from_secs(2); |
| 238 | #[must_use] |
| 239 | pub fn attention_delivery_allowed_at( |
| 240 | condition: AttentionCondition, |
| 241 | focused: bool, |
| 242 | unfocused_since_ms: u64, |
| 243 | now_ms: u64, |
| 244 | ) -> bool { |
| 245 | match condition { |
| 246 | AttentionCondition::Always => true, |
| 247 | AttentionCondition::Never => false, |
| 248 | AttentionCondition::Unfocused => { |
| 249 | !focused |
| 250 | && unfocused_since_ms > 0 |
| 251 | && now_ms.saturating_sub(unfocused_since_ms) |
| 252 | >= DEFAULT_UNFOCUSED_GRACE.as_millis() as u64 |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | /// Native hosts provide focus observations; the same grace/condition rule |
| 258 | /// applies before either native sound or banner preparation. |
| 259 | pub fn native_attention_allowed( |
| 260 | config: &NotificationsConfig, |
| 261 | focused: bool, |
| 262 | unfocused_for: Duration, |
| 263 | ) -> bool { |
| 264 | let condition = match config.condition.unwrap_or(NotificationCondition::Unfocused) { |
| 265 | NotificationCondition::Always => AttentionCondition::Always, |
| 266 | NotificationCondition::Unfocused => AttentionCondition::Unfocused, |
| 267 | NotificationCondition::Never => AttentionCondition::Never, |
| 268 | }; |
| 269 | let elapsed = unfocused_for.as_millis().min(u128::from(u64::MAX - 1)) as u64; |
| 270 | attention_delivery_allowed_at(condition, focused, 1, elapsed + 1) |
| 271 | } |
| 272 | |
| 273 | /// Resolve the effective notification method/threshold/include-summary tuple |
| 274 | /// for a completed turn, taking the high-level |
| 275 | /// `[tui].notification_condition` override into account on top of the |
| 276 | /// lower-level `[notifications]` block. |
| 277 | /// |
| 278 | /// Returns `None` only when the high-level attention policy is `never`. |
| 279 | /// `Method::Off` remains a valid projection so the event gate can report |
| 280 | /// that both banner and sound are disabled. |
| 281 | #[must_use] |
| 282 | pub fn settings_projection(notif: &NotificationsConfig) -> Option<(Method, Duration, bool)> { |
| 283 | let method = match notif.method { |
| 284 | NotificationMethod::Auto => Method::Auto, |
| 285 | NotificationMethod::Osc9 => Method::Osc9, |
| 286 | NotificationMethod::Bel => Method::Bel, |
| 287 | NotificationMethod::Kitty => Method::Kitty, |
| 288 | NotificationMethod::Ghostty => Method::Ghostty, |
| 289 | NotificationMethod::Off => Method::Off, |
| 290 | }; |
| 291 | match notif.condition.unwrap_or(NotificationCondition::Unfocused) { |
| 292 | NotificationCondition::Always => Some((method, Duration::ZERO, notif.include_summary)), |
| 293 | NotificationCondition::Unfocused => Some(( |
| 294 | method, |
| 295 | Duration::from_secs(notif.threshold_secs), |
| 296 | notif.include_summary, |
| 297 | )), |
| 298 | NotificationCondition::Never => None, |
| 299 | } |
| 300 | } |
| 301 |