Skip to main content

vtcode_core/notifications/
mod.rs

1//! Push notification system for VT Code terminal clients
2//! Handles important events like command failures, errors, policy approval requests,
3//! human in the loop interactions, completion and requests.
4
5use anyhow::Result;
6use parking_lot::{Mutex, RwLock};
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Arc, OnceLock};
11use std::time::{Duration, Instant};
12
13use crate::config::loader::VTCodeConfig;
14use crate::hooks::{LifecycleHookEngine, NotificationHookType};
15use vtcode_config::{
16    NotificationBackend, NotificationCondition, NotificationDeliveryMode, TerminalNotificationMethod,
17    TuiNotificationEvent, TuiNotificationsConfig,
18};
19
20#[cfg(target_os = "macos")]
21mod macos;
22
23/// Types of important events that trigger notifications
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub enum NotificationEvent {
26    /// Generic ad-hoc notification
27    Custom { title: String, message: String },
28    /// Command execution failed
29    CommandFailure {
30        command: String,
31        error: String,
32        exit_code: Option<i32>,
33    },
34    /// Tool execution failed
35    ToolFailure {
36        tool_name: String,
37        error: String,
38        details: Option<String>,
39    },
40    /// Tool execution succeeded
41    ToolSuccess { tool_name: String, details: Option<String> },
42    /// General error occurred
43    Error { message: String, context: Option<String> },
44    /// Policy approval required for action
45    PolicyApprovalRequest { action: String, details: String },
46    /// Human in the loop interaction required
47    HumanInTheLoop { prompt: String, context: String },
48    /// Approval or elicitation prompt that should surface as a permission request
49    PermissionPrompt { title: String, message: String },
50    /// VT Code has been waiting for user input long enough to notify
51    IdlePrompt { title: String, message: String },
52    /// Task or operation completed
53    Completion {
54        task: String,
55        status: CompletionStatus,
56        details: Option<String>,
57    },
58    /// Request received
59    Request { request_type: String, details: String },
60}
61
62/// Status of a completed task
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
64pub enum CompletionStatus {
65    Success,
66    PartialSuccess,
67    Failure,
68    Cancelled,
69}
70
71/// Notification configuration
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct NotificationConfig {
74    /// Enable command failure notifications
75    pub command_failure_notifications: bool,
76    /// Enable tool failure notifications
77    pub tool_failure_notifications: bool,
78    /// Enable error notifications
79    pub error_notifications: bool,
80    /// Enable policy approval request notifications
81    pub policy_approval_notifications: bool,
82    /// Enable human in the loop notifications
83    pub hitl_notifications: bool,
84    /// Enable completion notifications for successful turns/tasks
85    pub completion_success_notifications: bool,
86    /// Enable completion notifications for partial/failure/cancelled turns/tasks
87    pub completion_failure_notifications: bool,
88    /// Enable request notifications
89    pub request_notifications: bool,
90    /// Enable tool success notifications
91    pub tool_success_notifications: bool,
92    /// Enable/disable all terminal notifications (overrides other settings)
93    pub terminal_notifications_enabled: bool,
94    /// Suppress notifications while terminal is focused.
95    pub suppress_when_focused: bool,
96    /// Delivery mode for notifications.
97    pub delivery_mode: NotificationDeliveryMode,
98    /// Preferred backend for desktop notification delivery.
99    pub backend: NotificationBackend,
100    /// Preferred terminal notification transport.
101    pub notification_method: TerminalNotificationMethod,
102    /// When to deliver notifications relative to terminal focus.
103    /// Defaults to `Unfocused` (only when terminal is not focused).
104    pub notification_condition: NotificationCondition,
105    /// Time window for suppressing repeated identical notifications.
106    pub repeat_window_seconds: u64,
107    /// Maximum identical notifications allowed per suppression window.
108    pub max_identical_notifications_in_window: u32,
109}
110
111impl Default for NotificationConfig {
112    fn default() -> Self {
113        Self {
114            command_failure_notifications: false,
115            tool_failure_notifications: false,
116            error_notifications: true,
117            policy_approval_notifications: true,
118            hitl_notifications: true,
119            completion_success_notifications: false,
120            completion_failure_notifications: true,
121            request_notifications: false,
122            tool_success_notifications: false,
123            terminal_notifications_enabled: true,
124            suppress_when_focused: true,
125            delivery_mode: NotificationDeliveryMode::Desktop,
126            backend: NotificationBackend::Auto,
127            notification_method: TerminalNotificationMethod::Auto,
128            notification_condition: NotificationCondition::default(),
129            repeat_window_seconds: 30,
130            max_identical_notifications_in_window: 1,
131        }
132    }
133}
134
135impl NotificationConfig {
136    /// Build runtime notification config from full VTCodeConfig.
137    pub fn from_vtcode_config(config: &VTCodeConfig) -> Self {
138        let notifications = &config.ui.notifications;
139        let mut resolved = Self {
140            command_failure_notifications: notifications.command_failure.unwrap_or(notifications.tool_failure),
141            tool_failure_notifications: notifications.tool_failure,
142            error_notifications: notifications.error,
143            policy_approval_notifications: notifications.policy_approval.unwrap_or(notifications.hitl),
144            hitl_notifications: notifications.hitl,
145            completion_success_notifications: notifications.completion_success.unwrap_or(notifications.completion),
146            completion_failure_notifications: notifications.completion_failure.unwrap_or(notifications.completion),
147            request_notifications: notifications.request.unwrap_or(notifications.hitl),
148            tool_success_notifications: notifications.tool_success,
149            terminal_notifications_enabled: notifications.enabled,
150            suppress_when_focused: notifications.suppress_when_focused,
151            delivery_mode: notifications.delivery_mode,
152            backend: notifications.backend,
153            notification_method: config.tui.notification_method.unwrap_or_default(),
154            notification_condition: config.tui.notification_condition.unwrap_or_default(),
155            repeat_window_seconds: notifications.repeat_window_seconds,
156            max_identical_notifications_in_window: notifications.max_identical_in_window,
157        };
158
159        if let Some(tui_notifications) = &config.tui.notifications {
160            match tui_notifications {
161                TuiNotificationsConfig::Enabled(enabled) => {
162                    resolved.terminal_notifications_enabled = *enabled;
163                }
164                TuiNotificationsConfig::Events(events) => {
165                    let turn_complete = events.contains(&TuiNotificationEvent::AgentTurnComplete);
166                    let approval_requested = events.contains(&TuiNotificationEvent::ApprovalRequested);
167                    resolved.terminal_notifications_enabled = true;
168                    resolved.command_failure_notifications = false;
169                    resolved.tool_failure_notifications = false;
170                    resolved.error_notifications = false;
171                    resolved.tool_success_notifications = false;
172                    resolved.completion_success_notifications = turn_complete;
173                    resolved.completion_failure_notifications = turn_complete;
174                    resolved.policy_approval_notifications = approval_requested;
175                    resolved.hitl_notifications = approval_requested;
176                    resolved.request_notifications = approval_requested;
177                }
178            }
179        }
180
181        resolved
182    }
183}
184
185#[derive(Debug)]
186struct RepeatEntry {
187    window_start: Instant,
188    sent_in_window: u32,
189}
190
191impl RepeatEntry {
192    fn new(now: Instant) -> Self {
193        Self { window_start: now, sent_in_window: 0 }
194    }
195}
196
197#[derive(Debug, Default)]
198struct RepeatSuppressionState {
199    entries: HashMap<String, RepeatEntry>,
200}
201
202#[derive(Debug)]
203enum RepeatDecision {
204    Deliver,
205    Suppress,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209enum DesktopNotificationBackend {
210    #[cfg(target_os = "macos")]
211    Osascript,
212    NotifyRust,
213}
214
215const AUTO_DESKTOP_NOTIFICATION_BACKENDS: &[DesktopNotificationBackend] = &[DesktopNotificationBackend::NotifyRust];
216#[cfg(target_os = "macos")]
217const OSASCRIPT_DESKTOP_NOTIFICATION_BACKENDS: &[DesktopNotificationBackend] = &[DesktopNotificationBackend::Osascript];
218const NOTIFY_RUST_DESKTOP_NOTIFICATION_BACKENDS: &[DesktopNotificationBackend] =
219    &[DesktopNotificationBackend::NotifyRust];
220const NO_DESKTOP_NOTIFICATION_BACKENDS: &[DesktopNotificationBackend] = &[];
221
222/// Notification manager that handles sending notifications
223pub struct NotificationManager {
224    config: Arc<RwLock<NotificationConfig>>,
225    /// Track if the terminal is currently focused/active
226    terminal_focused: Arc<AtomicBool>,
227    repeat_state: Arc<Mutex<RepeatSuppressionState>>,
228}
229
230impl NotificationManager {
231    /// Create a new notification manager with default configuration
232    pub fn new() -> Self {
233        Self {
234            config: Arc::new(RwLock::new(NotificationConfig::default())),
235            terminal_focused: Arc::new(AtomicBool::new(false)), // Start as not focused
236            repeat_state: Arc::new(Mutex::new(RepeatSuppressionState::default())),
237        }
238    }
239
240    /// Create a new notification manager with custom configuration
241    pub fn with_config(config: NotificationConfig) -> Self {
242        Self {
243            config: Arc::new(RwLock::new(config)),
244            terminal_focused: Arc::new(AtomicBool::new(false)), // Start as not focused
245            repeat_state: Arc::new(Mutex::new(RepeatSuppressionState::default())),
246        }
247    }
248
249    /// Send a notification for an event
250    pub async fn send_notification(&self, event: NotificationEvent) -> Result<()> {
251        self.send_notification_inner(event, false).await
252    }
253
254    /// Send a notification for an event, ignoring terminal focus state.
255    ///
256    /// The bypass is a call-time flag, never a config rewrite: toggling the
257    /// shared config around the send would race with concurrent sends and
258    /// clobber unrelated settings updates.
259    pub async fn send_notification_forced(&self, event: NotificationEvent) -> Result<()> {
260        self.send_notification_inner(event, true).await
261    }
262
263    async fn send_notification_inner(&self, event: NotificationEvent, forced: bool) -> Result<()> {
264        let config = self.config.read().clone();
265
266        // Check if terminal notifications are enabled globally first
267        if !config.terminal_notifications_enabled {
268            return Ok(());
269        }
270
271        // Evaluate notification condition based on configuration
272        // `Unfocused` (default): only deliver when terminal is not focused
273        // `Always`: deliver regardless of focus state
274        let is_terminal_active = self.terminal_focused.load(Ordering::Relaxed);
275        let should_suppress_for_focus = !forced
276            && match config.notification_condition {
277                NotificationCondition::Unfocused => is_terminal_active && config.suppress_when_focused,
278                NotificationCondition::Always | NotificationCondition::Unknown => false,
279            };
280        if should_suppress_for_focus {
281            return Ok(());
282        }
283
284        if !self.event_enabled(&event, &config) {
285            return Ok(());
286        }
287
288        match self.repeat_decision(&event, &config) {
289            RepeatDecision::Deliver => {
290                self.send_notification_impl(&event, &config).await?;
291                self.run_notification_hook_if_configured(&event).await;
292            }
293            RepeatDecision::Suppress => {
294                return Ok(());
295            }
296        }
297
298        Ok(())
299    }
300
301    fn event_enabled(&self, event: &NotificationEvent, config: &NotificationConfig) -> bool {
302        match event {
303            NotificationEvent::Custom { .. } => true,
304            NotificationEvent::CommandFailure { .. } => config.command_failure_notifications,
305            NotificationEvent::ToolFailure { .. } => config.tool_failure_notifications,
306            NotificationEvent::ToolSuccess { .. } => config.tool_success_notifications,
307            NotificationEvent::Error { .. } => config.error_notifications,
308            NotificationEvent::PolicyApprovalRequest { .. } => config.policy_approval_notifications,
309            NotificationEvent::HumanInTheLoop { .. } => config.hitl_notifications,
310            NotificationEvent::PermissionPrompt { .. } => {
311                config.policy_approval_notifications || config.hitl_notifications
312            }
313            NotificationEvent::IdlePrompt { .. } => config.request_notifications,
314            NotificationEvent::Completion { status, .. } => match status {
315                CompletionStatus::Success => config.completion_success_notifications,
316                CompletionStatus::PartialSuccess | CompletionStatus::Failure | CompletionStatus::Cancelled => {
317                    config.completion_failure_notifications
318                }
319            },
320            NotificationEvent::Request { .. } => config.request_notifications,
321        }
322    }
323
324    fn repeat_decision(&self, event: &NotificationEvent, config: &NotificationConfig) -> RepeatDecision {
325        if config.repeat_window_seconds == 0 {
326            return RepeatDecision::Deliver;
327        }
328
329        let Some(fingerprint) = self.repeat_fingerprint(event) else {
330            return RepeatDecision::Deliver;
331        };
332
333        let window = Duration::from_secs(config.repeat_window_seconds.max(1));
334        let max_allowed = config.max_identical_notifications_in_window.max(1);
335        let now = Instant::now();
336
337        let mut state = self.repeat_state.lock();
338
339        if state.entries.len() > 1024 {
340            state.entries.retain(|_, entry| now.duration_since(entry.window_start) < window);
341        }
342
343        let entry = state.entries.entry(fingerprint).or_insert_with(|| RepeatEntry::new(now));
344
345        if now.duration_since(entry.window_start) >= window {
346            *entry = RepeatEntry::new(now);
347        }
348
349        if entry.sent_in_window < max_allowed {
350            entry.sent_in_window += 1;
351            RepeatDecision::Deliver
352        } else {
353            RepeatDecision::Suppress
354        }
355    }
356
357    /// Internal method to send the actual notification
358    async fn send_notification_impl(&self, event: &NotificationEvent, config: &NotificationConfig) -> Result<()> {
359        let message = self.format_notification_message(event);
360        self.send_message(&message, config).await
361    }
362
363    async fn run_notification_hook_if_configured(&self, event: &NotificationEvent) {
364        let Some((notification_type, title, message)) = self.notification_hook_payload(event) else {
365            return;
366        };
367        let Some(engine) = get_global_notification_hook_engine() else {
368            return;
369        };
370
371        if let Err(error) = engine
372            .run_notification(notification_type, title.as_str(), message.as_str())
373            .await
374        {
375            tracing::warn!(
376                error = %error,
377                notification_type = notification_type.as_str(),
378                "Failed to run notification lifecycle hook"
379            );
380        }
381    }
382
383    async fn send_message(&self, message: &str, config: &NotificationConfig) -> Result<()> {
384        match config.delivery_mode {
385            NotificationDeliveryMode::Terminal | NotificationDeliveryMode::Unknown => {
386                self.send_terminal_bell(message).await;
387            }
388            NotificationDeliveryMode::Hybrid => {
389                self.send_terminal_bell(message).await;
390                if config.backend != NotificationBackend::Terminal {
391                    let _ = self.send_desktop_notification(message, config).await;
392                }
393            }
394            NotificationDeliveryMode::Desktop => {
395                if config.backend == NotificationBackend::Terminal {
396                    self.send_terminal_bell(message).await;
397                } else {
398                    let _ = self.send_desktop_notification(message, config).await;
399                }
400            }
401        }
402
403        Ok(())
404    }
405
406    fn repeat_fingerprint(&self, event: &NotificationEvent) -> Option<String> {
407        let event_type = match event {
408            NotificationEvent::Custom { .. } => "custom",
409            NotificationEvent::CommandFailure { .. } => "command_failure",
410            NotificationEvent::ToolFailure { .. } => "tool_failure",
411            NotificationEvent::ToolSuccess { .. } => "tool_success",
412            NotificationEvent::Error { .. } => "error",
413            NotificationEvent::Completion { .. } => "completion",
414            NotificationEvent::IdlePrompt { .. } => "idle_prompt",
415            NotificationEvent::Request { .. } => "request",
416            NotificationEvent::PolicyApprovalRequest { .. }
417            | NotificationEvent::HumanInTheLoop { .. }
418            | NotificationEvent::PermissionPrompt { .. } => {
419                return None;
420            }
421        };
422
423        let normalized_message = self.normalize_message(&self.format_notification_message(event));
424        Some(format!("{event_type}:{normalized_message}"))
425    }
426
427    fn normalize_message(&self, message: &str) -> String {
428        vtcode_commons::formatting::collapse_whitespace(message).to_ascii_lowercase()
429    }
430
431    /// Format a notification message based on the event
432    fn format_notification_message(&self, event: &NotificationEvent) -> String {
433        match event {
434            NotificationEvent::Custom { title, message } => {
435                let title = title.trim();
436                if title.is_empty() {
437                    message.clone()
438                } else {
439                    format!("{title}: {message}")
440                }
441            }
442            NotificationEvent::CommandFailure { command, error, exit_code } => {
443                let exit_code_str = exit_code.map(|code| format!(" (exit code: {code})")).unwrap_or_default();
444                format!("Command failed: {command}{exit_code_str} - Error: {error}")
445            }
446            NotificationEvent::ToolFailure { tool_name, error, details } => {
447                let details_str = details.as_ref().map(|d| format!(" - Details: {d}")).unwrap_or_default();
448                format!("Tool '{tool_name}' failed: {error}{details_str}")
449            }
450            NotificationEvent::ToolSuccess { tool_name, details } => {
451                let details_str = details.as_ref().map(|d| format!(" - {d}")).unwrap_or_default();
452                format!("Tool '{tool_name}' completed{details_str}")
453            }
454            NotificationEvent::Error { message, context } => {
455                let context_str = context.as_ref().map(|ctx| format!(" [{ctx}]")).unwrap_or_default();
456                format!("Error occurred{context_str}: {message}")
457            }
458            NotificationEvent::PolicyApprovalRequest { action, details } => {
459                format!("Policy approval required: {action} - {details}")
460            }
461            NotificationEvent::HumanInTheLoop { prompt, context } => {
462                format!("Human input required: {prompt} [Context: {context}]")
463            }
464            NotificationEvent::PermissionPrompt { title, message } => {
465                format!("{title}: {message}")
466            }
467            NotificationEvent::IdlePrompt { title, message } => {
468                format!("{title}: {message}")
469            }
470            NotificationEvent::Completion { task, status, details } => {
471                let status_str = match status {
472                    CompletionStatus::Success => "completed successfully",
473                    CompletionStatus::PartialSuccess => "partially completed",
474                    CompletionStatus::Failure => "failed",
475                    CompletionStatus::Cancelled => "was cancelled",
476                };
477                let details_str = details.as_ref().map(|d| format!(" - {d}")).unwrap_or_default();
478                if task == "turn" {
479                    format!("Agent turn ended: {status_str}{details_str}")
480                } else if task == "session" {
481                    format!("Agent session ended: {status_str}{details_str}")
482                } else {
483                    format!("Task '{task}' {status_str}{details_str}")
484                }
485            }
486            NotificationEvent::Request { request_type, details } => {
487                format!("New {request_type} request: {details}")
488            }
489        }
490    }
491
492    /// Send a terminal bell notification
493    async fn send_terminal_bell(&self, message: &str) {
494        use crate::utils::ansi_codes::notify_attention_with_terminal_method;
495        let method = self.config.read().notification_method;
496        notify_attention_with_terminal_method(true, Some(message), method);
497    }
498
499    async fn send_desktop_notification(&self, message: &str, config: &NotificationConfig) -> bool {
500        tracing::info!("Notification: {}", message);
501
502        for backend in self.desktop_notification_backends(config.backend) {
503            if self.try_send_desktop_notification_backend(*backend, message) {
504                return true;
505            }
506        }
507
508        false
509    }
510
511    fn desktop_notification_backends(&self, backend: NotificationBackend) -> &'static [DesktopNotificationBackend] {
512        match backend {
513            NotificationBackend::Auto => AUTO_DESKTOP_NOTIFICATION_BACKENDS,
514            NotificationBackend::Osascript => {
515                #[cfg(target_os = "macos")]
516                {
517                    OSASCRIPT_DESKTOP_NOTIFICATION_BACKENDS
518                }
519                #[cfg(not(target_os = "macos"))]
520                {
521                    tracing::warn!("osascript notification backend is only supported on macOS");
522                    NO_DESKTOP_NOTIFICATION_BACKENDS
523                }
524            }
525            NotificationBackend::NotifyRust => NOTIFY_RUST_DESKTOP_NOTIFICATION_BACKENDS,
526            NotificationBackend::Terminal | NotificationBackend::Unknown => NO_DESKTOP_NOTIFICATION_BACKENDS,
527        }
528    }
529
530    fn try_send_desktop_notification_backend(&self, backend: DesktopNotificationBackend, message: &str) -> bool {
531        match backend {
532            #[cfg(target_os = "macos")]
533            DesktopNotificationBackend::Osascript => self.send_osascript_notification(message),
534            DesktopNotificationBackend::NotifyRust => self.send_notify_rust_notification(message),
535        }
536    }
537
538    #[cfg(target_os = "macos")]
539    fn send_osascript_notification(&self, message: &str) -> bool {
540        match macos::send_macos_osascript_notification(crate::config::constants::app::DISPLAY_NAME, message) {
541            Ok(()) => true,
542            Err(error) => {
543                tracing::warn!(error = %error, "Failed to send macOS osascript notification");
544                false
545            }
546        }
547    }
548
549    fn send_notify_rust_notification(&self, message: &str) -> bool {
550        #[cfg(feature = "desktop-notifications")]
551        {
552            use std::time::Duration;
553            let mut notification = notify_rust::Notification::new();
554            notification
555                .summary(crate::config::constants::app::DISPLAY_NAME)
556                .body(message)
557                .icon("dialog-information")
558                .timeout(Duration::from_secs(5));
559
560            #[cfg(target_os = "macos")]
561            let result = send_after_macos_notification_setup(ensure_macos_notification_application, || {
562                notification.show().map_err(Into::into)
563            });
564            #[cfg(not(target_os = "macos"))]
565            let result = notification.show();
566
567            match result {
568                Ok(notification) => {
569                    tracing::debug!("Desktop notification sent: {:?}", notification);
570                    true
571                }
572                Err(error) => {
573                    tracing::warn!("Failed to send desktop notification: {}", error);
574                    false
575                }
576            }
577        }
578
579        #[cfg(not(feature = "desktop-notifications"))]
580        {
581            let _ = message;
582            tracing::warn!("notify_rust notification backend is unavailable in this build");
583            false
584        }
585    }
586
587    /// Update the notification configuration
588    pub async fn update_config(&self, new_config: NotificationConfig) {
589        self.update_config_sync(new_config);
590    }
591
592    /// Synchronously update notification configuration.
593    pub fn update_config_sync(&self, new_config: NotificationConfig) {
594        let mut config = self.config.write();
595        *config = new_config;
596    }
597
598    /// Get the current notification configuration
599    pub async fn get_config(&self) -> NotificationConfig {
600        self.get_config_sync()
601    }
602
603    /// Get the current notification configuration synchronously.
604    pub fn get_config_sync(&self) -> NotificationConfig {
605        self.config.read().clone()
606    }
607
608    /// Update the terminal focus state - true if terminal is focused/active, false otherwise
609    pub fn set_terminal_focused(&self, focused: bool) {
610        self.terminal_focused.store(focused, Ordering::Relaxed);
611    }
612
613    /// Get the current terminal focus state
614    pub fn is_terminal_focused(&self) -> bool {
615        self.terminal_focused.load(Ordering::Relaxed)
616    }
617
618    fn notification_hook_payload(&self, event: &NotificationEvent) -> Option<(NotificationHookType, String, String)> {
619        match event {
620            NotificationEvent::PermissionPrompt { title, message } => {
621                Some((NotificationHookType::PermissionPrompt, title.clone(), message.clone()))
622            }
623            NotificationEvent::IdlePrompt { title, message } => {
624                Some((NotificationHookType::IdlePrompt, title.clone(), message.clone()))
625            }
626            _ => None,
627        }
628    }
629}
630
631#[cfg(all(target_os = "macos", feature = "desktop-notifications"))]
632fn ensure_macos_notification_application() -> Result<()> {
633    // notify-rust otherwise asks mac-notification-sys to discover an app with
634    // AppleScript, which triggers a macOS Automation permission dialog.
635    // `set_application` is idempotent after success and retryable after failure
636    // (patches/mac-notification-sys/PATCH.md). Call it on every send instead of
637    // caching a failure in `OnceLock` for the process lifetime.
638    notify_rust::set_application("com.apple.finder")
639        .map_err(|error| anyhow::anyhow!("failed to configure macOS notification application: {error}"))
640}
641
642#[cfg(all(target_os = "macos", feature = "desktop-notifications"))]
643fn send_after_macos_notification_setup<T>(
644    setup: impl FnOnce() -> Result<()>,
645    send: impl FnOnce() -> Result<T>,
646) -> Result<T> {
647    setup()?;
648    send()
649}
650
651impl Default for NotificationManager {
652    fn default() -> Self {
653        Self::new()
654    }
655}
656
657/// Global notification manager instance for easy access
658static GLOBAL_NOTIFICATION_MANAGER: OnceLock<NotificationManager> = OnceLock::new();
659static GLOBAL_NOTIFICATION_HOOK_ENGINE: OnceLock<RwLock<Option<LifecycleHookEngine>>> = OnceLock::new();
660
661/// Initialize the global notification manager
662pub fn init_global_notification_manager() -> Result<()> {
663    let manager = NotificationManager::new();
664    GLOBAL_NOTIFICATION_MANAGER
665        .set(manager)
666        .map_err(|_e| anyhow::anyhow!("Failed to set global notification manager"))
667}
668
669/// Initialize the global notification manager with explicit configuration.
670pub fn init_global_notification_manager_with_config(config: NotificationConfig) -> Result<()> {
671    let manager = NotificationManager::with_config(config);
672    GLOBAL_NOTIFICATION_MANAGER
673        .set(manager)
674        .map_err(|_e| anyhow::anyhow!("Failed to set global notification manager"))
675}
676
677/// Get a reference to the global notification manager
678pub fn get_global_notification_manager() -> Option<&'static NotificationManager> {
679    GLOBAL_NOTIFICATION_MANAGER.get()
680}
681
682pub fn set_global_notification_hook_engine(engine: Option<LifecycleHookEngine>) {
683    let slot = GLOBAL_NOTIFICATION_HOOK_ENGINE.get_or_init(|| RwLock::new(None));
684    *slot.write() = engine;
685}
686
687fn get_global_notification_hook_engine() -> Option<LifecycleHookEngine> {
688    GLOBAL_NOTIFICATION_HOOK_ENGINE.get().and_then(|slot| slot.read().clone())
689}
690
691/// Ensure the global manager is initialized, then apply updated configuration.
692pub fn apply_global_notification_config(config: NotificationConfig) -> Result<()> {
693    if let Some(manager) = get_global_notification_manager() {
694        manager.update_config_sync(config);
695        return Ok(());
696    }
697    init_global_notification_manager_with_config(config)
698}
699
700/// Build and apply notification settings from VTCodeConfig.
701pub fn apply_global_notification_config_from_vtcode(config: &VTCodeConfig) -> Result<()> {
702    let notification_config = NotificationConfig::from_vtcode_config(config);
703    apply_global_notification_config(notification_config)
704}
705
706/// Send a notification using the global notification manager
707pub async fn send_global_notification(event: NotificationEvent) -> Result<(), anyhow::Error> {
708    if let Some(manager) = get_global_notification_manager() {
709        manager.send_notification(event).await
710    } else {
711        // If global manager isn't initialized, create a temporary one for this notification
712        let manager = NotificationManager::new();
713        manager.send_notification(event).await
714    }
715}
716
717/// Send a notification immediately, even when the terminal is currently focused.
718pub async fn send_global_notification_force(event: NotificationEvent) -> Result<(), anyhow::Error> {
719    if let Some(manager) = get_global_notification_manager() {
720        manager.send_notification_forced(event).await
721    } else {
722        // If global manager isn't initialized, create a temporary one for this notification
723        let manager = NotificationManager::new();
724        manager.send_notification_forced(event).await
725    }
726}
727
728/// Set the terminal focus state using the global notification manager
729pub fn set_global_terminal_focused(focused: bool) {
730    if let Some(manager) = get_global_notification_manager() {
731        manager.set_terminal_focused(focused);
732    }
733}
734
735/// Check if the terminal is focused using the global notification manager
736pub fn is_global_terminal_focused() -> bool {
737    if let Some(manager) = get_global_notification_manager() {
738        manager.is_terminal_focused()
739    } else {
740        false // Default to not focused if manager isn't initialized
741    }
742}
743
744/// Convenience function to send a tool failure notification
745#[cold]
746pub async fn notify_tool_failure(tool_name: &str, error: &str, details: Option<&str>) -> Result<(), anyhow::Error> {
747    let event = NotificationEvent::ToolFailure {
748        tool_name: tool_name.to_string(),
749        error: error.to_string(),
750        details: details.map(|s| s.to_string()),
751    };
752    send_global_notification(event).await
753}
754
755/// Convenience function to send a tool success notification
756pub async fn notify_tool_success(tool_name: &str, details: Option<&str>) -> Result<(), anyhow::Error> {
757    let event = NotificationEvent::ToolSuccess {
758        tool_name: tool_name.to_string(),
759        details: details.map(|s| s.to_string()),
760    };
761    send_global_notification(event).await
762}
763
764/// Convenience function to send a command failure notification
765#[cold]
766pub async fn notify_command_failure(command: &str, error: &str, exit_code: Option<i32>) -> Result<(), anyhow::Error> {
767    let event = NotificationEvent::CommandFailure {
768        command: command.to_string(),
769        error: error.to_string(),
770        exit_code,
771    };
772    send_global_notification(event).await
773}
774
775/// Convenience function to send an error notification
776#[cold]
777pub async fn notify_error(message: &str, context: Option<&str>) -> Result<(), anyhow::Error> {
778    let event = NotificationEvent::Error {
779        message: message.to_string(),
780        context: context.map(|s| s.to_string()),
781    };
782    send_global_notification(event).await
783}
784
785/// Convenience function to send a human in the loop notification
786pub async fn notify_human_in_the_loop(prompt: &str, context: &str) -> Result<(), anyhow::Error> {
787    let event = NotificationEvent::HumanInTheLoop {
788        prompt: prompt.to_string(),
789        context: context.to_string(),
790    };
791    send_global_notification(event).await
792}
793
794#[cfg(test)]
795mod tests;