1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
25pub enum NotificationEvent {
26 Custom { title: String, message: String },
28 CommandFailure {
30 command: String,
31 error: String,
32 exit_code: Option<i32>,
33 },
34 ToolFailure {
36 tool_name: String,
37 error: String,
38 details: Option<String>,
39 },
40 ToolSuccess { tool_name: String, details: Option<String> },
42 Error { message: String, context: Option<String> },
44 PolicyApprovalRequest { action: String, details: String },
46 HumanInTheLoop { prompt: String, context: String },
48 PermissionPrompt { title: String, message: String },
50 IdlePrompt { title: String, message: String },
52 Completion {
54 task: String,
55 status: CompletionStatus,
56 details: Option<String>,
57 },
58 Request { request_type: String, details: String },
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
64pub enum CompletionStatus {
65 Success,
66 PartialSuccess,
67 Failure,
68 Cancelled,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct NotificationConfig {
74 pub command_failure_notifications: bool,
76 pub tool_failure_notifications: bool,
78 pub error_notifications: bool,
80 pub policy_approval_notifications: bool,
82 pub hitl_notifications: bool,
84 pub completion_success_notifications: bool,
86 pub completion_failure_notifications: bool,
88 pub request_notifications: bool,
90 pub tool_success_notifications: bool,
92 pub terminal_notifications_enabled: bool,
94 pub suppress_when_focused: bool,
96 pub delivery_mode: NotificationDeliveryMode,
98 pub backend: NotificationBackend,
100 pub notification_method: TerminalNotificationMethod,
102 pub notification_condition: NotificationCondition,
105 pub repeat_window_seconds: u64,
107 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 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
222pub struct NotificationManager {
224 config: Arc<RwLock<NotificationConfig>>,
225 terminal_focused: Arc<AtomicBool>,
227 repeat_state: Arc<Mutex<RepeatSuppressionState>>,
228}
229
230impl NotificationManager {
231 pub fn new() -> Self {
233 Self {
234 config: Arc::new(RwLock::new(NotificationConfig::default())),
235 terminal_focused: Arc::new(AtomicBool::new(false)), repeat_state: Arc::new(Mutex::new(RepeatSuppressionState::default())),
237 }
238 }
239
240 pub fn with_config(config: NotificationConfig) -> Self {
242 Self {
243 config: Arc::new(RwLock::new(config)),
244 terminal_focused: Arc::new(AtomicBool::new(false)), repeat_state: Arc::new(Mutex::new(RepeatSuppressionState::default())),
246 }
247 }
248
249 pub async fn send_notification(&self, event: NotificationEvent) -> Result<()> {
251 self.send_notification_inner(event, false).await
252 }
253
254 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 if !config.terminal_notifications_enabled {
268 return Ok(());
269 }
270
271 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 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 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 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 pub async fn update_config(&self, new_config: NotificationConfig) {
589 self.update_config_sync(new_config);
590 }
591
592 pub fn update_config_sync(&self, new_config: NotificationConfig) {
594 let mut config = self.config.write();
595 *config = new_config;
596 }
597
598 pub async fn get_config(&self) -> NotificationConfig {
600 self.get_config_sync()
601 }
602
603 pub fn get_config_sync(&self) -> NotificationConfig {
605 self.config.read().clone()
606 }
607
608 pub fn set_terminal_focused(&self, focused: bool) {
610 self.terminal_focused.store(focused, Ordering::Relaxed);
611 }
612
613 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::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
657static GLOBAL_NOTIFICATION_MANAGER: OnceLock<NotificationManager> = OnceLock::new();
659static GLOBAL_NOTIFICATION_HOOK_ENGINE: OnceLock<RwLock<Option<LifecycleHookEngine>>> = OnceLock::new();
660
661pub 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
669pub 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
677pub 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
691pub 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
700pub 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
706pub 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 let manager = NotificationManager::new();
713 manager.send_notification(event).await
714 }
715}
716
717pub 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 let manager = NotificationManager::new();
724 manager.send_notification_forced(event).await
725 }
726}
727
728pub 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
735pub fn is_global_terminal_focused() -> bool {
737 if let Some(manager) = get_global_notification_manager() {
738 manager.is_terminal_focused()
739 } else {
740 false }
742}
743
744#[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
755pub 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#[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#[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
785pub 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;