Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Seanaye/fix/linux notification open (#8065)
Sean Aye6551ac390039
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 95ef5cd4b6..c8150bd375 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -17,6 +17,7 @@"native:e2e": "bash tests/native/run.sh","native:e2e:smoke": "bash tests/native/run.sh --smoke","native:e2e:links": "bash tests/native/run.sh --links",+ "native:e2e:notifications": "bash tests/native/run.sh --notifications","native:e2e:fixtures": "bun test tests/native/fixtures","native:e2e:check": "tsc -p tests/native/tsconfig.json && tsc -p tests/native/tsconfig.browser.json","native:e2e:matrix": "bash tests/native/run.sh --matrix",diff --git a/apps/web/src/features/notifications/tests/notification-platform.test.ts b/apps/web/src/features/notifications/tests/notification-platform.test.tsindex 455746de32..2cca8ce531 100644--- a/apps/web/src/features/notifications/tests/notification-platform.test.ts+++ b/apps/web/src/features/notifications/tests/notification-platform.test.ts@@ -1,6 +1,7 @@import type { SplitManager } from '@components/app/split-layout/layoutManager';import { describe, expect, it, vi } from 'vitest';import type { PlatformNotificationState } from '../components/PlatformNotificationProvider';+import { openNotification } from '../notification-navigation';import type { PlatformNotificationHandle } from '../notification-platform';import type { UnifiedNotification } from '../types';@@ -246,6 +247,37 @@ describe('maybeHandlePlatformNotification', () => {expect(handle.onClick).toHaveBeenCalledOnce();});+ it('opens the original notification target only when its platform handle is clicked', async () => {+ const focus = vi.spyOn(window, 'focus').mockImplementation(() => {});+ vi.mocked(openNotification).mockClear();+ try {+ let click: (() => void) | undefined;+ const handle = createNotificationHandle();+ handle.onClick = (callback) => {+ click = callback;+ };+ const notification = createChannelInviteNotification();+ const layout = {} as SplitManager;+ await maybeHandlePlatformNotification(+ notification,+ createNotificationInterface(async () => handle),+ layout+ );+ expect(openNotification).not.toHaveBeenCalled();+ expect(handle.close).not.toHaveBeenCalled();+ expect(click).toBeDefined();+ click!();+ expect(focus).toHaveBeenCalledOnce();+ expect(openNotification).toHaveBeenCalledExactlyOnceWith(+ notification,+ layout+ );+ expect(handle.close).toHaveBeenCalledOnce();+ } finally {+ focus.mockRestore();+ }+ });+it('names the bot, not "Someone", for an agent notification with no sender', async () => {const handle = createNotificationHandle();const showNotification = vi.fn<diff --git a/apps/web/src/lib/tauri/linux-notification.ts b/apps/web/src/lib/tauri/linux-notification.tsnew file mode 100644index 0000000000..5e1c6a016c--- /dev/null+++ b/apps/web/src/lib/tauri/linux-notification.ts@@ -0,0 +1,72 @@+import { Channel, invoke } from '@tauri-apps/api/core';+import { MacOSNotificationUpdateRequiredError } from './notification-errors';++type NotificationEvent = 'click' | 'dismissed';++function dispatch(callback: () => void) {+ try {+ callback();+ } catch (error) {+ // Do not let a navigation error interrupt Tauri's channel-end bookkeeping.+ console.error('Linux notification callback failed', error);+ }+}++export async function showLinuxNotification(+ title: string,+ options?: Pick<NotificationOptions, 'body' | 'icon'>+) {+ const clicks: (() => void)[] = [];+ const dismissals: (() => void)[] = [];+ let finished: NotificationEvent | undefined;+ const events = new Channel<NotificationEvent>((event) => {+ if (finished) return;+ finished = event;+ const callbacks = event === 'click' ? clicks : dismissals;+ for (const callback of callbacks) dispatch(callback);+ clicks.length = 0;+ dismissals.length = 0;+ });+ let id: string;+ try {+ id = await invoke<string>('send_linux_notification', {+ title,+ body: options?.body,+ icon: options?.icon,+ onEvent: events,+ });+ } catch (error) {+ if (error === 'Command send_linux_notification not found') {+ throw new MacOSNotificationUpdateRequiredError(error);+ }+ throw error;+ }++ let closing = false;+ async function close() {+ if (finished || closing) return;+ closing = true;+ try {+ await invoke('close_linux_notification', { id });+ } catch (error) {+ closing = false;+ console.error('Failed to close Linux notification', error);+ }+ }++ return {+ onClick(callback: () => void) {+ // The daemon can deliver a click before the command returns, or before+ // the caller has registered its navigation callback. Replay it once.+ if (finished === 'click') dispatch(callback);+ else if (!finished) clicks.push(callback);+ },+ onDismiss(callback: () => void) {+ if (finished === 'dismissed') dispatch(callback);+ else if (!finished) dismissals.push(callback);+ },+ close() {+ void close();+ },+ };+}diff --git a/apps/web/src/lib/tauri/notification-errors.ts b/apps/web/src/lib/tauri/notification-errors.tsnew file mode 100644index 0000000000..2605f3998d--- /dev/null+++ b/apps/web/src/lib/tauri/notification-errors.ts@@ -0,0 +1,7 @@+// Keep the existing class name for callers; both desktop senders use this error.+export class MacOSNotificationUpdateRequiredError extends Error {+ constructor(cause: unknown) {+ super('Update Macro to receive desktop notifications.', { cause });+ this.name = 'MacOSNotificationUpdateRequiredError';+ }+}diff --git a/apps/web/src/lib/tauri/notification.test.ts b/apps/web/src/lib/tauri/notification.test.tsindex 06573eec2a..febd45bd3a 100644--- a/apps/web/src/lib/tauri/notification.test.ts+++ b/apps/web/src/lib/tauri/notification.test.ts@@ -10,9 +10,17 @@ const mocks = vi.hoisted(() => ({isPermissionGranted: vi.fn(async () => true),requestPermission: vi.fn(async () => 'granted'),sendNotification: vi.fn(),+ channels: [] as { onmessage: (event: 'click' | 'dismissed') => void }[],}));-vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }));+vi.mock('@tauri-apps/api/core', () => ({+ invoke: mocks.invoke,+ Channel: class {+ constructor(public onmessage: (event: 'click' | 'dismissed') => void) {+ mocks.channels.push(this);+ }+ },+}));vi.mock('@tauri-apps/plugin-os', () => ({ type: mocks.osType }));vi.mock('@tauri-apps/plugin-notification', () => ({isPermissionGranted: mocks.isPermissionGranted,@@ -36,6 +44,7 @@ const notification = {describe('desktop notification delivery', () => {beforeEach(() => {vi.resetAllMocks();+ mocks.channels.length = 0;mocks.osType.mockReturnValue('macos');mocks.isPermissionGranted.mockResolvedValue(true);mocks.requestPermission.mockResolvedValue('granted');@@ -136,9 +145,14 @@ describe('desktop notification delivery', () => {.mockRejectedValueOnce(missingCommand);const adapter = createTauriNotificationInterface(vi.fn());- await expect(adapter.showNotification(notification)).rejects.toEqual(- new MacOSNotificationUpdateRequiredError(missingCommand)+ const delivery = adapter.showNotification(notification);+ await expect(delivery).rejects.toBeInstanceOf(+ MacOSNotificationUpdateRequiredError);+ await expect(delivery).rejects.toMatchObject({+ message: 'Update Macro to receive desktop notifications.',+ cause: missingCommand,+ });expect(mocks.sendNotification).not.toHaveBeenCalled();});@@ -169,7 +183,7 @@ describe('desktop notification delivery', () => {expect(mocks.sendNotification).not.toHaveBeenCalled();});- it.each(['windows', 'linux', 'ios', 'android'])(+ it.each(['windows', 'ios', 'android'])('preserves plugin delivery on %s',async (os) => {mocks.osType.mockReturnValue(os);@@ -186,6 +200,170 @@ describe('desktop notification delivery', () => {});+ describe('Linux activation', () => {+ beforeEach(() => {+ mocks.osType.mockReturnValue('linux');+ mocks.invoke.mockResolvedValue('native-handle');+ });++ async function show(data = notification) {+ const adapter = createTauriNotificationInterface(vi.fn());+ const handle = await adapter.showNotification(data);+ if (handle === 'not-granted') throw new Error('Expected delivery');+ return handle;+ }++ it('sends an actionable native notification and dispatches its click only once', async () => {+ const handle = await show();+ const clicked = vi.fn();+ const dismissed = vi.fn();+ handle.onClick(clicked);+ handle.onDismiss(dismissed);+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith(+ 'send_linux_notification',+ {+ ...notification.options,+ title: notification.title,+ onEvent: mocks.channels[0],+ }+ );+ mocks.channels[0].onmessage('click');+ mocks.channels[0].onmessage('click');+ mocks.channels[0].onmessage('dismissed');+ handle.close();+ expect(clicked).toHaveBeenCalledOnce();+ expect(dismissed).not.toHaveBeenCalled();+ expect(mocks.invoke).toHaveBeenCalledTimes(1);+ expect(mocks.sendNotification).not.toHaveBeenCalled();+ });++ it('isolates callback errors from channel cleanup and other listeners', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const handle = await show();+ const failure = new Error('Navigation failed');+ const clicked = vi.fn();+ handle.onClick(() => {+ throw failure;+ });+ handle.onClick(clicked);+ expect(() => mocks.channels[0].onmessage('click')).not.toThrow();+ expect(clicked).toHaveBeenCalledOnce();+ expect(log).toHaveBeenCalledWith(+ 'Linux notification callback failed',+ failure+ );+ } finally {+ log.mockRestore();+ }+ });++ it('keeps simultaneous notifications and their close handles separate', async () => {+ mocks.invoke+ .mockResolvedValueOnce('first')+ .mockResolvedValueOnce('second');+ const first = await show();+ const second = await show();+ const firstClick = vi.fn();+ const secondClick = vi.fn();+ const firstDismiss = vi.fn();+ first.onClick(firstClick);+ first.onDismiss(firstDismiss);+ second.onClick(secondClick);+ first.close();+ first.close();+ expect(mocks.invoke).toHaveBeenLastCalledWith(+ 'close_linux_notification',+ { id: 'first' }+ );+ expect(mocks.invoke).toHaveBeenCalledTimes(3);+ mocks.channels[0].onmessage('dismissed');+ mocks.channels[1].onmessage('click');+ expect(firstDismiss).toHaveBeenCalledOnce();+ expect(firstClick).not.toHaveBeenCalled();+ expect(secondClick).toHaveBeenCalledOnce();+ });++ it.each(['click', 'dismissed'] as const)(+ 'buffers an early %s until callback registration',+ async (event) => {+ mocks.invoke.mockImplementation(async () => {+ mocks.channels[0].onmessage(event);+ return 'early';+ });+ const handle = await show();+ const clicked = vi.fn();+ const dismissed = vi.fn();+ handle.onClick(clicked);+ handle.onDismiss(dismissed);+ expect(clicked).toHaveBeenCalledTimes(event === 'click' ? 1 : 0);+ expect(dismissed).toHaveBeenCalledTimes(event === 'dismissed' ? 1 : 0);+ }+ );++ it('supports title-only notifications', async () => {+ await createTauriNotificationInterface(vi.fn()).showNotification({+ title: 'Reminder',+ });+ expect(mocks.invoke).toHaveBeenCalledWith('send_linux_notification', {+ title: 'Reminder',+ body: undefined,+ icon: undefined,+ onEvent: mocks.channels[0],+ });+ });++ it('waits for native delivery acceptance', async () => {+ const acceptance = deferred<string>();+ mocks.invoke.mockReturnValue(acceptance.promise);+ let completed = false;+ async function deliver() {+ await show();+ completed = true;+ }+ const delivery = deliver();+ await vi.waitFor(() => expect(mocks.invoke).toHaveBeenCalledOnce());+ expect(completed).toBe(false);+ acceptance.resolve('accepted');+ await delivery;+ expect(completed).toBe(true);+ });++ it('honors disabled delivery and denied permission', async () => {+ const disabled = createTauriNotificationInterface(vi.fn(), () => false);+ expect(await disabled.showNotification(notification)).toBe('not-granted');+ mocks.isPermissionGranted.mockResolvedValue(false);+ expect(+ await createTauriNotificationInterface(vi.fn()).showNotification(+ notification+ )+ ).toBe('not-granted');+ expect(mocks.invoke).not.toHaveBeenCalled();+ });++ it('uses the error class recognized by AppProviders when native support is missing', async () => {+ const missingCommand = 'Command send_linux_notification not found';+ mocks.invoke.mockRejectedValue(missingCommand);+ const delivery = show();+ // AppProviders imports this class from the existing notification export.+ await expect(delivery).rejects.toBeInstanceOf(+ MacOSNotificationUpdateRequiredError+ );+ await expect(delivery).rejects.toMatchObject({+ message: 'Update Macro to receive desktop notifications.',+ cause: missingCommand,+ });+ expect(mocks.sendNotification).not.toHaveBeenCalled();+ });++ it('propagates D-Bus delivery failures', async () => {+ const failure = new Error('Notification daemon unavailable');+ mocks.invoke.mockRejectedValue(failure);+ await expect(show()).rejects.toBe(failure);+ expect(mocks.sendNotification).not.toHaveBeenCalled();+ });+ });+it('preserves the title-only plugin call on other platforms', async () => {mocks.osType.mockReturnValue('windows');const adapter = createTauriNotificationInterface(vi.fn());diff --git a/apps/web/src/lib/tauri/notification.ts b/apps/web/src/lib/tauri/notification.tsindex 31a25ad6ff..322eae8606 100644--- a/apps/web/src/lib/tauri/notification.ts+++ b/apps/web/src/lib/tauri/notification.ts@@ -9,19 +9,17 @@ import {sendNotification,} from '@tauri-apps/plugin-notification';import { type as osType } from '@tauri-apps/plugin-os';+import { showLinuxNotification } from './linux-notification';+import { MacOSNotificationUpdateRequiredError } from './notification-errors';-export class MacOSNotificationUpdateRequiredError extends Error {- constructor(cause: unknown) {- super('Update Macro to receive desktop notifications.', { cause });- this.name = 'MacOSNotificationUpdateRequiredError';- }-}+export { MacOSNotificationUpdateRequiredError } from './notification-errors';export function createTauriNotificationInterface(setDisabled: () => Promise<void>,shouldSend: () => boolean = () => true): PlatformNotificationInterface {- const isMacOS = osType() === 'macos';+ const platform = osType();+ const isMacOS = platform === 'macos';let hasMacOSPermissionCommands = isMacOS;async function getCur(): Promise<NotificationPermission> {@@ -86,6 +84,10 @@ export function createTauriNotificationInterface(return createTauriNotification();}+ if (platform === 'linux') {+ return await showLinuxNotification(data.title, data.options);+ }+if (!data.options) {sendNotification(data.title);return createTauriNotification();diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex 7327c7e089..4f9fbbcce9 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -247,7 +247,9 @@ version = "0.1.0"dependencies = ["block2","clap",+ "futures-util","graphql_cache_plugin",+ "gtk","http","jni","libc",@@ -303,6 +305,7 @@ dependencies = ["url","urlencoding","uuid",+ "zbus",][[package]]diff --git a/apps/web/tauri/navigation_plugin/src/lib.rs b/apps/web/tauri/navigation_plugin/src/lib.rsindex 3b2e4144a8..c1a6d44a45 100644--- a/apps/web/tauri/navigation_plugin/src/lib.rs+++ b/apps/web/tauri/navigation_plugin/src/lib.rs@@ -155,6 +155,14 @@ impl MacroNavigationPlugin {fn new_window_destination<'a>(&self, url: &'a Url) -> NavigationOutput<'a> {match self.get_destination(url) {+ // Standalone documents on an allowed webview origin are not SPA+ // routes. Keep local-file policy and all other destinations intact.+ NavigationOutput::Internal+ if matches!(url.scheme(), "http" | "https" | "tauri")+ && url.path().ends_with(".html") =>+ {+ NavigationOutput::Internal+ }// A relative/same-origin app link should use the SPA router, not// create a second webview or reload the existing app.NavigationOutput::Internal => MacroScheme::from_url(url)@@ -165,15 +173,19 @@ impl MacroNavigationPlugin {}/// Route desktop anchors and `window.open` requests at the webview boundary.- /// Never create a popup webview: app links stay in the SPA and external URLs- /// go to the system handler. Mobile keeps the opener plugin's JS fallback.+ /// App links stay in the SPA and external URLs go to the system handler;+ /// trusted standalone HTML documents may open a popup webview.+ /// Mobile keeps the opener plugin's JS fallback.pub fn on_new_window<R: Runtime>(&self,app: &tauri::AppHandle<R>,url: &Url,) -> tauri::webview::NewWindowResponse<R> {- self.dispatch(app, self.new_window_destination(url));- tauri::webview::NewWindowResponse::Deny+ if self.dispatch(app, self.new_window_destination(url)) {+ tauri::webview::NewWindowResponse::Allow+ } else {+ tauri::webview::NewWindowResponse::Deny+ }}/// Return true only when the current webview may load the URL itself.diff --git a/apps/web/tauri/navigation_plugin/src/tests.rs b/apps/web/tauri/navigation_plugin/src/tests.rsindex c03227cbda..5a8e95c4d8 100644--- a/apps/web/tauri/navigation_plugin/src/tests.rs+++ b/apps/web/tauri/navigation_plugin/src/tests.rs@@ -157,6 +157,8 @@ fn popup_app_links_include_same_origin_and_macro_scheme() {"tauri://localhost/app/mail?view=all","http://tauri.localhost/app/mail?view=all","http://localhost:3000/app/mail?view=all",+ "tauri://localhost/mail?view=all",+ "http://localhost:3000/mail?view=all",] {let url = Url::parse(input).unwrap();match plugin.new_window_destination(&url) {@@ -169,6 +171,67 @@ fn popup_app_links_include_same_origin_and_macro_scheme() {}}+#[test]+fn standalone_html_popup_remains_internal_and_is_allowed() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ use tauri::Listener;++ let app = tauri::test::mock_builder()+ .build(tauri::test::mock_context(tauri::test::noop_assets()))+ .unwrap();+ let received = Arc::new(AtomicUsize::new(0));+ let events = received.clone();+ app.listen("navigate", move |_| {+ events.fetch_add(1, Ordering::Relaxed);+ });++ let plugin = test_plugin();+ for input in [+ "http://localhost:3000/billing-lab.html",+ "http://localhost:3000/billing-lab.html?scenario=paid#details",+ "tauri://localhost/billing-lab.html",+ "http://tauri.localhost/another-document.html",+ ] {+ let url = Url::parse(input).unwrap();+ assert!(+ matches!(+ plugin.new_window_destination(&url),+ NavigationOutput::Internal+ ),+ "{url}"+ );+ assert!(+ matches!(+ plugin.on_new_window(app.handle(), &url),+ tauri::webview::NewWindowResponse::Allow+ ),+ "{url}"+ );+ }+ assert_eq!(received.load(Ordering::Relaxed), 0);+}++#[test]+fn standalone_html_does_not_bypass_origin_policy() {+ let plugin = test_plugin();+ for input in [+ "https://example.com/billing-lab.html",+ "http://localhost:9999/billing-lab.html",+ ] {+ assert!(+ matches!(+ plugin.new_window_destination(&Url::parse(input).unwrap()),+ NavigationOutput::External(_)+ ),+ "{input}"+ );+ }+ assert!(matches!(+ plugin.new_window_destination(&Url::parse("file:///etc/billing-lab.html").unwrap()),+ NavigationOutput::Blocked+ ));+}+#[test]fn browser_only_urls_and_untrusted_local_files_are_blocked() {let plugin = test_plugin();diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 4a78a37f24..fc4805f4db 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -77,6 +77,11 @@ tauri-plugin-updater = "=2.10.1"# 2.5 requires tauri 2.12; the pinned fork is 2.11.tauri-plugin-window-state = "=2.4.1"+[target.'cfg(target_os = "linux")'.dependencies]+futures-util = "0.3"+gtk = "0.18"+zbus = "5"+[target.'cfg(target_os = "macos")'.dependencies]block2 = "0.6"libc = "0.2"diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.mdindex 1d27bcaf4c..b9f4341d74 100644--- a/apps/web/tauri/src-tauri/README.md+++ b/apps/web/tauri/src-tauri/README.md@@ -205,6 +205,16 @@ sender. Before publishing this frontend in a desktop OTA archive, setbinaries show an update-required notice instead of falling back to the legacynotification API, which macOS rejects after UserNotifications has been used.+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+this frontend as a desktop OTA archive, raise `MIN_NATIVE_BUILD` to that release.+Older Linux binaries show an update-required error rather than silently sending+notifications that cannot be activated. The native sender retains the D-Bus+connection, advertises the default Open action, and forwards activation tokens to+GTK before the existing frontend notification callback navigates. Dismissal never+navigates. This supports the running app, not relaunch after the process exits.+Extraction writes a sibling `<directory>.complete` record only after checksum,extraction, manifest, and entrypoint validation succeed. Directories without amatching completion record cannot be reused or restored. Previously cached OTAdiff --git a/apps/web/tauri/src-tauri/examples/notification-test-daemon.rs b/apps/web/tauri/src-tauri/examples/notification-test-daemon.rsnew file mode 100644index 0000000000..76d9fb473d--- /dev/null+++ b/apps/web/tauri/src-tauri/examples/notification-test-daemon.rs@@ -0,0 +1,117 @@+//! Disposable notification daemon for the isolated WebKit regression runner.+//! Not part of the application; refuses to replace an existing notification service.++#[cfg(target_os = "linux")]+mod linux {+ use std::{+ collections::{HashMap, HashSet},+ time::Duration,+ };+ use zbus::{message::Header, object_server::SignalEmitter, zvariant::OwnedValue};++ const SERVICE: &str = "org.freedesktop.Notifications";+ const PATH: &str = "/org/freedesktop/Notifications";++ #[derive(Default)]+ struct Daemon {+ next_id: u32,+ closed: Vec<u32>,+ removed: HashSet<u32>,+ senders: HashSet<String>,+ }++ #[derive(Debug, zbus::DBusError)]+ #[zbus(prefix = "org.freedesktop.Notifications.Error")]+ enum CloseError {+ NotFound(String),+ }++ #[zbus::interface(name = "org.freedesktop.Notifications")]+ impl Daemon {+ #[expect(clippy::too_many_arguments, reason = "freedesktop Notify signature")]+ fn notify(+ &mut self,+ _app: &str,+ replaces: u32,+ _icon: &str,+ _summary: &str,+ _body: &str,+ actions: Vec<String>,+ _hints: HashMap<String, OwnedValue>,+ _timeout: i32,+ #[zbus(header)] header: Header<'_>,+ ) -> u32 {+ self.senders.insert(header.sender().unwrap().to_string());+ assert_eq!(replaces, 0);+ assert_eq!(actions, ["default", "Open"]);+ self.next_id += 1;+ self.next_id+ }++ fn close_notification(&mut self, id: u32) -> Result<(), CloseError> {+ self.closed.push(id);+ if !self.removed.insert(id) {+ return Err(CloseError::NotFound("notification id was not found".into()));+ }+ Ok(())+ }++ fn snapshot(&self) -> String {+ serde_json::json!({+ "sent": self.next_id,+ "closed": self.closed,+ "connections": self.senders.len(),+ })+ .to_string()+ }++ async fn activate(+ &mut self,+ id: u32,+ #[zbus(signal_emitter)] emitter: SignalEmitter<'_>,+ ) -> zbus::fdo::Result<()> {+ // Match Noctalia: activation removes the alert before the client+ // processes ActionInvoked and asks to close it.+ self.removed.insert(id);+ emitter+ .emit(SERVICE, "ActivationToken", &(id, "fixture-token"))+ .await?;+ emitter+ .emit(SERVICE, "ActionInvoked", &(id, "default"))+ .await?;+ Ok(())+ }++ async fn dismiss(+ &mut self,+ id: u32,+ #[zbus(signal_emitter)] emitter: SignalEmitter<'_>,+ ) -> zbus::fdo::Result<()> {+ self.removed.insert(id);+ emitter+ .emit(SERVICE, "NotificationClosed", &(id, 2u32))+ .await?;+ Ok(())+ }+ }++ pub async fn run() {+ let _connection = zbus::connection::Builder::session()+ .unwrap()+ .name(SERVICE)+ .unwrap()+ .serve_at(PATH, Daemon::default())+ .unwrap()+ .build()+ .await+ .unwrap();+ println!("ready");+ tokio::time::sleep(Duration::from_secs(120)).await;+ }+}++#[tokio::main]+async fn main() {+ #[cfg(target_os = "linux")]+ linux::run().await;+}diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex b4a5c3bf9d..914da5f8ec 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -36,6 +36,8 @@ use url::Url;mod desktop_update;mod device;mod diagnostics;+#[cfg(target_os = "linux")]+mod linux_notification;mod logging;#[cfg(target_os = "macos")]mod macos_notification_permission;@@ -186,6 +188,19 @@ pub fn run() {.plugin(window_state::plugin());}+ #[cfg(target_os = "linux")]+ {+ builder = builder+ .manage(linux_notification::LinuxNotifications::default())+ .on_window_event(|window, event| {+ if matches!(event, tauri::WindowEvent::Destroyed) {+ window+ .state::<linux_notification::LinuxNotifications>()+ .close_window(window.label());+ }+ });+ }+#[cfg(target_os = "ios")]{builder = builder@@ -300,6 +315,10 @@ pub fn run() {desktop_update::get_native_update_status,desktop_update::restart_native_update,diagnostics::read_desktop_diagnostics,+ #[cfg(target_os = "linux")]+ linux_notification::send_linux_notification,+ #[cfg(target_os = "linux")]+ linux_notification::close_linux_notification,#[cfg(target_os = "macos")]macos_notification_permission::get_macos_notification_permission,#[cfg(target_os = "macos")]diff --git a/apps/web/tauri/src-tauri/src/linux_notification.rs b/apps/web/tauri/src-tauri/src/linux_notification.rsnew file mode 100644index 0000000000..dd94ccd735--- /dev/null+++ b/apps/web/tauri/src-tauri/src/linux_notification.rs@@ -0,0 +1,138 @@+//! Actionable freedesktop notifications. Keep the D-Bus connection alive until+//! activation/dismissal and forward the compositor's token to GTK on Wayland.++use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+};++use gtk::prelude::*;+use serde::Serialize;+use tauri::{Manager, Runtime, State, WebviewWindow, ipc::Channel};+use tokio::sync::{OnceCell, oneshot};+use uuid::Uuid;++mod transport;+use transport::{Notification, Outcome};++#[derive(Clone, Default)]+pub struct LinuxNotifications {+ pending: Arc<Mutex<HashMap<Uuid, Pending>>>,+ connection: Arc<OnceCell<zbus::Connection>>,+}++struct Pending {+ window: String,+ close: oneshot::Sender<()>,+}++#[derive(Clone, Copy, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum NotificationEvent {+ Click,+ Dismissed,+}++impl LinuxNotifications {+ pub fn close_window(&self, label: &str) {+ // Dropping the senders also wakes the notification tasks for cleanup.+ self.pending+ .lock()+ .unwrap()+ .retain(|_, pending| pending.window != label);+ }+}++#[tauri::command]+pub async fn send_linux_notification<R: Runtime>(+ window: WebviewWindow<R>,+ state: State<'_, LinuxNotifications>,+ title: String,+ body: Option<String>,+ icon: Option<String>,+ on_event: Channel<NotificationEvent>,+) -> Result<String, String> {+ // Share one bus connection across sends, including concurrent first sends.+ // Failed initialization leaves the cell empty so the next send can retry.+ let connection = state+ .connection+ .get_or_try_init(zbus::Connection::session)+ .await+ .map_err(|e| e.to_string())?+ .clone();+ let notification = Notification::show(+ connection,+ &window.app_handle().config().identifier,+ &title,+ body.as_deref(),+ icon.as_deref(),+ )+ .await+ .map_err(|e| e.to_string())?;+ // This key identifies our handle, not a server ID that could be reused after+ // a daemon restart. A different webview cannot close this window's handles.+ let key = Uuid::new_v4();+ let (close, closed) = oneshot::channel();+ let state = state.inner().clone();+ state.pending.lock().unwrap().insert(+ key,+ Pending {+ window: window.label().to_owned(),+ close,+ },+ );+ tauri::async_runtime::spawn(async move {+ let outcome = notification.wait(closed).await;+ state.pending.lock().unwrap().remove(&key);+ match outcome {+ Ok(Outcome::Activated(token)) => {+ // GTK calls must run on the UI thread. window.focus() in JS has+ // neither a native window handle nor the Wayland activation token.+ let target = window.clone();+ if let Err(error) = window.run_on_main_thread(move || {+ match target.gtk_window() {+ Ok(gtk_window) => {+ if let Some(token) = token {+ gtk_window.set_startup_id(&token);+ }+ gtk_window.deiconify();+ gtk_window.present();+ }+ Err(error) => {+ tracing::warn!(?error, "Unable to activate notification window")+ }+ }+ let _ = on_event.send(NotificationEvent::Click);+ }) {+ tracing::warn!(?error, "Unable to dispatch notification click");+ }+ }+ result => {+ if let Err(error) = result {+ tracing::warn!(?error, "Linux notification listener failed");+ }+ let _ = on_event.send(NotificationEvent::Dismissed);+ }+ }+ });+ Ok(key.to_string())+}++#[tauri::command]+pub fn close_linux_notification<R: Runtime>(+ window: WebviewWindow<R>,+ state: State<'_, LinuxNotifications>,+ id: String,+) -> Result<(), String> {+ let key = Uuid::parse_str(&id).map_err(|e| e.to_string())?;+ let mut pending = state.pending.lock().unwrap();+ if let Some(notification) = pending.get(&key) {+ if notification.window != window.label() {+ return Err("Notification belongs to a different window".into());+ }+ if let Some(notification) = pending.remove(&key) {+ let _ = notification.close.send(());+ }+ }+ Ok(())+}diff --git a/apps/web/tauri/src-tauri/src/linux_notification/transport.rs b/apps/web/tauri/src-tauri/src/linux_notification/transport.rsnew file mode 100644index 0000000000..c2666a6555--- /dev/null+++ b/apps/web/tauri/src-tauri/src/linux_notification/transport.rs@@ -0,0 +1,138 @@+use std::collections::HashMap;++use futures_util::StreamExt;+use tokio::sync::oneshot;+use zbus::{+ Connection, Proxy,+ proxy::{OwnerChangedStream, SignalStream},+ zvariant::Value,+};++const SERVICE: &str = "org.freedesktop.Notifications";+const PATH: &str = "/org/freedesktop/Notifications";+const DEFAULT_ACTION: &str = "default";++pub(super) struct Notification {+ proxy: Proxy<'static>,+ signals: SignalStream<'static>,+ owners: OwnerChangedStream<'static>,+ id: u32,+}++#[derive(Debug, PartialEq, Eq)]+pub(super) enum Outcome {+ Activated(Option<String>),+ Dismissed,+}++impl Notification {+ pub(super) async fn show(+ connection: Connection,+ desktop_entry: &str,+ title: &str,+ body: Option<&str>,+ icon: Option<&str>,+ ) -> zbus::Result<Self> {+ let bus = zbus::fdo::DBusProxy::new(&connection).await?;+ let owner = match bus.get_name_owner(SERVICE.try_into()?).await {+ Ok(owner) => owner,+ Err(zbus::fdo::Error::NameHasNoOwner(_)) => {+ // Preserve D-Bus activation for lazily started daemons (e.g. dunst).+ bus.start_service_by_name(SERVICE.try_into()?, 0).await?;+ bus.get_name_owner(SERVICE.try_into()?).await?+ }+ Err(error) => return Err(error.into()),+ };+ // Pin the daemon's unique connection, not its replaceable service name:+ // a restarted daemon may reuse the same numeric notification IDs.+ let proxy = Proxy::new_owned(connection, owner, PATH, SERVICE).await?;+ // Subscribe BEFORE Notify: even an immediate click must not be lost.+ // One ordered stream preserves ActivationToken -> ActionInvoked ordering.+ let signals = proxy.receive_all_signals().await?;+ let owners = proxy.receive_owner_changed().await?;+ let hints = HashMap::from([("desktop-entry", Value::from(desktop_entry))]);+ let body = gtk::glib::markup_escape_text(body.unwrap_or_default());+ let id = proxy+ .call(+ "Notify",+ &(+ "Macro",+ 0u32,+ icon.unwrap_or("macro"),+ title,+ body.as_str(),+ &[DEFAULT_ACTION, "Open"][..],+ hints,+ -1i32,+ ),+ )+ .await?;+ Ok(Self {+ proxy,+ signals,+ owners,+ id,+ })+ }++ async fn close(&self) -> zbus::Result<()> {+ let result = self+ .proxy+ .call::<_, _, ()>("CloseNotification", &(self.id,))+ .await;+ // Some daemons (including Noctalia) remove the alert as soon as it is+ // activated. Closing it afterward is successful, idempotent cleanup.+ if matches!(&result, Err(zbus::Error::MethodError(name, _, _))+ if name.as_str() == "org.freedesktop.Notifications.Error.NotFound")+ {+ return Ok(());+ }+ result.inspect_err(|error| {+ tracing::warn!(?error, "Unable to close Linux notification");+ })+ }++ pub(super) async fn wait(mut self, mut closed: oneshot::Receiver<()>) -> zbus::Result<Outcome> {+ let mut token = None;+ loop {+ let message = tokio::select! {+ biased;+ _ = self.owners.next() => return Ok(Outcome::Dismissed),+ _ = &mut closed => {+ let _ = self.close().await;+ return Ok(Outcome::Dismissed);+ }+ message = self.signals.next() => match message {+ Some(message) => message,+ None => return Ok(Outcome::Dismissed),+ },+ };+ match message.header().member().map(|name| name.as_str()) {+ Some("ActivationToken") => {+ let (id, value): (u32, String) = message.body().deserialize()?;+ if id == self.id {+ token = Some(value);+ }+ }+ Some("ActionInvoked") => {+ let (id, action): (u32, String) = message.body().deserialize()?;+ if id == self.id && action == DEFAULT_ACTION {+ // Not all daemons remove a notification after activation.+ let _ = self.close().await;+ return Ok(Outcome::Activated(token));+ }+ }+ Some("NotificationClosed") => {+ let (id, _reason): (u32, u32) = message.body().deserialize()?;+ if id == self.id {+ return Ok(Outcome::Dismissed);+ }+ }+ _ => {}+ }+ }+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/src-tauri/src/linux_notification/transport/test.rs b/apps/web/tauri/src-tauri/src/linux_notification/transport/test.rsnew file mode 100644index 0000000000..ea3aec6456--- /dev/null+++ b/apps/web/tauri/src-tauri/src/linux_notification/transport/test.rs@@ -0,0 +1,294 @@+use super::*;+use std::{+ io::{BufRead, BufReader},+ process::{Child, Command, Stdio},+ sync::{Arc, Mutex},+ time::Duration,+};+use zbus::{connection::Builder, object_server::SignalEmitter, zvariant::OwnedValue};++#[derive(Default)]+struct Calls {+ actions: Vec<String>,+ bodies: Vec<String>,+ closed: Vec<u32>,+ close_error: Option<CloseError>,+}++#[derive(Clone, Debug, zbus::DBusError)]+#[zbus(prefix = "org.freedesktop.Notifications.Error")]+enum CloseError {+ NotFound(String),+ Failed(String),+}++struct Daemon {+ calls: Arc<Mutex<Calls>>,+ early_click: bool,+ fail: bool,+}++#[zbus::interface(name = "org.freedesktop.Notifications")]+impl Daemon {+ #[expect(+ clippy::too_many_arguments,+ reason = "freedesktop Notify wire signature"+ )]+ async fn notify(+ &self,+ app: &str,+ replaces: u32,+ _icon: &str,+ _summary: &str,+ body: &str,+ actions: Vec<String>,+ hints: HashMap<String, OwnedValue>,+ timeout: i32,+ #[zbus(signal_emitter)] emitter: SignalEmitter<'_>,+ ) -> zbus::fdo::Result<u32> {+ if self.fail {+ return Err(zbus::fdo::Error::Failed("Delivery rejected".into()));+ }+ assert_eq!(app, "Macro");+ assert_eq!(replaces, 0);+ assert_eq!(timeout, -1);+ assert!(hints.contains_key("desktop-entry"));+ let id = {+ let mut calls = self.calls.lock().unwrap();+ calls.actions = actions;+ calls.bodies.push(body.to_owned());+ calls.bodies.len() as u32+ };+ if self.early_click {+ emitter+ .emit(SERVICE, "ActivationToken", &(id, "early-token"))+ .await?;+ emitter+ .emit(SERVICE, "ActionInvoked", &(id, DEFAULT_ACTION))+ .await?;+ }+ Ok(id)+ }++ fn close_notification(&self, id: u32) -> Result<(), CloseError> {+ let mut calls = self.calls.lock().unwrap();+ calls.closed.push(id);+ match calls.close_error.clone() {+ Some(error) => Err(error),+ None => Ok(()),+ }+ }+}++struct Bus(Child);+impl Drop for Bus {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+}++async fn setup(early_click: bool, fail: bool) -> (Bus, Connection, Connection, Arc<Mutex<Calls>>) {+ // Never claim the developer's real notification service or display popups.+ let mut child = Command::new("dbus-daemon")+ .args(["--session", "--nofork", "--print-address=1"])+ .stdout(Stdio::piped())+ .spawn()+ .expect("dbus-daemon from the tauri-e2e shell");+ let mut address = String::new();+ BufReader::new(child.stdout.take().unwrap())+ .read_line(&mut address)+ .unwrap();+ let bus = Bus(child);+ let calls = Arc::new(Mutex::new(Calls::default()));+ let server = Builder::address(address.trim())+ .unwrap()+ .name(SERVICE)+ .unwrap()+ .serve_at(+ PATH,+ Daemon {+ calls: calls.clone(),+ early_click,+ fail,+ },+ )+ .unwrap()+ .build()+ .await+ .unwrap();+ let client = Builder::address(address.trim())+ .unwrap()+ .build()+ .await+ .unwrap();+ (bus, server, client, calls)+}++async fn show(client: Connection) -> Notification {+ Notification::show(+ client,+ "com.macro.app.e2e",+ "Test",+ Some("<hello> & goodbye"),+ None,+ )+ .await+ .unwrap()+}++async fn signal(server: &Connection, name: &str, body: &(u32, &str)) {+ server+ .emit_signal(None::<&str>, PATH, SERVICE, name, body)+ .await+ .unwrap();+}++async fn outcome(notification: Notification, close: oneshot::Receiver<()>) -> Outcome {+ tokio::time::timeout(Duration::from_secs(3), notification.wait(close))+ .await+ .expect("notification listener timed out")+ .unwrap()+}++#[tokio::test]+async fn advertises_default_action_and_buffers_early_token_and_click() {+ let (_bus, _server, client, calls) = setup(true, false).await;+ let notification = show(client).await;+ let (_close, closed) = oneshot::channel();+ assert_eq!(+ outcome(notification, closed).await,+ Outcome::Activated(Some("early-token".into()))+ );+ let calls = calls.lock().unwrap();+ assert_eq!(calls.actions, ["default", "Open"]);+ assert_eq!(calls.bodies, ["<hello> & goodbye"]);+ assert_eq!(calls.closed, [1]);+}++#[tokio::test]+async fn closing_an_already_removed_notification_succeeds() {+ let (_bus, _server, client, calls) = setup(false, false).await;+ let notification = show(client).await;+ calls.lock().unwrap().close_error =+ Some(CloseError::NotFound("notification id was not found".into()));+ notification.close().await.unwrap();+ assert_eq!(calls.lock().unwrap().closed, [1]);+}++#[tokio::test]+async fn daemon_removal_on_click_does_not_prevent_activation() {+ let (_bus, _server, client, calls) = setup(true, false).await;+ let notification = show(client).await;+ calls.lock().unwrap().close_error =+ Some(CloseError::NotFound("notification id was not found".into()));+ let (_close, closed) = oneshot::channel();+ assert_eq!(+ outcome(notification, closed).await,+ Outcome::Activated(Some("early-token".into()))+ );+ assert_eq!(calls.lock().unwrap().closed, [1]);+}++#[tokio::test]+async fn other_close_errors_are_not_suppressed_even_with_the_same_description() {+ let (_bus, _server, client, calls) = setup(false, false).await;+ let notification = show(client).await;+ calls.lock().unwrap().close_error =+ Some(CloseError::Failed("notification id was not found".into()));+ let error = notification.close().await.unwrap_err();+ assert!(matches!(error, zbus::Error::MethodError(name, _, _)+ if name.as_str() == "org.freedesktop.Notifications.Error.Failed"));+}++#[tokio::test]+async fn simultaneous_notifications_keep_their_tokens_and_actions_separate() {+ let (_bus, server, client, calls) = setup(false, false).await;+ let first = show(client.clone()).await;+ let second = show(client).await;+ signal(&server, "ActivationToken", &(2, "second-token")).await;+ signal(&server, "ActionInvoked", &(1, "unknown-action")).await;+ signal(&server, "ActionInvoked", &(2, DEFAULT_ACTION)).await;+ signal(&server, "ActionInvoked", &(1, DEFAULT_ACTION)).await;+ let (_close1, closed1) = oneshot::channel();+ let (_close2, closed2) = oneshot::channel();+ assert_eq!(outcome(first, closed1).await, Outcome::Activated(None));+ assert_eq!(+ outcome(second, closed2).await,+ Outcome::Activated(Some("second-token".into()))+ );+ assert_eq!(calls.lock().unwrap().closed, [1, 2]);+}++#[tokio::test]+async fn expiry_and_dismissal_never_activate() {+ for reason in [1u32, 2, 3, 4] {+ let (_bus, server, client, calls) = setup(false, false).await;+ let notification = show(client).await;+ server+ .emit_signal(+ None::<&str>,+ PATH,+ SERVICE,+ "NotificationClosed",+ &(1u32, reason),+ )+ .await+ .unwrap();+ let (_close, closed) = oneshot::channel();+ assert_eq!(outcome(notification, closed).await, Outcome::Dismissed);+ assert!(calls.lock().unwrap().closed.is_empty());+ }+}++#[tokio::test]+async fn explicit_close_and_window_destruction_close_the_native_notification() {+ for send in [true, false] {+ let (_bus, _server, client, calls) = setup(false, false).await;+ let notification = show(client).await;+ let (close, closed) = oneshot::channel();+ if send {+ close.send(()).unwrap();+ } else {+ drop(close);+ }+ assert_eq!(outcome(notification, closed).await, Outcome::Dismissed);+ assert_eq!(calls.lock().unwrap().closed, [1]);+ }+}++#[tokio::test]+async fn ignores_signals_from_other_bus_clients() {+ let (_bus, server, client, _) = setup(false, false).await;+ let notification = show(client.clone()).await;+ signal(&client, "ActivationToken", &(1, "wrong-sender")).await;+ signal(&client, "ActionInvoked", &(1, DEFAULT_ACTION)).await;+ signal(&server, "ActionInvoked", &(1, DEFAULT_ACTION)).await;+ let (_close, closed) = oneshot::channel();+ assert_eq!(+ outcome(notification, closed).await,+ Outcome::Activated(None)+ );+}++#[tokio::test]+async fn daemon_exit_releases_pending_notifications_without_activation() {+ let (_bus, server, client, _) = setup(false, false).await;+ let notification = show(client).await;+ server.close().await.unwrap();+ let (_close, closed) = oneshot::channel();+ assert_eq!(outcome(notification, closed).await, Outcome::Dismissed);+}++#[tokio::test]+async fn delivery_errors_reach_the_caller() {+ let (_bus, _server, client, _) = setup(false, true).await;+ let result = Notification::show(client, "com.macro.app.e2e", "Test", None, None).await;+ assert!(+ result+ .err()+ .unwrap()+ .to_string()+ .contains("Delivery rejected")+ );+}diff --git a/apps/web/tests/native/README.md b/apps/web/tests/native/README.mdindex 7bc31d5cf2..8fc2111a62 100644--- a/apps/web/tests/native/README.md+++ b/apps/web/tests/native/README.md@@ -88,10 +88,29 @@ and keyboard activation, a normal `_blank` link, same-frame external navigation,`window.open`, and absolute/relative Macro app links. Each external activationmust launch exactly once and retain the original webview. Prevented clicks andbrowser-only/local-file popup URLs must not launch anything. The desktop JS click-interceptor must be absent. Artifacts are under `test-results/native/links-*`.+interceptor must be absent. A trusted standalone HTML document must open in a+separate native window, not be converted to an SPA navigation or external launch.+Artifacts are under `test-results/native/links-*`.This is Linux coverage; macOS/Windows native popup handling and the unchangedmobile JS fallback need platform-specific verification.+## Native notification activation regression++After `bun run native:e2e:build`, run `bun run native:e2e:notifications` in the+same `.#tauri-e2e` shell. A disposable Rust notification daemon owns only the+isolated session bus. The production Linux notification adapter runs in the real+WebKit window and calls the actual native commands; no IPC is mocked. The suite+checks the advertised default action, two independent notification handles,+activation-token/click delivery through GTK to the correct JS callback, dismissal+without navigation, and explicit close. Artifacts are in+`test-results/native/notifications-*`.++This is not a compositor focus test: Xvfb has no Wayland activation protocol. On a+real desktop, separately check clicking a notification with Macro minimized,+hidden, or on another workspace. Both the shell and GTK must support activation+tokens for Wayland focus. It also does not test process relaunch or authenticated+notification-target rendering (the callback navigates a local fixture).+## Exhaustive filter-selection matrix```shdiff --git a/apps/web/tests/native/build.sh b/apps/web/tests/native/build.shindex 6fc08644d0..b0839f6027 100644--- a/apps/web/tests/native/build.sh+++ b/apps/web/tests/native/build.sh@@ -42,7 +42,7 @@ export CARGO_TARGET_DIR="$out/cargo"# production optimization. The unoptimized recursive parser has large stack# frames that exhaust a Tokio worker stack on valid compound filter queries.# Exhaustive matrices execute hundreds of thousands of real indexed queries.-cargo build --locked -p app --no-default-features \+cargo build --locked -p app --no-default-features --bin app --example notification-test-daemon \--config 'profile.dev.package.turso_core.opt-level=3' \--config 'profile.dev.package.turso_parser.opt-level=3'# Publish atomically so an existing isolated run can finish on its old inode.diff --git a/apps/web/tests/native/fixtures/links.html b/apps/web/tests/native/fixtures/links.htmlindex 2edb03388e..420536a7a4 100644--- a/apps/web/tests/native/fixtures/links.html+++ b/apps/web/tests/native/fixtures/links.html@@ -13,6 +13,7 @@<p><a id="app-link" href="https://macro.com/app/mail?view=all" target="_blank">Macro app link</a></p><p><a id="relative-link" href="/app/mail?view=all" target="_blank">Relative app link</a></p><button id="popup" type="button">Programmatic popup</button>+ <p><a id="standalone-link" href="/billing-lab.html" target="_blank">Standalone HTML document</a></p><script type="module" src="/links.js"></script></body></html>diff --git a/apps/web/tests/native/fixtures/notifications-browser.ts b/apps/web/tests/native/fixtures/notifications-browser.tsnew file mode 100644index 0000000000..ae2b70c05e--- /dev/null+++ b/apps/web/tests/native/fixtures/notifications-browser.ts@@ -0,0 +1,35 @@+import { showLinuxNotification } from '../../../src/lib/tauri/linux-notification';++declare global {+ interface Window {+ notificationFixture: {+ show: () => Promise<void>;+ close: (index: number) => void;+ clicked: number[];+ dismissed: number[];+ };+ }+}++const handles: Awaited<ReturnType<typeof showLinuxNotification>>[] = [];+window.notificationFixture = {+ clicked: [],+ dismissed: [],+ async show() {+ const index = handles.length;+ const handle = await showLinuxNotification(`Notification ${index}`);+ handles.push(handle);+ handle.onClick(() => {+ window.notificationFixture.clicked.push(index);+ // The production navigation callback owns the destination; this fixture+ // verifies that native activation reaches the correct frontend callback.+ location.hash = `notification-${index}`;+ handle.close();+ });+ handle.onDismiss(() => window.notificationFixture.dismissed.push(index));+ },+ close(index) {+ handles[index].close();+ },+};+document.documentElement.dataset.ready = 'true';diff --git a/apps/web/tests/native/links-runner.ts b/apps/web/tests/native/links-runner.tsindex 33e5a32542..94ca9ca4b2 100644--- a/apps/web/tests/native/links-runner.ts+++ b/apps/web/tests/native/links-runner.ts@@ -36,7 +36,16 @@ const server = Bun.serve({hostname: '127.0.0.1',port: 3009,fetch(request) {- const script = new URL(request.url).pathname === '/links.js';+ const path = new URL(request.url).pathname;+ if (path === '/billing-lab.html') {+ return new Response(+ '<!doctype html><title>Standalone HTML document</title><h1>Standalone document</h1>',+ {+ headers: { 'Content-Type': 'text/html' },+ }+ );+ }+ const script = path === '/links.js';return new Response(script ? javascript : html, {headers: { 'Content-Type': script ? 'text/javascript' : 'text/html' },});@@ -187,9 +196,36 @@ try {assert.deepEqual(await openedUrls(), expected);assert.equal(await browser.getUrl(), originalUrl);assert.equal((await browser.getWindowHandles()).length, 1);+ const originalWindow = await browser.getWindowHandle();+ await activate('standalone-link');+ await browser.waitUntil(+ async () => (await browser!.getWindowHandles()).length === 2,+ {+ timeoutMsg: 'Standalone HTML document did not open a native popup',+ }+ );+ const popup = (await browser.getWindowHandles()).find(+ (handle) => handle !== originalWindow+ )!;+ await browser.switchToWindow(popup);+ await browser.waitUntil(+ async () => (await browser!.getTitle()) === 'Standalone HTML document'+ );+ assert.equal(+ await browser.getUrl(),+ 'http://localhost:3009/billing-lab.html'+ );+ await browser.closeWindow();+ await browser.switchToWindow(originalWindow);+ assert.equal(await browser.getUrl(), originalUrl);+ assert.deepEqual(await openedUrls(), expected);+ assert.equal(+ await browser.execute(() => window.linkFixture.events.length),+ 2+ );await browser.saveScreenshot(resolve(artifacts, 'links.png'));console.log(- 'PASS: native popup and same-frame routing, stopped clicks, keyboard, cancellation, no duplicates, and in-app links'+ 'PASS: native popup and same-frame routing, stopped clicks, keyboard, cancellation, no duplicates, in-app links, and standalone HTML documents');} catch (error) {if (browser) {diff --git a/apps/web/tests/native/notifications-runner.ts b/apps/web/tests/native/notifications-runner.tsnew file mode 100644index 0000000000..62bbf1cc16--- /dev/null+++ b/apps/web/tests/native/notifications-runner.ts@@ -0,0 +1,201 @@+import assert from 'node:assert/strict';+import { mkdir } from 'node:fs/promises';+import { resolve } from 'node:path';+import { type Browser, remote } from 'webdriverio';+import type {} from './fixtures/notifications-browser';++assert.equal(process.env.MACRO_E2E_NETNS, '1', 'Run through isolated run.sh');+const web = resolve(import.meta.dirname, '../..');+const binaries = resolve(web, 'tauri/target/e2e');+const artifacts = resolve(+ web,+ 'test-results/native',+ `notifications-${Date.now()}`+);+await mkdir(artifacts, { recursive: true });+const bundle = await Bun.build({+ entrypoints: [+ resolve(import.meta.dirname, 'fixtures/notifications-browser.ts'),+ ],+ target: 'browser',+});+assert(bundle.success, String(bundle.logs));+const javascript = await bundle.outputs[0].text();+const server = Bun.serve({+ hostname: '127.0.0.1',+ port: 3009,+ fetch(request) {+ if (new URL(request.url).pathname === '/notifications.js') {+ return new Response(javascript, {+ headers: { 'Content-Type': 'text/javascript' },+ });+ }+ return new Response(+ '<!doctype html><title>Notifications</title><h1>Native notification regression</h1><script type="module" src="/notifications.js"></script>',+ {+ headers: { 'Content-Type': 'text/html' },+ }+ );+ },+});+const daemon = Bun.spawn(+ [resolve(binaries, 'cargo/debug/examples/notification-test-daemon')],+ {+ stdout: Bun.file(resolve(artifacts, 'daemon.log')),+ stderr: Bun.file(resolve(artifacts, 'daemon.stderr.log')),+ }+);+const driver = Bun.spawn(+ [+ resolve(binaries, 'tools/bin/tauri-driver'),+ '--port',+ '4444',+ '--native-driver',+ Bun.which('WebKitWebDriver')!,+ ],+ {+ env: {+ ...process.env,+ WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: '1',+ WEBKIT_DISABLE_DMABUF_RENDERER: '1',+ LIBGL_ALWAYS_SOFTWARE: '1',+ },+ stdout: Bun.file(resolve(artifacts, 'tauri.log')),+ stderr: Bun.file(resolve(artifacts, 'tauri.stderr.log')),+ }+);+const watchdog = setTimeout(() => {+ console.error(`Notification test timed out: ${artifacts}`);+ process.exit(1);+}, 120_000);+let browser: Browser | undefined;+async function call(method: string, id?: number) {+ const process = Bun.spawn(+ [+ 'gdbus',+ 'call',+ '--session',+ '--dest',+ 'org.freedesktop.Notifications',+ '--object-path',+ '/org/freedesktop/Notifications',+ '--method',+ `org.freedesktop.Notifications.${method}`,+ ...(id === undefined ? [] : [String(id)]),+ ],+ { stdout: 'pipe', stderr: 'pipe' }+ );+ const output = await new Response(process.stdout).text();+ assert.equal(+ await process.exited,+ 0,+ await new Response(process.stderr).text()+ );+ return output;+}+try {+ for (;;) {+ assert.equal(driver.exitCode, null);+ assert.equal(daemon.exitCode, null);+ try {+ if (+ (await fetch('http://localhost:4444/status')).ok &&+ (await Bun.file(resolve(artifacts, 'daemon.log')).text()).includes(+ 'ready'+ )+ )+ break;+ } catch {+ /* Wait for both services. */+ }+ await Bun.sleep(100);+ }+ const capabilities: WebdriverIO.Capabilities & {+ 'tauri:options': { application: string };+ } = {+ 'tauri:options': { application: resolve(binaries, 'app') },+ };+ browser = await remote({+ hostname: '127.0.0.1',+ port: 4444,+ logLevel: 'warn',+ connectionRetryCount: 0,+ connectionRetryTimeout: 30_000,+ capabilities,+ });+ await browser.waitUntil(+ () =>+ browser!.execute(() => document.documentElement.dataset.ready === 'true'),+ { timeout: 30_000 }+ );+ await browser.execute(async () => {+ await window.notificationFixture.show();+ await window.notificationFixture.show();+ });+ await call('Activate', 2);+ await browser.waitUntil(() =>+ browser!.execute(() => window.notificationFixture.clicked.length === 1)+ );+ assert.deepEqual(+ await browser.execute(() => window.notificationFixture.clicked),+ [1]+ );+ assert.equal(await browser.execute(() => location.hash), '#notification-1');+ await call('Dismiss', 1);+ await browser.waitUntil(() =>+ browser!.execute(() => window.notificationFixture.dismissed.length === 1)+ );+ assert.deepEqual(+ await browser.execute(() => window.notificationFixture.dismissed),+ [0]+ );+ await browser.execute(async () => {+ await window.notificationFixture.show();+ window.notificationFixture.close(2);+ });+ await browser.waitUntil(() =>+ browser!.execute(() => window.notificationFixture.dismissed.length === 2)+ );+ const snapshot = await call('Snapshot');+ assert.match(snapshot, /"closed":\[2,3\]/);+ assert.match(snapshot, /"sent":3/);+ assert.match(+ snapshot,+ /"connections":1/,+ 'All sends must reuse one session-bus connection'+ );+ assert.deepEqual(+ await browser.execute(() => window.notificationFixture.clicked),+ [1]+ );+ for (const log of ['tauri.log', 'tauri.stderr.log']) {+ assert.doesNotMatch(+ await Bun.file(resolve(artifacts, log)).text(),+ /Unable to close Linux notification/,+ 'A notification already removed by the daemon must not warn'+ );+ }+ await browser.saveScreenshot(resolve(artifacts, 'notifications.png'));+ console.log(+ 'PASS: real Linux WebKit -> native D-Bus delivery -> GTK activation -> correct JS callback; dismissal, explicit close, and already-removed cleanup without warnings'+ );+} finally {+ if (browser) {+ try {+ await browser.deleteSession();+ } catch {+ /* Shutdown still owns the driver. */+ }+ }+ driver.kill();+ daemon.kill();+ await Promise.race([+ Promise.all([driver.exited, daemon.exited]),+ Bun.sleep(2000),+ ]);+ if (driver.exitCode === null) driver.kill('SIGKILL');+ if (daemon.exitCode === null) daemon.kill('SIGKILL');+ await server.stop(true);+ clearTimeout(watchdog);+ console.log(`Artifacts: ${artifacts}`);+}diff --git a/apps/web/tests/native/run.sh b/apps/web/tests/native/run.shindex a9bf2175a3..f3f86477e1 100644--- a/apps/web/tests/native/run.sh+++ b/apps/web/tests/native/run.sh@@ -5,6 +5,9 @@ runner=runner.tsif [[ ${1:-} == --links ]]; thenrunner=links-runner.tsshift+elif [[ ${1:-} == --notifications ]]; then+ runner=notifications-runner.ts+ shiftfifor tool in bun unshare ip dbus-run-session xvfb-run WebKitWebDriver; doif ! command -v "$tool" >/dev/null; thendiff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 25090f22b8..aade350ad1 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -25,7 +25,9 @@ Desktop external links open in the system browser, whether activated by a normalanchor, a `target="_blank"` anchor, or `window.open(url)`. Native webview navigationhandles this, not a window-level DOM click listener. Each activation should openexactly once, without replacing the app or creating another app window. Macro app-links (including same-origin popup links) route inside the existing SPA.+links (including same-origin popup links) route inside the existing SPA. Standalone+`.html` documents on trusted app origins, such as `/billing-lab.html`, instead open+in a native popup without replacing the app or emitting an SPA navigation event.Verify the `owner/repo#number` footer link in a pull request's floating detailspanel with both a click and keyboard activation. The panel stops click propagation;diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 2f778b3c13..333d2b8ec5 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2789,6 +2789,18 @@ can still suppress alerts even when authorization is granted.Verify off/on and persistence after restarting; on the Notifications page, a failedtoggle should show an error toast and allow retry.+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+an alert must not navigate. With two alerts, click the older one to check that the+correct target opens. Also test with Macro hidden/minimized and on another+workspace: Wayland focus requires the notification daemon to supply an activation+token. This needs a native AppImage update, not just a frontend update; an older+binary reports **Update Macro to receive desktop notifications.** Activation is+supported while the app process is running, not after quitting it. The isolated+Linux WebKit/D-Bus regression is `bun run native:e2e:notifications`; compositor+focus behavior still needs a real Wayland/X11 desktop check.+On native Android, enable notifications in Settings while signed in. Android 13+also asks for system permission; the system's **Activity** notification channelmust be enabled. Remote push owns system notification display after registration,