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(notifications): open macOS alerts at their destination (#8319)

Eric Hayes979e53e8b50f
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index a0ee70dbd0..dc9a49bd8e 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -163,6 +163,17 @@ Follow [`docs/ios-releases.md`](docs/ios-releases.md) for App Store signing and
provisioning, including both extensions. The release script temporarily selects
manual export when a distribution certificate path is supplied.
+## macOS notification activation
+
+Carry the notification ID through native delivery and the buffered `navigate`
+bridge, so clicks survive app restarts and wait for the split layout to be ready.
+Install and retain the UserNotifications delegate before the native event loop
+starts. Clicking restores and focuses the main window; receipt and dismissal do
+not navigate. Preserve iOS and Android `createPushApi` tap navigation when changing
+desktop delivery, including buffered launch taps before device registration.
+This requires a native macOS release; see the
+[notification walkthrough](../../docs/agent-guide/notifications.md).
+
## Desktop file drops
Keep `app.windows[].dragDropEnabled` false in `tauri/src-tauri/tauri.macos.conf.json`.
diff --git a/apps/web/src/features/notifications/notification-platform.ts b/apps/web/src/features/notifications/notification-platform.ts
index 7ab5c67026..5642c86b2c 100644
--- a/apps/web/src/features/notifications/notification-platform.ts
+++ b/apps/web/src/features/notifications/notification-platform.ts
@@ -29,6 +29,7 @@ export interface PlatformNotificationHandle {
export interface PlatformNotificationData {
title: string;
+ notificationId?: string;
options?: NotificationOptions;
}
@@ -138,9 +139,10 @@ export async function maybeHandlePlatformNotification(
);
if (platformNotificationData) {
- let notificationHandle = await notificationInterface.showNotification(
- platformNotificationData
- );
+ let notificationHandle = await notificationInterface.showNotification({
+ ...platformNotificationData,
+ notificationId: notification.id,
+ });
if (
notificationHandle !== 'not-granted' &&
notificationHandle !== 'disabled-in-ui'
diff --git a/apps/web/src/features/notifications/tests/notification-platform.test.ts b/apps/web/src/features/notifications/tests/notification-platform.test.ts
index 2cca8ce531..811bba9eb3 100644
--- a/apps/web/src/features/notifications/tests/notification-platform.test.ts
+++ b/apps/web/src/features/notifications/tests/notification-platform.test.ts
@@ -239,6 +239,7 @@ describe('maybeHandlePlatformNotification', () => {
expect(showNotification).toHaveBeenCalledWith(
expect.objectContaining({
title: 'Someone <General>',
+ notificationId: 'notification-1',
options: expect.objectContaining({
body: 'invited you to',
}),
diff --git a/apps/web/src/lib/tauri/PushNotification.test.tsx b/apps/web/src/lib/tauri/PushNotification.test.tsx
index 8233f06593..62a8d4c21b 100644
--- a/apps/web/src/lib/tauri/PushNotification.test.tsx
+++ b/apps/web/src/lib/tauri/PushNotification.test.tsx
@@ -1,12 +1,20 @@
+import {
+ pendingNotificationNavigationId,
+ setPendingNotificationNavigationId,
+} from '@notifications/notification-navigation-intent';
import { createRoot } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MaybePushNotificationRegistration } from './PushNotification';
+import type { PushEvent } from './push-api';
const registration = vi.hoisted(() => ({
os: 'android',
version: '16',
sync: undefined as (() => Promise<void>) | undefined,
register: vi.fn(async () => ({ isErr: () => false })),
+ receive: undefined as ((event: PushEvent) => void) | undefined,
+ buffered: undefined as PushEvent | undefined,
+ acknowledge: vi.fn(async (_deliveryId: string) => {}),
}));
vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLKIT: true }));
vi.mock('@core/util/platform', () => ({
@@ -37,9 +45,9 @@ vi.mock('@solid-primitives/storage', () => ({
vi.mock('@tauri-apps/plugin-notification', () => ({
removeAllActive: async () => {},
}));
-vi.mock('@notifications', () => ({
+vi.mock('@notifications', async () => ({
PlatformNotificationProvider: () => null,
- triggerNotificationNavigation: vi.fn(),
+ ...(await import('@notifications/notification-navigation-intent')),
}));
vi.mock('./TauriProvider', () => ({
useExpectTauri: () => ({ os: registration.os }),
@@ -52,8 +60,12 @@ vi.mock('./push-api', () => ({
checkPermissions: async () => ({ status: 'granted' }),
register: async () => ({ token: 'test-device-token' }),
configureRecipient: async () => {},
- watch: async () => {},
+ watch: async (callback: (event: PushEvent) => void) => {
+ registration.receive = callback;
+ if (registration.buffered) callback(registration.buffered);
+ },
unwatch: async () => {},
+ acknowledge: registration.acknowledge,
}),
}));
@@ -63,13 +75,100 @@ beforeEach(() => {
registration.version = '16';
registration.sync = undefined;
registration.register.mockClear();
+ registration.receive = undefined;
+ registration.buffered = undefined;
+ registration.acknowledge.mockClear();
+ setPendingNotificationNavigationId(undefined);
delete window.__MACRO_ANDROID_CALL_KIT__;
});
afterEach(() => {
dispose?.();
+ dispose = undefined;
+ setPendingNotificationNavigationId(undefined);
delete window.__MACRO_ANDROID_CALL_KIT__;
});
+describe.each(['ios', 'android'])('%s push notification navigation', (os) => {
+ beforeEach(() => {
+ registration.os = os;
+ });
+
+ it.each(['FOREGROUND_TAP', 'BACKGROUND_TAP'] as const)(
+ 'opens the tapped location for %s before device registration completes',
+ (type) => {
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ MaybePushNotificationRegistration({ children: null });
+ });
+ expect(registration.register).not.toHaveBeenCalled();
+ expect(registration.receive).toBeDefined();
+ registration.receive!({
+ type,
+ payload: { notificationId: 'mobile-notification' },
+ deliveryId: 'mobile-delivery',
+ });
+ expect(pendingNotificationNavigationId()).toBe('mobile-notification');
+ expect(registration.acknowledge).toHaveBeenCalledExactlyOnceWith(
+ 'mobile-delivery'
+ );
+ }
+ );
+
+ it('retains a launch tap replayed when the native listener attaches', () => {
+ registration.buffered = {
+ type: 'BACKGROUND_TAP',
+ payload: { notificationId: 'cold-start-notification' },
+ };
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ MaybePushNotificationRegistration({ children: null });
+ });
+ expect(pendingNotificationNavigationId()).toBe('cold-start-notification');
+ expect(registration.register).not.toHaveBeenCalled();
+ });
+
+ it.each(['FOREGROUND_DELIVERY', 'BACKGROUND_DELIVERY'] as const)(
+ 'does not navigate on %s',
+ (type) => {
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ MaybePushNotificationRegistration({ children: null });
+ });
+ registration.receive!({
+ type,
+ payload: { notificationId: 'received-notification' },
+ });
+ expect(pendingNotificationNavigationId()).toBeUndefined();
+ }
+ );
+
+ it.each<PushEvent['payload']>([{}, { notificationId: '' }])(
+ 'ignores a tap without a destination (%j)',
+ (payload) => {
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ MaybePushNotificationRegistration({ children: null });
+ });
+ registration.receive!({ type: 'BACKGROUND_TAP', payload });
+ expect(pendingNotificationNavigationId()).toBeUndefined();
+ }
+ );
+
+ it('ignores taps after the mobile registration provider is disposed', () => {
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ MaybePushNotificationRegistration({ children: null });
+ });
+ dispose?.();
+ dispose = undefined;
+ registration.receive!({
+ type: 'BACKGROUND_TAP',
+ payload: { notificationId: 'stale-notification' },
+ });
+ expect(pendingNotificationNavigationId()).toBeUndefined();
+ });
+});
+
describe('push registration native-call capability', () => {
it.each([
{ os: 'android', version: '16', binary: true, expected: true },
diff --git a/apps/web/src/lib/tauri/navigation.test.ts b/apps/web/src/lib/tauri/navigation.test.ts
index 3614e88c91..5e9e8a45f4 100644
--- a/apps/web/src/lib/tauri/navigation.test.ts
+++ b/apps/web/src/lib/tauri/navigation.test.ts
@@ -25,6 +25,10 @@ vi.mock('./macroLinkInterceptor', () => ({
}));
import { registerPipedreamCallback } from '@core/pipedream/connect-callback';
+import {
+ pendingNotificationNavigationId,
+ setPendingNotificationNavigationId,
+} from '@notifications/notification-navigation-intent';
import { useTauriNavigationEffect } from './navigation';
let dispose: (() => void) | undefined;
@@ -32,6 +36,7 @@ let receive: (event: { payload: { path: string; query: string } }) => void;
beforeEach(() => {
vi.clearAllMocks();
+ setPendingNotificationNavigationId(undefined);
mocks.platform = 'android';
mocks.invoke.mockResolvedValue(undefined);
mocks.listen.mockImplementation(async (_name, handler) => {
@@ -47,6 +52,42 @@ beforeEach(() => {
afterEach(() => dispose?.());
describe('native link session routing', () => {
+ it('queues a desktop notification click for navigation when the layout is ready', () => {
+ mocks.platform = 'macos';
+ receive({
+ payload: {
+ path: '/notification',
+ query:
+ 'notificationId=01a1561c-62b1-7ee4-99d5-1fa5988dbf5d&deliveryId=delivery',
+ },
+ });
+ expect(pendingNotificationNavigationId()).toBe(
+ '01a1561c-62b1-7ee4-99d5-1fa5988dbf5d'
+ );
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('uses the clicked notification rather than the most recently received one', () => {
+ setPendingNotificationNavigationId('newer-notification');
+ receive({
+ payload: {
+ path: '/notification',
+ query: 'notificationId=older-notification',
+ },
+ });
+ expect(pendingNotificationNavigationId()).toBe('older-notification');
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it.each(['', 'notificationId='])(
+ 'ignores notification links without a target (%s)',
+ (query) => {
+ receive({ payload: { path: '/notification', query } });
+ expect(pendingNotificationNavigationId()).toBeUndefined();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ }
+ );
+
it('completes a connector callback without navigating away from the active chat', () => {
const onEvent = vi.fn();
const { state } = registerPipedreamCallback(onEvent);
diff --git a/apps/web/src/lib/tauri/navigation.ts b/apps/web/src/lib/tauri/navigation.ts
index f1d910ea2a..458024f88c 100644
--- a/apps/web/src/lib/tauri/navigation.ts
+++ b/apps/web/src/lib/tauri/navigation.ts
@@ -2,6 +2,7 @@ import { handlePipedreamCallback } from '@core/pipedream/connect-callback';
import { getNativeMobilePlatform } from '@core/util/platform';
import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { Telemetry } from '@macro-inc/observability';
+import { triggerNotificationNavigation } from '@notifications/notification-navigation-intent';
import { useNavigate } from '@solidjs/router';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
@@ -27,6 +28,21 @@ export function useTauriNavigationEffect() {
async function inner() {
unsubscribe = await listen<NavigateEvent>('navigate', (ev) => {
if (handlePipedreamCallback(ev.payload.path, ev.payload.query)) return;
+ if (ev.payload.path === '/notification') {
+ const notificationId = new URLSearchParams(ev.payload.query).get(
+ 'notificationId'
+ );
+ if (notificationId) {
+ const span = Telemetry.span('notification.activate');
+ try {
+ span.setAttr('notification.id', notificationId);
+ span.run(() => triggerNotificationNavigation(notificationId));
+ } finally {
+ span.end();
+ }
+ }
+ return;
+ }
const path = ev.payload.query
? `${ev.payload.path}?${ev.payload.query}`
: ev.payload.path;
diff --git a/apps/web/src/lib/tauri/notification.test.ts b/apps/web/src/lib/tauri/notification.test.ts
index febd45bd3a..ed46626ed3 100644
--- a/apps/web/src/lib/tauri/notification.test.ts
+++ b/apps/web/src/lib/tauri/notification.test.ts
@@ -38,6 +38,7 @@ function deferred<T>() {
const notification = {
title: 'New message',
+ notificationId: '01a1561c-62b1-7ee4-99d5-1fa5988dbf5d',
options: { body: 'A teammate mentioned you', icon: 'macro-icon.svg' },
};
@@ -72,6 +73,7 @@ describe('desktop notification delivery', () => {
expect(mocks.invoke).toHaveBeenCalledWith('send_macos_notification', {
title: notification.title,
body: notification.options.body,
+ notificationId: notification.notificationId,
});
});
expect(completed).toBe(false);
@@ -92,6 +94,7 @@ describe('desktop notification delivery', () => {
expect(mocks.invoke).toHaveBeenCalledWith('send_macos_notification', {
title: 'Reminder',
body: undefined,
+ notificationId: undefined,
});
expect(mocks.sendNotification).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/lib/tauri/notification.ts b/apps/web/src/lib/tauri/notification.ts
index 322eae8606..ceebdfe136 100644
--- a/apps/web/src/lib/tauri/notification.ts
+++ b/apps/web/src/lib/tauri/notification.ts
@@ -72,6 +72,7 @@ export function createTauriNotificationInterface(
await invoke<void>('send_macos_notification', {
title: data.title,
body: data.options?.body,
+ notificationId: data.notificationId,
});
} catch (error) {
// OTA frontend updates can reach an older native app. Its legacy
@@ -81,7 +82,13 @@ export function createTauriNotificationInterface(
}
throw error;
}
- return createTauriNotification();
+ // Native activation carries the ID through the startup-safe navigation
+ // bridge. It also works after this webview (and its callbacks) is gone.
+ return {
+ onClick: () => {},
+ onDismiss: () => {},
+ close: () => {},
+ };
}
if (platform === 'linux') {
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index 94a360c09f..269d0284d0 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -95,6 +95,8 @@ objc2-foundation = { version = "0.3", default-features = false, features = [
objc2-user-notifications = { version = "0.3", default-features = false, features = [
"std",
"block2",
+ "UNNotification",
+ "UNNotificationResponse",
"UNNotificationContent",
"UNNotificationRequest",
"UNNotificationSettings",
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 805a224408..7aa0239c79 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -217,6 +217,18 @@ sender. Before publishing this frontend in a desktop OTA archive, set
binaries show an update-required notice instead of falling back to the legacy
notification API, which macOS rejects after UserNotifications has been used.
+macOS notification activation additionally requires the retained
+UserNotifications response delegate, installed before the event loop starts.
+`send_macos_notification` embeds the optional `notificationId` in each unique
+request identifier. A click restores/focuses the main window and sends the
+destination through the existing buffered deep-link bridge. The frontend queues
+it until notification navigation is ready, including on cold launch. Dismissal
+does not navigate. Ship this native change with the frontend and raise the macOS
+`MIN_NATIVE_BUILD` to that release before publishing an OTA archive; older native
+builds ignore the added ID and cannot navigate. Previously delivered alerts have
+no destination to recover. Verify the [notification walkthrough](../../../../docs/agent-guide/notifications.md)
+in an installed macOS bundle before release.
+
Linux notification activation requires `send_linux_notification` and
`close_linux_notification`. Ship a full native AppImage containing these commands;
a frontend-only update cannot add clickable system notifications. Before publishing
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index e5188c9beb..cf7614f044 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -296,7 +296,7 @@ pub fn run() {
"tauri://localhost"
};
- builder
+ let app = builder
.register_asynchronous_uri_scheme_protocol("tauri", {
// Build this outside the closure so we only create it once.
// We need the AppHandle which isn't available until setup, but
@@ -399,79 +399,81 @@ pub fn run() {
Ok(())
})
.build(context)
- .expect("error while building tauri application")
- .run(move |app_handle, event| match &event {
- RunEvent::Ready if !recording => {
- #[cfg(feature = "auto_apply_update")]
- {
- let app = app_handle.clone();
- tauri::async_runtime::spawn(async move {
- match apply_completed_update_from(&app, "run_event_ready").await {
- Ok(_) => {}
- Err(e) => {
- tracing::error!("Failed to auto-apply bundle update on ready: {e}");
- }
+ .expect("error while building tauri application");
+ // Install before the event loop finishes launching the app: macOS can
+ // deliver the notification response that launched it before setup runs.
+ #[cfg(target_os = "macos")]
+ macos_notification_permission::install_delegate(app.handle());
+ app.run(move |app_handle, event| match &event {
+ RunEvent::Ready if !recording => {
+ #[cfg(feature = "auto_apply_update")]
+ {
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ match apply_completed_update_from(&app, "run_event_ready").await {
+ Ok(_) => {}
+ Err(e) => {
+ tracing::error!("Failed to auto-apply bundle update on ready: {e}");
}
- });
- }
+ }
+ });
}
- // Tao 0.37 delivers mobile foreground transitions per window, not
- // through the top-level event-loop Resumed event or focus changes.
- #[cfg(mobile)]
- RunEvent::WindowEvent {
- label,
- event: tauri::WindowEvent::Resumed,
- ..
- } => {
- tracing::debug!(window_label = %label, "mobile window resumed");
+ }
+ // Tao 0.37 delivers mobile foreground transitions per window, not
+ // through the top-level event-loop Resumed event or focus changes.
+ #[cfg(mobile)]
+ RunEvent::WindowEvent {
+ label,
+ event: tauri::WindowEvent::Resumed,
+ ..
+ } => {
+ tracing::debug!(window_label = %label, "mobile window resumed");
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ if let Err(e) = retry_waiting_for_wifi(&app).await {
+ tracing::warn!("Failed to retry bundle update Wi-Fi wait on resume: {e}");
+ }
+ });
+ #[cfg(feature = "auto_apply_update")]
+ {
let app = app_handle.clone();
tauri::async_runtime::spawn(async move {
- if let Err(e) = retry_waiting_for_wifi(&app).await {
- tracing::warn!("Failed to retry bundle update Wi-Fi wait on resume: {e}");
+ if let Err(e) = allow_update_reload_retry(&app).await {
+ tracing::warn!("Failed to allow bundle update reload retry on resume: {e}");
}
- });
- #[cfg(feature = "auto_apply_update")]
- {
- let app = app_handle.clone();
- tauri::async_runtime::spawn(async move {
- if let Err(e) = allow_update_reload_retry(&app).await {
- tracing::warn!(
- "Failed to allow bundle update reload retry on resume: {e}"
- );
- }
- match apply_completed_update_from(&app, "run_event_resumed").await {
- Ok(true) => {}
- Ok(false) => {
- if let Err(e) = start_update_check(&app).await {
- tracing::error!(
- "Failed to start bundle update check on resume: {e}"
- );
- }
- }
- Err(e) => {
- tracing::error!("Failed to auto-apply bundle update: {e}");
+ match apply_completed_update_from(&app, "run_event_resumed").await {
+ Ok(true) => {}
+ Ok(false) => {
+ if let Err(e) = start_update_check(&app).await {
+ tracing::error!(
+ "Failed to start bundle update check on resume: {e}"
+ );
}
}
- });
- }
- }
- #[cfg(desktop)]
- RunEvent::ExitRequested { api, .. } => {
- window_state::save(app_handle);
- desktop_update::on_exit_requested(app_handle, api)
+ Err(e) => {
+ tracing::error!("Failed to auto-apply bundle update: {e}");
+ }
+ }
+ });
}
- RunEvent::Exit => {
- if let Some(state) = app_handle.try_state::<graphql_cache_plugin::CacheState>() {
- state
- .shutdown()
- .inspect_err(
- |error| tracing::error!(error=?error, "failed to close graphql cache"),
- )
- .ok();
- }
+ }
+ #[cfg(desktop)]
+ RunEvent::ExitRequested { api, .. } => {
+ window_state::save(app_handle);
+ desktop_update::on_exit_requested(app_handle, api)
+ }
+ RunEvent::Exit => {
+ if let Some(state) = app_handle.try_state::<graphql_cache_plugin::CacheState>() {
+ state
+ .shutdown()
+ .inspect_err(
+ |error| tracing::error!(error=?error, "failed to close graphql cache"),
+ )
+ .ok();
}
- _ => {}
- });
+ }
+ _ => {}
+ });
}
/// fn to merge the headers from the http cookie store into the initial
@@ -577,6 +579,28 @@ fn emit_navigate_for_deep_link(url: Url, handle: &AppHandle) -> Result<(), Repor
Ok(handle.emit("navigate", payload)?)
}
+fn deliver_deep_link(url: Url, handle: &AppHandle) {
+ let delivery = handle.state::<DeepLinkDelivery>();
+ let to_emit = {
+ let Ok(mut state) = delivery.launch.lock() else {
+ tracing::error!("deep link state mutex poisoned; dropping deep link");
+ return;
+ };
+ match &*state {
+ // Emitting now would be lost — hold the link for the flush.
+ LaunchState::NotReady | LaunchState::PendingNavigation(_) => {
+ tracing::trace!("frontend not ready; buffering deep link");
+ *state = LaunchState::PendingNavigation(url);
+ None
+ }
+ LaunchState::Ready => Some(url),
+ }
+ };
+ if let Some(url) = to_emit {
+ emit_navigate_for_deep_link(url, handle).log_and_consume();
+ }
+}
+
fn attach_deep_link_handler(app: &mut tauri::App) {
app.deep_link().on_open_url({
let handle = app.handle().clone();
@@ -590,25 +614,7 @@ fn attach_deep_link_handler(app: &mut tauri::App) {
return;
}
- let delivery = handle.state::<DeepLinkDelivery>();
- let to_emit = {
- let Ok(mut state) = delivery.launch.lock() else {
- tracing::error!("deep link state mutex poisoned; dropping deep link");
- return;
- };
- match &*state {
- // Emitting now would be lost — hold the link for the flush.
- LaunchState::NotReady | LaunchState::PendingNavigation(_) => {
- tracing::trace!("frontend not ready; buffering deep link");
- *state = LaunchState::PendingNavigation(url);
- None
- }
- LaunchState::Ready => Some(url),
- }
- };
- if let Some(url) = to_emit {
- emit_navigate_for_deep_link(url, &handle).log_and_consume();
- }
+ deliver_deep_link(url, &handle);
}
});
}
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 dbe02f09ab..1b4689ba5c 100644
--- a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
@@ -19,6 +19,9 @@ use serde::{Serialize, Serializer};
use tokio::sync::mpsc;
use uuid::Uuid;
+mod activation;
+pub use activation::install_delegate;
+
#[cfg(test)]
mod test;
@@ -152,12 +155,27 @@ pub async fn request_macos_notification_permission()
.ok_or(NotificationError::CallbackDropped)?
}
-fn notification_request(title: &str, body: Option<&str>) -> Retained<UNNotificationRequest> {
+fn notification_request(
+ title: &str,
+ body: Option<&str>,
+ notification_id: 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());
+ let delivery_id = Uuid::new_v4().to_string();
+ let identifier = match notification_id {
+ Some(notification_id) => {
+ let mut url =
+ url::Url::parse("macro:///notification").expect("static notification URL");
+ url.query_pairs_mut()
+ .append_pair("notificationId", notification_id)
+ .append_pair("deliveryId", &delivery_id);
+ NSString::from_str(url.as_str())
+ }
+ None => NSString::from_str(&delivery_id),
+ };
UNNotificationRequest::requestWithIdentifier_content_trigger(&identifier, &content, None)
}
@@ -168,11 +186,12 @@ fn notification_request(title: &str, body: Option<&str>) -> Retained<UNNotificat
pub async fn send_macos_notification(
title: String,
body: Option<String>,
+ notification_id: Option<String>,
) -> Result<(), NotificationError> {
ensure_application_bundle()?;
let (sender, mut receiver) = mpsc::channel(1);
{
- let request = notification_request(&title, body.as_deref());
+ let request = notification_request(&title, body.as_deref(), notification_id.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.
diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs
new file mode 100644
index 0000000000..ddb6c720da
--- /dev/null
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs
@@ -0,0 +1,119 @@
+//! macOS owns delivered notifications beyond the lifetime of a webview. Keep
+//! their navigation in the native response delegate and the deep-link bridge.
+
+use std::cell::RefCell;
+
+use block2::DynBlock;
+use objc2::rc::Retained;
+use objc2::runtime::ProtocolObject;
+use objc2::{AnyThread, DefinedClass, define_class, msg_send};
+use objc2_foundation::{NSObject, NSObjectProtocol};
+use objc2_user_notifications::{
+ UNNotification, UNNotificationDefaultActionIdentifier, UNNotificationPresentationOptions,
+ UNNotificationResponse, UNUserNotificationCenter, UNUserNotificationCenterDelegate,
+};
+use tauri::{AppHandle, Manager};
+use url::Url;
+
+thread_local! {
+ // UNUserNotificationCenter.delegate is weak. Retain it for the app lifetime
+ // on the setup thread; callbacks only access the thread-safe AppHandle.
+ static DELEGATE: RefCell<Option<Retained<NotificationDelegate>>> = const { RefCell::new(None) };
+}
+
+define_class!(
+ // SAFETY: NSObject imposes no subclassing requirements. The only ivar is a
+ // thread-safe AppHandle, and there is no custom Drop implementation.
+ #[unsafe(super = NSObject)]
+ #[ivars = AppHandle]
+ struct NotificationDelegate;
+
+ unsafe impl NSObjectProtocol for NotificationDelegate {}
+
+ // SAFETY: All methods match the UserNotifications protocol signatures.
+ unsafe impl UNUserNotificationCenterDelegate for NotificationDelegate {
+ #[unsafe(method(userNotificationCenter:willPresentNotification:withCompletionHandler:))]
+ fn will_present(
+ &self,
+ _center: &UNUserNotificationCenter,
+ _notification: &UNNotification,
+ completion: &DynBlock<dyn Fn(UNNotificationPresentationOptions)>,
+ ) {
+ completion.call((UNNotificationPresentationOptions::Banner
+ | UNNotificationPresentationOptions::List
+ | UNNotificationPresentationOptions::Sound,));
+ }
+
+ #[unsafe(method(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:))]
+ fn did_receive(
+ &self,
+ _center: &UNUserNotificationCenter,
+ response: &UNNotificationResponse,
+ completion: &DynBlock<dyn Fn()>,
+ ) {
+ // SAFETY: this immutable framework constant is available on every
+ // supported macOS version. Dismissal is never a navigation action.
+ if response.actionIdentifier().as_ref()
+ == unsafe { UNNotificationDefaultActionIdentifier }
+ {
+ let identifier = response.notification().request().identifier().to_string();
+ activate(self.ivars(), notification_url(&identifier));
+ }
+ completion.call(());
+ }
+ }
+);
+
+pub fn install_delegate(app: &AppHandle) {
+ // Unbundled dev executables cannot use UserNotifications.
+ if super::ensure_application_bundle().is_err() {
+ return;
+ }
+ let delegate = NotificationDelegate::alloc().set_ivars(app.clone());
+ // SAFETY: NSObject's initializer is valid for this subclass with its ivars set.
+ let delegate: Retained<NotificationDelegate> = unsafe { msg_send![super(delegate), init] };
+ UNUserNotificationCenter::currentNotificationCenter()
+ .setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
+ DELEGATE.with(|slot| *slot.borrow_mut() = Some(delegate));
+}
+
+pub(super) fn notification_url(identifier: &str) -> Option<Url> {
+ let url = Url::parse(identifier).ok()?;
+ (url.scheme() == crate::APP_SCHEME
+ && url.host_str().is_none()
+ && url.path() == "/notification"
+ && url
+ .query_pairs()
+ .any(|(key, value)| key == "notificationId" && !value.is_empty()))
+ .then_some(url)
+}
+
+#[tracing::instrument(skip_all, fields(notification_id))]
+fn activate(app: &AppHandle, destination: Option<Url>) {
+ let span = tracing::Span::current();
+ if let Some(url) = &destination
+ && let Some((_, notification_id)) =
+ url.query_pairs().find(|(key, _)| key == "notificationId")
+ {
+ span.record("notification_id", notification_id.as_ref());
+ }
+ let handle = app.clone();
+ if let Err(error) = app.run_on_main_thread(move || {
+ let _entered = span.enter();
+ if let Err(error) = handle.show() {
+ tracing::warn!(?error, "Unable to show Macro for notification");
+ }
+ if let Some(window) = handle.get_webview_window("main") {
+ for result in [window.unminimize(), window.show(), window.set_focus()] {
+ if let Err(error) = result {
+ tracing::warn!(?error, "Unable to focus notification window");
+ }
+ }
+ }
+ if let Some(url) = destination {
+ crate::deliver_deep_link(url, &handle);
+ }
+ }) {
+ tracing::error!(?error, "Unable to dispatch notification activation");
+ }
+}
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 5c6e7b642e..b911ce0fad 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
@@ -59,7 +59,7 @@ fn native_authorization_errors_reach_the_frontend_with_their_details() {
#[test]
fn immediate_notifications_preserve_the_title_and_optional_body() {
- let request = notification_request("Macro — new message", Some("Hello 👋\nSecond line"));
+ let request = notification_request("Macro — new message", Some("Hello 👋\nSecond line"), None);
assert_eq!(request.content().title().to_string(), "Macro — new message");
assert_eq!(
request.content().body().to_string(),
@@ -67,19 +67,53 @@ fn immediate_notifications_preserve_the_title_and_optional_body() {
);
assert!(request.trigger().is_none());
- let title_only = notification_request("Reminder", None);
+ let title_only = notification_request("Reminder", None, 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);
+ let first = notification_request("Same title", None, None);
+ let second = notification_request("Same title", None, None);
assert_ne!(first.identifier(), second.identifier());
assert!(Uuid::parse_str(&first.identifier().to_string()).is_ok());
}
+#[test]
+fn delivered_notifications_keep_their_destination_without_webview_callbacks() {
+ let request = notification_request("Message", None, Some("first-notification"));
+ let second = notification_request("Message", None, Some("second-notification"));
+ let repeated = notification_request("Message", None, Some("first-notification"));
+ assert_ne!(request.identifier(), repeated.identifier());
+ for (request, expected) in [
+ (request, "first-notification"),
+ (second, "second-notification"),
+ ] {
+ let url = activation::notification_url(&request.identifier().to_string())
+ .expect("delivered notification has a navigation destination");
+ assert_eq!(url.path(), "/notification");
+ assert!(
+ url.query_pairs()
+ .any(|(key, value)| key == "notificationId" && value == expected)
+ );
+ }
+}
+
+#[test]
+fn legacy_and_unrelated_notification_identifiers_cannot_route() {
+ for identifier in [
+ "legacy-delivery-id",
+ "macro:///notification?notificationId=",
+ "macro:///notification?deliveryId=123",
+ "macro:///task/123?notificationId=123",
+ "https://example.com/notification?notificationId=123",
+ "macro://external/notification?notificationId=123",
+ ] {
+ assert!(activation::notification_url(identifier).is_none());
+ }
+}
+
#[test]
fn native_delivery_errors_reach_the_frontend_with_their_details() {
// SAFETY: no user-info dictionary is supplied, so its generic types cannot
diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.md
index fd1d8e32c9..e6d3b1e681 100644
--- a/docs/agent-guide/notifications.md
+++ b/docs/agent-guide/notifications.md
@@ -17,6 +17,16 @@ can still suppress alerts even when authorization is granted.
Verify off/on and persistence after restarting; on the Notifications page, a failed
toggle should show an error toast and allow retry.
+On macOS builds with notification activation, clicking an alert restores and
+focuses Macro and opens that notification's message, thread, or document location.
+The native notification retains its destination across app restarts, and startup
+waits for the layout before opening it. Receipt and dismissal must not navigate.
+Verify two alerts with different targets by clicking the older one, then repeat
+with Macro minimized, hidden, and quit. Test a channel reply and a document
+comment to check the location inside the entity, not just the entity itself.
+This requires a full native macOS release; frontend-only updates cannot add the
+response delegate or repair destinations in previously delivered alerts.
+
On Linux desktop builds with native notification activation, clicking a system
notification (or its **Open** action) restores/presents Macro and opens that
notification's target using the normal in-app navigation. Dismissing or expiring