Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(desktop): restore macOS notification delivery (#7978)

Eric Hayes00a71cd7d651
diff --git a/apps/web/src/components/app/AppProviders.tsx b/apps/web/src/components/app/AppProviders.tsx
index cd57d1475a..079e63c411 100644
--- a/apps/web/src/components/app/AppProviders.tsx
+++ b/apps/web/src/components/app/AppProviders.tsx
@@ -4,10 +4,12 @@ import { SearchProvider } from '@app/features/soup/search/context';
import { useCalendarCache } from '@app/lib/queries/calendar/graphql/use-calendar-cache';
import { useInvalidateQueriesOnReconnect } from '@app/lib/queries/invalidate-on-reconnect';
import { useSoupBackfills } from '@app/lib/queries/soup/backfill';
+import { MacOSNotificationUpdateRequiredError } from '@app/lib/tauri/notification';
import { globalSplitManager } from '@app/signal/splitLayout';
import { GlobalAppStateProvider } from '@components/app/GlobalAppState';
import { useReactiveFavicon } from '@components/app/useReactiveFavicon';
import { useGlobalAttachableHistory } from '@core/component/AI/signal/globalAttachments';
+import { toast } from '@core/component/Toast/Toast';
import { TeamContextProvider } from '@core/context/team';
import { useUserId } from '@core/context/user';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
@@ -40,19 +42,31 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {
useInvalidateQueriesOnReconnect();
}
- const onNotification = (notification: UnifiedNotification) => {
+ let notificationUpdatePrompted = false;
+ async function deliverNotification(notification: UnifiedNotification) {
if (notifInterface === 'not-supported') return;
const layoutManager = globalSplitManager();
if (!layoutManager) return;
- maybeHandlePlatformNotification(
- notification,
- notifInterface,
- layoutManager
- );
- };
+ try {
+ await maybeHandlePlatformNotification(
+ notification,
+ notifInterface,
+ layoutManager
+ );
+ } catch (error) {
+ console.error('Failed to deliver platform notification', error);
+ if (
+ error instanceof MacOSNotificationUpdateRequiredError &&
+ !notificationUpdatePrompted
+ ) {
+ notificationUpdatePrompted = true;
+ toast.failure(error.message);
+ }
+ }
+ }
const notificationSource = createNotificationSource(
connectionGatewayWebsocket,
- onNotification
+ (notification) => void deliverNotification(notification)
);
useNotificationUpdates(notificationSource);
useReactiveFavicon(notificationSource);
diff --git a/apps/web/src/lib/tauri/notification.test.ts b/apps/web/src/lib/tauri/notification.test.ts
new file mode 100644
index 0000000000..06573eec2a
--- /dev/null
+++ b/apps/web/src/lib/tauri/notification.test.ts
@@ -0,0 +1,195 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createTauriNotificationInterface,
+ MacOSNotificationUpdateRequiredError,
+} from './notification';
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn<(command: string, args?: unknown) => Promise<unknown>>(),
+ osType: vi.fn(() => 'macos'),
+ isPermissionGranted: vi.fn(async () => true),
+ requestPermission: vi.fn(async () => 'granted'),
+ sendNotification: vi.fn(),
+}));
+
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }));
+vi.mock('@tauri-apps/plugin-os', () => ({ type: mocks.osType }));
+vi.mock('@tauri-apps/plugin-notification', () => ({
+ isPermissionGranted: mocks.isPermissionGranted,
+ requestPermission: mocks.requestPermission,
+ sendNotification: mocks.sendNotification,
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((finish) => {
+ resolve = finish;
+ });
+ return { promise, resolve };
+}
+
+const notification = {
+ title: 'New message',
+ options: { body: 'A teammate mentioned you', icon: 'macro-icon.svg' },
+};
+
+describe('desktop notification delivery', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.osType.mockReturnValue('macos');
+ mocks.isPermissionGranted.mockResolvedValue(true);
+ mocks.requestPermission.mockResolvedValue('granted');
+ mocks.invoke.mockImplementation(async (command) => {
+ if (command === 'get_macos_notification_permission') return 'granted';
+ });
+ });
+
+ it('sends macOS notifications through the modern native command and awaits acceptance', async () => {
+ const acceptance = deferred<void>();
+ mocks.invoke.mockImplementation(async (command) => {
+ if (command === 'get_macos_notification_permission') return 'granted';
+ return acceptance.promise;
+ });
+ const adapter = createTauriNotificationInterface(vi.fn());
+ let completed = false;
+ async function deliver() {
+ const result = await adapter.showNotification(notification);
+ completed = true;
+ return result;
+ }
+ const delivery = deliver();
+
+ await vi.waitFor(() => {
+ expect(mocks.invoke).toHaveBeenCalledWith('send_macos_notification', {
+ title: notification.title,
+ body: notification.options.body,
+ });
+ });
+ expect(completed).toBe(false);
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+
+ acceptance.resolve();
+ await expect(delivery).resolves.toEqual({
+ onClick: expect.any(Function),
+ onDismiss: expect.any(Function),
+ close: expect.any(Function),
+ });
+ expect(completed).toBe(true);
+ });
+
+ it('supports a title without a body on macOS', async () => {
+ const adapter = createTauriNotificationInterface(vi.fn());
+ await adapter.showNotification({ title: 'Reminder' });
+ expect(mocks.invoke).toHaveBeenCalledWith('send_macos_notification', {
+ title: 'Reminder',
+ body: undefined,
+ });
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ });
+
+ it.each(['default', 'denied'])(
+ 'does not send when macOS permission is %s',
+ async (permission) => {
+ mocks.invoke.mockResolvedValue(permission);
+ const adapter = createTauriNotificationInterface(vi.fn());
+ await expect(adapter.showNotification(notification)).resolves.toBe(
+ 'not-granted'
+ );
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith(
+ 'get_macos_notification_permission'
+ );
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ }
+ );
+
+ it('rechecks the in-app preference after the OS permission read completes', async () => {
+ const permission = deferred<NotificationPermission>();
+ mocks.invoke.mockReturnValue(permission.promise);
+ let enabled = true;
+ const adapter = createTauriNotificationInterface(vi.fn(), () => enabled);
+ const delivery = adapter.showNotification(notification);
+ enabled = false;
+ permission.resolve('granted');
+
+ await expect(delivery).resolves.toBe('not-granted');
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith(
+ 'get_macos_notification_permission'
+ );
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ });
+
+ it('propagates native delivery failures without using the legacy sender', async () => {
+ const failure = new Error('Notifications are not allowed');
+ mocks.invoke
+ .mockResolvedValueOnce('granted')
+ .mockRejectedValueOnce(failure);
+ const adapter = createTauriNotificationInterface(vi.fn());
+
+ await expect(adapter.showNotification(notification)).rejects.toBe(failure);
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ });
+
+ it('requires an app update when an older native build has no modern sender', async () => {
+ const missingCommand = 'Command send_macos_notification not found';
+ mocks.invoke
+ .mockResolvedValueOnce('granted')
+ .mockRejectedValueOnce(missingCommand);
+ const adapter = createTauriNotificationInterface(vi.fn());
+
+ await expect(adapter.showNotification(notification)).rejects.toEqual(
+ new MacOSNotificationUpdateRequiredError(missingCommand)
+ );
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ });
+
+ it('never downgrades macOS delivery when an older build also lacks permission commands', async () => {
+ mocks.invoke
+ .mockRejectedValueOnce(
+ 'Command get_macos_notification_permission not found'
+ )
+ .mockRejectedValueOnce('Command send_macos_notification not found');
+ const adapter = createTauriNotificationInterface(vi.fn());
+
+ await expect(adapter.showNotification(notification)).rejects.toThrow(
+ 'Update Macro to receive desktop notifications.'
+ );
+ expect(mocks.isPermissionGranted).toHaveBeenCalledOnce();
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ });
+
+ it('does not dispatch when reading macOS authorization fails', async () => {
+ const failure = new Error('Permission callback was dropped');
+ mocks.invoke.mockRejectedValue(failure);
+ const adapter = createTauriNotificationInterface(vi.fn());
+
+ await expect(adapter.showNotification(notification)).rejects.toBe(failure);
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith(
+ 'get_macos_notification_permission'
+ );
+ expect(mocks.sendNotification).not.toHaveBeenCalled();
+ });
+
+ it.each(['windows', 'linux', 'ios', 'android'])(
+ 'preserves plugin delivery on %s',
+ async (os) => {
+ mocks.osType.mockReturnValue(os);
+ const adapter = createTauriNotificationInterface(vi.fn());
+ await adapter.showNotification(notification);
+
+ expect(mocks.invoke).not.toHaveBeenCalled();
+ expect(mocks.sendNotification).toHaveBeenCalledExactlyOnceWith({
+ title: notification.title,
+ body: notification.options.body,
+ icon: notification.options.icon,
+ extra: {},
+ });
+ }
+ );
+
+ it('preserves the title-only plugin call on other platforms', async () => {
+ mocks.osType.mockReturnValue('windows');
+ const adapter = createTauriNotificationInterface(vi.fn());
+ await adapter.showNotification({ title: 'Reminder' });
+ expect(mocks.sendNotification).toHaveBeenCalledExactlyOnceWith('Reminder');
+ });
+});
diff --git a/apps/web/src/lib/tauri/notification.ts b/apps/web/src/lib/tauri/notification.ts
index 4e0d14d9ba..31a25ad6ff 100644
--- a/apps/web/src/lib/tauri/notification.ts
+++ b/apps/web/src/lib/tauri/notification.ts
@@ -10,11 +10,19 @@ import {
} from '@tauri-apps/plugin-notification';
import { type as osType } from '@tauri-apps/plugin-os';
+export class MacOSNotificationUpdateRequiredError extends Error {
+ constructor(cause: unknown) {
+ super('Update Macro to receive desktop notifications.', { cause });
+ this.name = 'MacOSNotificationUpdateRequiredError';
+ }
+}
+
export function createTauriNotificationInterface(
setDisabled: () => Promise<void>,
shouldSend: () => boolean = () => true
): PlatformNotificationInterface {
- let hasMacOSPermissionCommands = osType() === 'macos';
+ const isMacOS = osType() === 'macos';
+ let hasMacOSPermissionCommands = isMacOS;
async function getCur(): Promise<NotificationPermission> {
// The notification plugin always reports permission as granted on desktop.
@@ -61,6 +69,23 @@ export function createTauriNotificationInterface(
return 'not-granted';
}
+ if (isMacOS) {
+ try {
+ await invoke<void>('send_macos_notification', {
+ title: data.title,
+ body: data.options?.body,
+ });
+ } catch (error) {
+ // OTA frontend updates can reach an older native app. Its legacy
+ // sender silently drops notifications, so require a native update.
+ if (error === 'Command send_macos_notification not found') {
+ throw new MacOSNotificationUpdateRequiredError(error);
+ }
+ throw error;
+ }
+ return createTauriNotification();
+ }
+
if (!data.options) {
sendNotification(data.title);
return createTauriNotification();
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index 4934bff208..4bc51537c6 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -88,7 +88,10 @@ objc2-foundation = { version = "0.3", default-features = false, features = [
objc2-user-notifications = { version = "0.3", default-features = false, features = [
"std",
"block2",
+ "UNNotificationContent",
+ "UNNotificationRequest",
"UNNotificationSettings",
+ "UNNotificationTrigger",
"UNUserNotificationCenter",
] }
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 25f138fed9..b62118d230 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -178,6 +178,14 @@ Deploy the updated native_app_service before publishing schema 3 archives;
an old server returns the legacy minimum and the client rejects the mismatch.
Never lower a minimum to force an incompatible update to apply.
+macOS notification delivery requires `send_macos_notification`, which uses
+UserNotifications for both authorization and delivery. Ship a full macOS native
+release containing this command; a frontend-only update cannot repair the legacy
+sender. Before publishing this frontend in a desktop OTA archive, set
+`MIN_NATIVE_BUILD` to the first native release containing the command. Older
+binaries show an update-required notice instead of falling back to the legacy
+notification API, which macOS rejects after UserNotifications has been used.
+
Extraction writes a sibling `<directory>.complete` record only after checksum,
extraction, manifest, and entrypoint validation succeed. Directories without a
matching completion record cannot be reused or restored. Previously cached OTA
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 4ec96a071f..dffdffda41 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -280,6 +280,8 @@ pub fn run() {
macos_notification_permission::get_macos_notification_permission,
#[cfg(target_os = "macos")]
macos_notification_permission::request_macos_notification_permission,
+ #[cfg(target_os = "macos")]
+ macos_notification_permission::send_macos_notification,
graphql_cache_plugin::commands::graphql_cache_init,
graphql_cache_plugin::commands::graphql_cache_init_with_schema,
graphql_cache_plugin::commands::graphql_cache_current_revision,
diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
index c956e955ae..dbe02f09ab 100644
--- a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
@@ -1,19 +1,23 @@
-//! Read and request this app's notification authorization from macOS.
+//! Authorize and deliver this app's notifications through macOS UserNotifications.
//!
//! The cross-platform notification plugin always reports permission granted on
-//! desktop. Its delivery transport remains in use; these commands provide the
-//! actual system permission without prompting during a permission read.
+//! desktop and delivers through the legacy NSUserNotificationCenter API. macOS
+//! rejects legacy delivery after this app has connected to UserNotifications,
+//! so permission reads, authorization, and delivery must all use the modern API.
-use std::ptr::NonNull;
+use std::{fmt, ptr::NonNull};
use block2::RcBlock;
+use objc2::rc::Retained;
use objc2::runtime::Bool;
-use objc2_foundation::{NSBundle, NSError};
+use objc2_foundation::{NSBundle, NSError, NSString};
use objc2_user_notifications::{
- UNAuthorizationOptions, UNAuthorizationStatus, UNNotificationSettings, UNUserNotificationCenter,
+ UNAuthorizationOptions, UNAuthorizationStatus, UNMutableNotificationContent,
+ UNNotificationRequest, UNNotificationSettings, UNUserNotificationCenter,
};
use serde::{Serialize, Serializer};
use tokio::sync::mpsc;
+use uuid::Uuid;
#[cfg(test)]
mod test;
@@ -27,33 +31,58 @@ pub enum NotificationPermission {
}
#[derive(Debug, thiserror::Error)]
-pub enum NotificationPermissionError {
- #[error("macOS notification permissions require an application bundle; use the installed app")]
+pub enum NotificationError {
+ #[error("macOS notifications require an application bundle; use the installed app")]
MissingBundleIdentifier,
- #[error("macOS notification permission callback was dropped")]
+ #[error("macOS notification callback was dropped")]
CallbackDropped,
- #[error("macOS notification authorization failed ({domain} {code}): {description}")]
+ #[error("macOS notification {operation} failed ({domain} {code}): {description}")]
Native {
+ operation: NotificationOperation,
domain: String,
code: isize,
description: String,
},
}
-fn ensure_application_bundle() -> Result<(), NotificationPermissionError> {
+#[derive(Debug)]
+pub enum NotificationOperation {
+ Authorization,
+ Delivery,
+}
+
+impl fmt::Display for NotificationOperation {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(match self {
+ Self::Authorization => "authorization",
+ Self::Delivery => "delivery",
+ })
+ }
+}
+
+fn ensure_application_bundle() -> Result<(), NotificationError> {
NSBundle::mainBundle()
.bundleIdentifier()
.filter(|identifier| !identifier.is_empty())
- .ok_or(NotificationPermissionError::MissingBundleIdentifier)?;
+ .ok_or(NotificationError::MissingBundleIdentifier)?;
Ok(())
}
-impl Serialize for NotificationPermissionError {
+impl Serialize for NotificationError {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
+fn native_error(operation: NotificationOperation, error: &NSError) -> NotificationError {
+ NotificationError::Native {
+ operation,
+ domain: error.domain().to_string(),
+ code: error.code(),
+ description: error.localizedDescription().to_string(),
+ }
+}
+
fn permission_from_status(status: UNAuthorizationStatus) -> NotificationPermission {
match status {
UNAuthorizationStatus::NotDetermined => NotificationPermission::Default,
@@ -66,8 +95,8 @@ fn permission_from_status(status: UNAuthorizationStatus) -> NotificationPermissi
}
#[tauri::command]
-pub async fn get_macos_notification_permission()
--> Result<NotificationPermission, NotificationPermissionError> {
+pub async fn get_macos_notification_permission() -> Result<NotificationPermission, NotificationError>
+{
// UserNotifications raises an Objective-C exception for unbundled dev/test
// executables. Fail explicitly before asking it to create a center.
ensure_application_bundle()?;
@@ -87,12 +116,12 @@ pub async fn get_macos_notification_permission()
receiver
.recv()
.await
- .ok_or(NotificationPermissionError::CallbackDropped)
+ .ok_or(NotificationError::CallbackDropped)
}
#[tauri::command]
pub async fn request_macos_notification_permission()
--> Result<NotificationPermission, NotificationPermissionError> {
+-> Result<NotificationPermission, NotificationError> {
ensure_application_bundle()?;
let (sender, mut receiver) = mpsc::channel(1);
{
@@ -100,11 +129,7 @@ pub async fn request_macos_notification_permission()
// SAFETY: the optional NSError belongs to macOS and remains valid
// during the callback. Copy its details before returning.
let result = match unsafe { error.as_ref() } {
- Some(error) => Err(NotificationPermissionError::Native {
- domain: error.domain().to_string(),
- code: error.code(),
- description: error.localizedDescription().to_string(),
- }),
+ Some(error) => Err(native_error(NotificationOperation::Authorization, error)),
None => Ok(if granted.as_bool() {
NotificationPermission::Granted
} else {
@@ -124,5 +149,44 @@ pub async fn request_macos_notification_permission()
receiver
.recv()
.await
- .ok_or(NotificationPermissionError::CallbackDropped)?
+ .ok_or(NotificationError::CallbackDropped)?
+}
+
+fn notification_request(title: &str, body: Option<&str>) -> Retained<UNNotificationRequest> {
+ let content = UNMutableNotificationContent::new();
+ content.setTitle(&NSString::from_str(title));
+ content.setBody(&NSString::from_str(body.unwrap_or_default()));
+ // Reusing an identifier would replace a previously delivered notification.
+ let identifier = NSString::from_str(&Uuid::new_v4().to_string());
+ UNNotificationRequest::requestWithIdentifier_content_trigger(&identifier, &content, None)
+}
+
+/// Deliver immediately through the same framework used for authorization.
+/// Completion means macOS accepted the request; system presentation settings
+/// still determine whether it appears as a banner.
+#[tauri::command]
+pub async fn send_macos_notification(
+ title: String,
+ body: Option<String>,
+) -> Result<(), NotificationError> {
+ ensure_application_bundle()?;
+ let (sender, mut receiver) = mpsc::channel(1);
+ {
+ let request = notification_request(&title, body.as_deref());
+ let callback = RcBlock::new(move |error: *mut NSError| {
+ // SAFETY: the optional NSError is valid for this completion handler.
+ // Copy its details before the native callback returns.
+ let result = match unsafe { error.as_ref() } {
+ Some(error) => Err(native_error(NotificationOperation::Delivery, error)),
+ None => Ok(()),
+ };
+ let _ = sender.try_send(result);
+ });
+ UNUserNotificationCenter::currentNotificationCenter()
+ .addNotificationRequest_withCompletionHandler(&request, Some(&callback));
+ }
+ receiver
+ .recv()
+ .await
+ .ok_or(NotificationError::CallbackDropped)?
}
diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs
index 0c901cb3c3..5c6e7b642e 100644
--- a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs
@@ -45,7 +45,8 @@ fn permission_values_match_the_frontend_notification_permission_contract() {
#[test]
fn native_authorization_errors_reach_the_frontend_with_their_details() {
- let error = NotificationPermissionError::Native {
+ let error = NotificationError::Native {
+ operation: NotificationOperation::Authorization,
domain: "UNErrorDomain".into(),
code: 1,
description: "Notifications are not allowed".into(),
@@ -55,3 +56,43 @@ fn native_authorization_errors_reach_the_frontend_with_their_details() {
"macOS notification authorization failed (UNErrorDomain 1): Notifications are not allowed"
);
}
+
+#[test]
+fn immediate_notifications_preserve_the_title_and_optional_body() {
+ let request = notification_request("Macro — new message", Some("Hello 👋\nSecond line"));
+ assert_eq!(request.content().title().to_string(), "Macro — new message");
+ assert_eq!(
+ request.content().body().to_string(),
+ "Hello 👋\nSecond line"
+ );
+ assert!(request.trigger().is_none());
+
+ let title_only = notification_request("Reminder", None);
+ assert_eq!(title_only.content().title().to_string(), "Reminder");
+ assert!(title_only.content().body().is_empty());
+}
+
+#[test]
+fn repeated_notifications_do_not_replace_each_other() {
+ let first = notification_request("Same title", None);
+ let second = notification_request("Same title", None);
+ assert_ne!(first.identifier(), second.identifier());
+ assert!(Uuid::parse_str(&first.identifier().to_string()).is_ok());
+}
+
+#[test]
+fn native_delivery_errors_reach_the_frontend_with_their_details() {
+ // SAFETY: no user-info dictionary is supplied, so its generic types cannot
+ // mismatch the native values.
+ let error = unsafe {
+ NSError::errorWithDomain_code_userInfo(&NSString::from_str("UNErrorDomain"), 1, None)
+ };
+ let result = native_error(NotificationOperation::Delivery, &error);
+ assert_eq!(
+ serde_json::to_value(result).unwrap(),
+ format!(
+ "macOS notification delivery failed (UNErrorDomain 1): {}",
+ error.localizedDescription()
+ )
+ );
+}