mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
gpui: Keep macOS notification service calls off the UI thread (#66934)
## Problem macOS notification APIs can synchronously wait for the notification service, even when they expose completion handlers. A captured main-thread stack showed notification dismissal blocked in `removePendingNotificationRequestsWithIdentifiers:` → `__NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__`. GPUI called that API on the UI thread while holding its platform-state mutex, freezing the interface until macOS replied. ## Changes - Lazily start one dedicated notification thread that owns the notification center, delegate, authorization state, and registered categories. - Queue posting and dismissal in FIFO order so a delayed dismissal cannot overtake a replacement notification. Initialization and native calls happen on the worker; notification responses still return through the foreground executor. - Return a `Task<()>` from `dismiss_system_notification`, allowing callers to await completion without blocking the UI. Completion means the platform calls returned, not that asynchronous OS work finished. Dropping the task does not cancel dismissal. Update the other platform implementations, example, and tests for the return type. - Keep the unbundled-binary guard and use autorelease pools around native work. A stalled notification service can still delay later notification commands, but no longer stalls the UI. ## Verification Ran on macOS: ```sh corgi test -p gpui -p gpui_macos --lib 'system_notification' ``` All five tests passed. The new regression test submits show/dismiss/show commands without advancing a consumer, checks their order, and verifies completion remains pending until acknowledgement. The source published here is identical to that tested revision; the subsequent commit only records the human removal of the README review marker. No live macOS-service stall was induced, and Linux/Windows/browser workflows were not run. Release Notes: - [GPUI] Fixed macOS system notification operations blocking the UI thread while waiting for the notification service. --------- Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com> Co-authored-by: Anthony Eid <hello@anthonyeid.me>
This commit is contained in:
@@ -63,7 +63,7 @@ impl Render for SystemNotificationExample {
|
||||
)))
|
||||
.child(
|
||||
button("dismiss", "Dismiss").on_click(cx.listener(|this, _, _, cx| {
|
||||
cx.dismiss_system_notification(NOTIFICATION_TAG);
|
||||
cx.dismiss_system_notification(NOTIFICATION_TAG).detach();
|
||||
this.status = "Dismissed the notification".into();
|
||||
cx.notify();
|
||||
})),
|
||||
|
||||
@@ -2085,8 +2085,11 @@ impl App {
|
||||
///
|
||||
/// Best-effort: some platforms cannot retract a notification once shown,
|
||||
/// in which case it ages out of the notification center on its own.
|
||||
pub fn dismiss_system_notification(&self, tag: &str) {
|
||||
self.platform.dismiss_system_notification(tag);
|
||||
/// The task completes after the platform calls return, not after any
|
||||
/// asynchronous work inside the operating system. Dropping it does not
|
||||
/// cancel dismissal.
|
||||
pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
|
||||
self.platform.dismiss_system_notification(tag)
|
||||
}
|
||||
|
||||
/// Registers the handler invoked when the user activates a system
|
||||
|
||||
@@ -1424,7 +1424,7 @@ mod tests {
|
||||
}]
|
||||
);
|
||||
|
||||
cx.update(|cx| cx.dismiss_system_notification("thread-1"));
|
||||
cx.update(|cx| cx.dismiss_system_notification("thread-1").detach());
|
||||
assert!(cx.delivered_system_notifications().is_empty());
|
||||
assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]);
|
||||
}
|
||||
@@ -1499,7 +1499,7 @@ mod tests {
|
||||
actions: Vec::new(),
|
||||
});
|
||||
cx.on_system_notification_response(|response, cx| {
|
||||
cx.dismiss_system_notification(&response.tag);
|
||||
cx.dismiss_system_notification(&response.tag).detach();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -579,8 +579,12 @@ pub trait Platform: 'static {
|
||||
///
|
||||
/// Best-effort: some platforms cannot retract a notification once shown,
|
||||
/// in which case it ages out of the notification center on its own.
|
||||
fn dismiss_system_notification(&self, tag: &str) {
|
||||
/// The task completes after the platform calls return, not after any
|
||||
/// asynchronous work inside the operating system. Dropping it does not
|
||||
/// cancel dismissal.
|
||||
fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
|
||||
_ = tag;
|
||||
Task::ready(())
|
||||
}
|
||||
|
||||
/// Registers the callback invoked when the user activates a system
|
||||
|
||||
@@ -735,7 +735,7 @@ impl Platform for TestPlatform {
|
||||
system_notifications.shown.push(notification);
|
||||
}
|
||||
|
||||
fn dismiss_system_notification(&self, tag: &str) {
|
||||
fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
|
||||
let mut system_notifications = self.system_notifications.borrow_mut();
|
||||
system_notifications
|
||||
.delivered
|
||||
@@ -743,6 +743,7 @@ impl Platform for TestPlatform {
|
||||
system_notifications
|
||||
.dismissed
|
||||
.push(SharedString::from(tag.to_string()));
|
||||
Task::ready(())
|
||||
}
|
||||
|
||||
fn on_system_notification_response(
|
||||
|
||||
@@ -1005,8 +1005,9 @@ impl Platform for LinuxPlatform {
|
||||
});
|
||||
}
|
||||
|
||||
fn dismiss_system_notification(&self, tag: &str) {
|
||||
fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
|
||||
self.with_common(|common| common.system_notifications.dismiss(tag));
|
||||
Task::ready(())
|
||||
}
|
||||
|
||||
fn on_system_notification_response(
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::{
|
||||
AppleActivity, AppleDispatcher, BoolExt, MacDisplay, MacKeyboardLayout, MacKeyboardMapper,
|
||||
MacWindow, events::key_to_menu_equivalent, main_thread_marker, ns_string,
|
||||
pasteboard::Pasteboard, renderer, set_active_window_cursor_style,
|
||||
system_notifications::NotificationCommand,
|
||||
};
|
||||
use anyhow::{Context as _, anyhow};
|
||||
use block2::RcBlock;
|
||||
@@ -1128,14 +1129,27 @@ impl Platform for MacPlatform {
|
||||
|
||||
fn show_system_notification(&self, notification: gpui::SystemNotification) {
|
||||
let mut state = self.0.lock();
|
||||
let executor = state.foreground_executor.clone();
|
||||
state.system_notifications.show(&executor, notification);
|
||||
let foreground_executor = state.foreground_executor.clone();
|
||||
let background_executor = state.background_executor.clone();
|
||||
state
|
||||
.system_notifications
|
||||
.send(
|
||||
&foreground_executor,
|
||||
&background_executor,
|
||||
NotificationCommand::Show(notification),
|
||||
)
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn dismiss_system_notification(&self, tag: &str) {
|
||||
fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
|
||||
let mut state = self.0.lock();
|
||||
let executor = state.foreground_executor.clone();
|
||||
state.system_notifications.dismiss(&executor, tag);
|
||||
let foreground_executor = state.foreground_executor.clone();
|
||||
let background_executor = state.background_executor.clone();
|
||||
state.system_notifications.send(
|
||||
&foreground_executor,
|
||||
&background_executor,
|
||||
NotificationCommand::Dismiss(gpui::SharedString::from(tag.to_owned())),
|
||||
)
|
||||
}
|
||||
|
||||
fn on_system_notification_response(
|
||||
|
||||
@@ -4,19 +4,24 @@
|
||||
//! so nothing can trigger the authorization prompt or the framework's
|
||||
//! not-in-a-bundle abort) until the application posts a notification or
|
||||
//! registers a response callback.
|
||||
//!
|
||||
//! Notification-center calls can synchronously wait for the macOS service.
|
||||
//! A single worker owns the center so those waits never block the UI, while
|
||||
//! preserving the order of posting and dismissing notifications.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
use block2::RcBlock;
|
||||
use futures::StreamExt as _;
|
||||
use futures::channel::mpsc;
|
||||
use futures::channel::{mpsc, oneshot};
|
||||
use gpui::{
|
||||
ForegroundExecutor, SharedString, SystemNotification, SystemNotificationAction,
|
||||
SystemNotificationResponse, Task,
|
||||
BackgroundExecutor, ForegroundExecutor, SharedString, SystemNotification,
|
||||
SystemNotificationAction, SystemNotificationResponse, Task,
|
||||
};
|
||||
use objc2::rc::Retained;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{Bool, ProtocolObject};
|
||||
use objc2::{AnyThread, DefinedClass, define_class, msg_send};
|
||||
use objc2_foundation::{NSArray, NSBundle, NSError, NSObject, NSObjectProtocol, NSSet, NSString};
|
||||
@@ -30,10 +35,19 @@ use objc2_user_notifications::{
|
||||
|
||||
type ResponseCallback = Rc<RefCell<Option<Box<dyn FnMut(SystemNotificationResponse)>>>>;
|
||||
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
pub(crate) enum NotificationCommand {
|
||||
Show(SystemNotification),
|
||||
Dismiss(SharedString),
|
||||
}
|
||||
|
||||
pub(crate) struct SystemNotificationState {
|
||||
initialized: bool,
|
||||
center: Option<NotificationCenter>,
|
||||
commands: Option<Sender<(NotificationCommand, oneshot::Sender<()>)>>,
|
||||
callback: ResponseCallback,
|
||||
/// The center's `delegate` property is weak; keeping the delegate retained
|
||||
/// here keeps response handling alive for the app's lifetime.
|
||||
_delegate: Option<Retained<NotificationResponseDelegate>>,
|
||||
_response_task: Option<Task<()>>,
|
||||
}
|
||||
|
||||
@@ -41,24 +55,35 @@ impl SystemNotificationState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
initialized: false,
|
||||
center: None,
|
||||
commands: None,
|
||||
callback: Rc::new(RefCell::new(None)),
|
||||
_delegate: None,
|
||||
_response_task: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn show(&mut self, executor: &ForegroundExecutor, notification: SystemNotification) {
|
||||
self.initialize(executor);
|
||||
if let Some(center) = &self.center {
|
||||
center.show(notification);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dismiss(&mut self, executor: &ForegroundExecutor, tag: &str) {
|
||||
self.initialize(executor);
|
||||
if let Some(center) = &self.center {
|
||||
center.dismiss(tag);
|
||||
pub(crate) fn send(
|
||||
&mut self,
|
||||
foreground_executor: &ForegroundExecutor,
|
||||
background_executor: &BackgroundExecutor,
|
||||
command: NotificationCommand,
|
||||
) -> Task<()> {
|
||||
self.initialize(foreground_executor);
|
||||
let Some(commands) = &self.commands else {
|
||||
return Task::ready(());
|
||||
};
|
||||
let (completed, completion) = oneshot::channel();
|
||||
if let Err(error) = commands.send((command, completed)) {
|
||||
log::error!("system notification worker disconnected: {error}");
|
||||
return Task::ready(());
|
||||
}
|
||||
background_executor.spawn(async move {
|
||||
if let Err(error) = completion.await {
|
||||
log::error!(
|
||||
"system notification worker stopped before completing a command: {error}"
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn on_response(
|
||||
@@ -76,12 +101,46 @@ impl SystemNotificationState {
|
||||
}
|
||||
self.initialized = true;
|
||||
|
||||
let (sender, mut receiver) = mpsc::unbounded();
|
||||
self.center = NotificationCenter::new(sender);
|
||||
if self.center.is_none() {
|
||||
// UserNotifications aborts outside an app bundle. Checking the bundle
|
||||
// does not contact the notification service.
|
||||
if NSBundle::mainBundle().bundleIdentifier().is_none() {
|
||||
log::info!("system notifications disabled: not running from an app bundle");
|
||||
return;
|
||||
}
|
||||
|
||||
let (sender, mut receiver) = mpsc::unbounded();
|
||||
// Install the delegate before returning so a response delivered right
|
||||
// after registration (e.g. the click that launched the app) has
|
||||
// somewhere to go. Setting the delegate doesn't wait on the
|
||||
// notification service, unlike the calls handled by the worker.
|
||||
let delegate = autoreleasepool(|_| {
|
||||
let delegate = NotificationResponseDelegate::new(sender);
|
||||
UNUserNotificationCenter::currentNotificationCenter()
|
||||
.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
delegate
|
||||
});
|
||||
self._delegate = Some(delegate);
|
||||
|
||||
let (commands, pending_commands) = channel::<(NotificationCommand, oneshot::Sender<()>)>();
|
||||
let worker = std::thread::Builder::new()
|
||||
.name("system-notifications".into())
|
||||
.spawn(move || {
|
||||
let mut center = autoreleasepool(|_| NotificationCenter::new());
|
||||
for (command, completed) in pending_commands {
|
||||
autoreleasepool(|_| match command {
|
||||
NotificationCommand::Show(notification) => center.show(notification),
|
||||
NotificationCommand::Dismiss(tag) => center.dismiss(&tag),
|
||||
});
|
||||
// The caller may stop waiting without cancelling the operation.
|
||||
_ = completed.send(());
|
||||
}
|
||||
});
|
||||
if let Err(error) = worker {
|
||||
log::error!("failed to start system notification worker: {error}");
|
||||
return;
|
||||
}
|
||||
self.commands = Some(commands);
|
||||
|
||||
// Responses arrive from the delegate on an arbitrary thread; this task
|
||||
// hands them to the registered callback on the main thread.
|
||||
let callback = self.callback.clone();
|
||||
@@ -102,46 +161,28 @@ impl SystemNotificationState {
|
||||
|
||||
struct NotificationCenter {
|
||||
center: Retained<UNUserNotificationCenter>,
|
||||
/// The center's `delegate` property is weak; keeping the delegate retained
|
||||
/// here keeps response handling alive for the app's lifetime.
|
||||
_delegate: Retained<NotificationResponseDelegate>,
|
||||
/// The union of every action set registered so far. Categories are shared
|
||||
/// by notifications with identical actions because macOS replaces the
|
||||
/// entire registered set whenever a category is added.
|
||||
categories: RefCell<
|
||||
categories:
|
||||
HashMap<Vec<SystemNotificationAction>, (SharedString, Retained<UNNotificationCategory>)>,
|
||||
>,
|
||||
authorization_requested: Cell<bool>,
|
||||
authorization_requested: bool,
|
||||
}
|
||||
|
||||
impl NotificationCenter {
|
||||
fn new(sender: mpsc::UnboundedSender<SystemNotificationResponse>) -> Option<Self> {
|
||||
// `UNUserNotificationCenter` raises `NSInternalInconsistencyException`
|
||||
// ("bundleProxyForCurrentProcess is nil"), aborting the process, when
|
||||
// the binary isn't part of an app bundle — which is how dev builds run
|
||||
// via `cargo run`. A bundle identifier is only present when launched
|
||||
// from a real `.app`, so use it as the guard.
|
||||
if NSBundle::mainBundle().bundleIdentifier().is_none() {
|
||||
log::info!("system notifications disabled: not running from an app bundle");
|
||||
return None;
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
center: UNUserNotificationCenter::currentNotificationCenter(),
|
||||
categories: HashMap::new(),
|
||||
authorization_requested: false,
|
||||
}
|
||||
|
||||
let center = UNUserNotificationCenter::currentNotificationCenter();
|
||||
let delegate = NotificationResponseDelegate::new(sender);
|
||||
center.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
|
||||
Some(Self {
|
||||
center,
|
||||
_delegate: delegate,
|
||||
categories: RefCell::new(HashMap::new()),
|
||||
authorization_requested: Cell::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
fn request_authorization(&self) {
|
||||
if self.authorization_requested.replace(true) {
|
||||
fn request_authorization(&mut self) {
|
||||
if self.authorization_requested {
|
||||
return;
|
||||
}
|
||||
self.authorization_requested = true;
|
||||
let completion = RcBlock::new(|granted: Bool, error: *mut NSError| {
|
||||
// SAFETY: when non-null, `error` is a valid `NSError` for the
|
||||
// duration of the callback.
|
||||
@@ -161,7 +202,7 @@ impl NotificationCenter {
|
||||
);
|
||||
}
|
||||
|
||||
fn show(&self, notification: SystemNotification) {
|
||||
fn show(&mut self, notification: SystemNotification) {
|
||||
self.request_authorization();
|
||||
|
||||
let content = UNMutableNotificationContent::new();
|
||||
@@ -194,14 +235,15 @@ impl NotificationCenter {
|
||||
.addNotificationRequest_withCompletionHandler(&request, Some(&completion));
|
||||
}
|
||||
|
||||
fn register_category(&self, actions: &[SystemNotificationAction]) -> SharedString {
|
||||
let mut categories = self.categories.borrow_mut();
|
||||
if let Some((identifier, _category)) = categories.get(actions) {
|
||||
fn register_category(&mut self, actions: &[SystemNotificationAction]) -> SharedString {
|
||||
if let Some((identifier, _category)) = self.categories.get(actions) {
|
||||
return identifier.clone();
|
||||
}
|
||||
|
||||
let identifier =
|
||||
SharedString::from(format!("gpui-system-notification-{}", categories.len()));
|
||||
let identifier = SharedString::from(format!(
|
||||
"gpui-system-notification-{}",
|
||||
self.categories.len()
|
||||
));
|
||||
let platform_actions: Vec<Retained<UNNotificationAction>> = actions
|
||||
.iter()
|
||||
.map(|action| {
|
||||
@@ -220,8 +262,10 @@ impl NotificationCenter {
|
||||
UNNotificationCategoryOptions::empty(),
|
||||
);
|
||||
|
||||
categories.insert(actions.to_vec(), (identifier.clone(), category));
|
||||
let all: Vec<Retained<UNNotificationCategory>> = categories
|
||||
self.categories
|
||||
.insert(actions.to_vec(), (identifier.clone(), category));
|
||||
let all: Vec<Retained<UNNotificationCategory>> = self
|
||||
.categories
|
||||
.values()
|
||||
.map(|(_identifier, category)| category.clone())
|
||||
.collect();
|
||||
@@ -307,3 +351,65 @@ impl NotificationResponseDelegate {
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::FutureExt as _;
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_notification_commands_do_not_wait_for_the_service(cx: &mut gpui::TestAppContext) {
|
||||
let (sender, receiver) = channel();
|
||||
let mut state = SystemNotificationState {
|
||||
initialized: true,
|
||||
commands: Some(sender),
|
||||
..SystemNotificationState::new()
|
||||
};
|
||||
let notification = SystemNotification {
|
||||
tag: "thread".into(),
|
||||
title: "Finished".into(),
|
||||
body: "Ready for input".into(),
|
||||
actions: vec![],
|
||||
};
|
||||
|
||||
// No service consumes commands until after every UI call has returned.
|
||||
let mut tasks = [
|
||||
state.send(
|
||||
&cx.foreground_executor,
|
||||
&cx.background_executor,
|
||||
NotificationCommand::Show(notification.clone()),
|
||||
),
|
||||
state.send(
|
||||
&cx.foreground_executor,
|
||||
&cx.background_executor,
|
||||
NotificationCommand::Dismiss("thread".into()),
|
||||
),
|
||||
state.send(
|
||||
&cx.foreground_executor,
|
||||
&cx.background_executor,
|
||||
NotificationCommand::Show(notification.clone()),
|
||||
),
|
||||
];
|
||||
for task in &mut tasks {
|
||||
assert!(task.now_or_never().is_none());
|
||||
}
|
||||
|
||||
let (commands, completions): (Vec<_>, Vec<_>) = receiver.try_iter().unzip();
|
||||
assert_eq!(
|
||||
commands,
|
||||
vec![
|
||||
NotificationCommand::Show(notification.clone()),
|
||||
NotificationCommand::Dismiss("thread".into()),
|
||||
NotificationCommand::Show(notification),
|
||||
]
|
||||
);
|
||||
for completed in completions {
|
||||
completed
|
||||
.send(())
|
||||
.expect("caller is waiting for completion");
|
||||
}
|
||||
for task in tasks {
|
||||
task.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -927,8 +927,9 @@ impl Platform for WindowsPlatform {
|
||||
.log_err();
|
||||
}
|
||||
|
||||
fn dismiss_system_notification(&self, tag: &str) {
|
||||
fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
|
||||
self.system_notifications.borrow_mut().dismiss(tag);
|
||||
Task::ready(())
|
||||
}
|
||||
|
||||
fn on_system_notification_response(
|
||||
|
||||
Reference in New Issue
Block a user