Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: route notification clicks to their originating window

Charlie Yan865c58721921
diff --git a/src-tauri/build.rs b/src-tauri/build.rs
index 2f464a68..366c3b62 100644
--- a/src-tauri/build.rs
+++ b/src-tauri/build.rs
@@ -5,6 +5,7 @@ fn main() {
tauri_build::AppManifest::new().commands(&[
"download_file",
"send_notification",
+ "close_notification",
"increment_dock_badge",
"set_dock_badge",
"set_dock_badge_label",
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index ef9b2f99..6e3d9d67 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -6,6 +6,7 @@
"permissions": [
"allow-download-file",
"allow-send-notification",
+ "allow-close-notification",
"allow-increment-dock-badge",
"allow-set-dock-badge",
"allow-set-dock-badge-label",
diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rs
index e0a65ab9..9dd42038 100644
--- a/src-tauri/src/app/config.rs
+++ b/src-tauri/src/app/config.rs
@@ -236,7 +236,13 @@ mod tests {
fn remote_ipc_requires_the_configured_scheme_host_and_port() {
let acl = resolve(&config_for("https://example.com/app?next=https://evil.com"));
assert!(acl.has_app_acl);
- for command in ["download_file", "set_zoom", "plugin:window|is_fullscreen"] {
+ for command in [
+ "download_file",
+ "send_notification",
+ "close_notification",
+ "set_zoom",
+ "plugin:window|is_fullscreen",
+ ] {
for label in ["pake", "pake-1"] {
assert!(allows(
&acl,
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rs
index 5556867a..cc2a27e0 100644
--- a/src-tauri/src/app/invoke.rs
+++ b/src-tauri/src/app/invoke.rs
@@ -1,4 +1,5 @@
use crate::app::navigation::{history_step, reload_window};
+use crate::app::notification::{self, NotificationOutcome, NotificationParams};
use crate::util::{
check_file_or_append, get_download_dir, get_download_message_with_lang,
sanitize_download_filename, show_toast, MessageType,
@@ -77,13 +78,6 @@ pub struct DownloadFileParams {
language: Option<String>,
}
-#[derive(serde::Deserialize)]
-pub struct NotificationParams {
- title: String,
- body: String,
- icon: String,
-}
-
/// Build a Cookie header from the webview session so authenticated downloads
/// match what the page itself would request. Best-effort: missing cookies
/// fall through to an anonymous request.
@@ -196,16 +190,19 @@ pub async fn download_file(
}
#[command]
-pub fn send_notification(app: AppHandle, params: NotificationParams) -> Result<(), String> {
- use tauri_plugin_notification::NotificationExt;
- app.notification()
- .builder()
- .title(&params.title)
- .body(&params.body)
- .icon(&params.icon)
- .show()
- .map_err(|e| format!("Failed to show notification: {}", e))?;
- Ok(())
+pub fn send_notification(
+ app: AppHandle,
+ window: WebviewWindow,
+ params: NotificationParams,
+) -> Result<NotificationOutcome, String> {
+ // Tauri injects the invoker as `window`, so a notification raised by a
+ // secondary window routes its click back to that window rather than "pake".
+ notification::send(&app, &window, &params)
+}
+
+#[command]
+pub fn close_notification(app: AppHandle, window: WebviewWindow, id: String) -> Result<(), String> {
+ notification::close(&app, &window, &id)
}
#[command]
diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs
index b9076c8b..94f55d05 100644
--- a/src-tauri/src/app/mod.rs
+++ b/src-tauri/src/app/mod.rs
@@ -5,6 +5,7 @@ pub mod invoke;
#[cfg(target_os = "macos")]
pub mod menu;
pub mod navigation;
+pub mod notification;
pub mod setup;
#[cfg(target_os = "macos")]
pub mod tab_bar;
diff --git a/src-tauri/src/app/notification.rs b/src-tauri/src/app/notification.rs
new file mode 100644
index 00000000..00f8dcfb
--- /dev/null
+++ b/src-tauri/src/app/notification.rs
@@ -0,0 +1,311 @@
+//! Native notification delivery with a real click callback.
+//!
+//! `tauri-plugin-notification` is fire-and-forget on desktop: `show()` hands the
+//! notification to `notify_rust` and drops the handle, so nothing ever tells the
+//! page which notification the user clicked. Because Pake replaces the page's
+//! `window.Notification` wholesale, that also kills the page's own click
+//! routing: Slack never jumps to the conversation the notification came from.
+//!
+//! macOS therefore delivers notifications itself through
+//! `NSUserNotificationCenter` with a delegate and routes the click back to the
+//! originating webview. Other platforms keep the plugin path, and the page falls
+//! back to the focus heuristic in `inject/event.js`.
+
+use tauri::{AppHandle, WebviewWindow};
+
+/// Ids are minted by the packaged (untrusted) page and echoed into a native
+/// notification identifier and a webview `eval`, so keep them short and opaque.
+const MAX_NOTIFICATION_ID_LEN: usize = 64;
+
+#[derive(serde::Deserialize)]
+pub struct NotificationParams {
+ id: String,
+ title: String,
+ body: String,
+ icon: String,
+}
+
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NotificationOutcome {
+ /// True when this platform reports the click back to the page. The page
+ /// keeps its focus-based fallback disabled in that case, so an ordinary app
+ /// switch never fires a phantom click on the newest notification.
+ native_click: bool,
+}
+
+fn validate_id(id: &str) -> Result<(), String> {
+ if id.is_empty() || id.len() > MAX_NOTIFICATION_ID_LEN {
+ return Err(format!(
+ "Notification id must be 1-{MAX_NOTIFICATION_ID_LEN} characters"
+ ));
+ }
+ if !id
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
+ {
+ return Err("Notification id must be alphanumeric, '-' or '_'".to_string());
+ }
+ Ok(())
+}
+
+/// Set up the platform click callback. Runs on the main thread during setup so
+/// the availability probe is a plain synchronous check later on.
+pub fn init_native_click(app: &AppHandle) {
+ #[cfg(target_os = "macos")]
+ macos::init(app);
+ #[cfg(not(target_os = "macos"))]
+ let _ = app;
+}
+
+pub fn send(
+ app: &AppHandle,
+ window: &WebviewWindow,
+ params: &NotificationParams,
+) -> Result<NotificationOutcome, String> {
+ validate_id(&params.id)?;
+
+ #[cfg(target_os = "macos")]
+ if macos::deliver(app, window.label(), params)? {
+ return Ok(NotificationOutcome { native_click: true });
+ }
+ #[cfg(not(target_os = "macos"))]
+ let _ = window;
+
+ use tauri_plugin_notification::NotificationExt;
+ app.notification()
+ .builder()
+ .title(&params.title)
+ .body(&params.body)
+ .icon(&params.icon)
+ .show()
+ .map_err(|e| format!("Failed to show notification: {e}"))?;
+
+ Ok(NotificationOutcome {
+ native_click: false,
+ })
+}
+
+/// Withdraw only the calling webview's notification. Other platforms retain
+/// their existing delivery path, which does not expose a withdrawal handle.
+pub fn close(app: &AppHandle, window: &WebviewWindow, id: &str) -> Result<(), String> {
+ validate_id(id)?;
+ #[cfg(target_os = "macos")]
+ return macos::withdraw(app, window.label(), id);
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = (app, window);
+ Ok(())
+ }
+}
+
+/// Reveal the window the notification came from and hand the click to the page.
+///
+/// A hidden or minimized window is exactly the case where a notification click
+/// matters most, so this goes through the same show + `reapply_window_icon` +
+/// focus sequence as every other hidden-to-visible path (#1323).
+#[cfg(target_os = "macos")]
+fn dispatch_click(app: &AppHandle, window_label: &str, id: &str) {
+ use tauri::Manager;
+
+ let Some(window) = app.get_webview_window(window_label) else {
+ return;
+ };
+
+ let _ = window.unminimize();
+ let _ = window.show();
+ crate::app::window::reapply_window_icon(&window);
+ let _ = window.set_focus();
+
+ // `id` passed `validate_id`, so it cannot break out of the string literal.
+ let _ = window.eval(format!(
+ "window.__pakeNotificationClick && window.__pakeNotificationClick('{id}')"
+ ));
+}
+
+#[cfg(target_os = "macos")]
+mod macos {
+ // The whole NSUserNotification family is deprecated in favour of
+ // UserNotifications.framework, which needs a provisioned bundle and a
+ // permission prompt that a webpage wrapper cannot meaningfully ask for.
+ // This is also the API the notification plugin already reaches through
+ // notify-rust, so staying on it keeps notification appearance unchanged.
+ #![allow(deprecated)]
+
+ use super::{dispatch_click, validate_id, NotificationParams};
+ use objc2::rc::Retained;
+ use objc2::runtime::{AnyClass, ProtocolObject};
+ use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
+ use objc2_foundation::{
+ NSObject, NSObjectProtocol, NSString, NSUserNotification, NSUserNotificationCenter,
+ NSUserNotificationCenterDelegate,
+ };
+ use std::cell::OnceCell;
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use tauri::AppHandle;
+
+ static NATIVE_CLICK_READY: AtomicBool = AtomicBool::new(false);
+
+ thread_local! {
+ static DELEGATE: OnceCell<Retained<Delegate>> = const { OnceCell::new() };
+ }
+
+ struct DelegateIvars {
+ app: AppHandle,
+ }
+
+ define_class!(
+ // SAFETY:
+ // - NSObject has no subclassing requirements.
+ // - Delegate does not implement Drop.
+ #[unsafe(super(NSObject))]
+ #[thread_kind = MainThreadOnly]
+ #[name = "PakeUserNotificationDelegate"]
+ #[ivars = DelegateIvars]
+ struct Delegate;
+
+ unsafe impl NSObjectProtocol for Delegate {}
+
+ unsafe impl NSUserNotificationCenterDelegate for Delegate {
+ #[unsafe(method(userNotificationCenter:didActivateNotification:))]
+ fn did_activate(
+ &self,
+ _center: &NSUserNotificationCenter,
+ notification: &NSUserNotification,
+ ) {
+ let Some(identifier) = notification.identifier() else {
+ return;
+ };
+ // `rsplit_once` because a popup window label comes from the
+ // page's `window.open` name and may itself contain '|', while
+ // the id never can.
+ let identifier = identifier.to_string();
+ let Some((label, id)) = identifier.rsplit_once('|') else {
+ return;
+ };
+ if validate_id(id).is_err() {
+ return;
+ }
+ dispatch_click(&self.ivars().app, label, id);
+ }
+
+ // Show the banner even when Pake is frontmost: the window that owns
+ // the conversation may still be hidden or in the background, and the
+ // click is what routes the page there.
+ #[unsafe(method(userNotificationCenter:shouldPresentNotification:))]
+ fn should_present(
+ &self,
+ _center: &NSUserNotificationCenter,
+ _notification: &NSUserNotification,
+ ) -> bool {
+ true
+ }
+ }
+ );
+
+ impl Delegate {
+ fn new(mtm: MainThreadMarker, app: AppHandle) -> Retained<Self> {
+ let this = Self::alloc(mtm).set_ivars(DelegateIvars { app });
+ unsafe { msg_send![super(this), init] }
+ }
+ }
+
+ /// `defaultUserNotificationCenter` is nil for a process without a bundle
+ /// identifier (`pnpm run dev` runs the bare binary), and the class itself
+ /// disappears if a future macOS finally drops the deprecated API. Probe once
+ /// here rather than risking a nil dereference on every notification.
+ fn default_center(mtm: MainThreadMarker) -> Option<Retained<NSUserNotificationCenter>> {
+ let _ = mtm;
+ let class = AnyClass::get(c"NSUserNotificationCenter")?;
+ unsafe { msg_send![class, defaultUserNotificationCenter] }
+ }
+
+ pub fn init(app: &AppHandle) {
+ let Some(mtm) = MainThreadMarker::new() else {
+ return;
+ };
+ let Some(center) = default_center(mtm) else {
+ return;
+ };
+
+ DELEGATE.with(|cell| {
+ let delegate = cell.get_or_init(|| Delegate::new(mtm, app.clone()));
+ unsafe { center.setDelegate(Some(ProtocolObject::from_ref(&**delegate))) };
+ });
+ NATIVE_CLICK_READY.store(true, Ordering::SeqCst);
+ }
+
+ /// Returns whether the notification was handed to the native center. `false`
+ /// means the caller should fall back to the plugin path.
+ pub fn deliver(
+ app: &AppHandle,
+ window_label: &str,
+ params: &NotificationParams,
+ ) -> Result<bool, String> {
+ if !NATIVE_CLICK_READY.load(Ordering::SeqCst) {
+ return Ok(false);
+ }
+
+ let identifier = format!("{window_label}|{}", params.id);
+ let title = params.title.clone();
+ let body = params.body.clone();
+
+ app.run_on_main_thread(move || {
+ let Some(mtm) = MainThreadMarker::new() else {
+ return;
+ };
+ let Some(center) = default_center(mtm) else {
+ return;
+ };
+
+ let notification = NSUserNotification::new();
+ notification.setTitle(Some(&NSString::from_str(&title)));
+ notification.setInformativeText(Some(&NSString::from_str(&body)));
+ notification.setIdentifier(Some(&NSString::from_str(&identifier)));
+ center.deliverNotification(&notification);
+ })
+ .map_err(|e| format!("Failed to dispatch notification: {e}"))?;
+
+ Ok(true)
+ }
+
+ pub fn withdraw(app: &AppHandle, window_label: &str, id: &str) -> Result<(), String> {
+ let identifier = format!("{window_label}|{id}");
+ app.run_on_main_thread(move || {
+ let Some(mtm) = MainThreadMarker::new() else {
+ return;
+ };
+ let Some(center) = default_center(mtm) else {
+ return;
+ };
+ for notification in center.deliveredNotifications() {
+ if notification
+ .identifier()
+ .is_some_and(|value| value.to_string() == identifier)
+ {
+ center.removeDeliveredNotification(&notification);
+ }
+ }
+ })
+ .map_err(|e| format!("Failed to withdraw notification: {e}"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::validate_id;
+
+ #[test]
+ fn accepts_generated_ids() {
+ assert!(validate_id("pake-12-a1b2c3d4").is_ok());
+ assert!(validate_id("A_b-9").is_ok());
+ }
+
+ #[test]
+ fn rejects_ids_that_could_escape_an_eval_literal() {
+ for id in ["", "a'b", "a\\b", "a|b", "a b", "a\nb", "a;b"] {
+ assert!(validate_id(id).is_err(), "expected {id:?} to be rejected");
+ }
+ assert!(validate_id(&"a".repeat(65)).is_err());
+ }
+}
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 1f54c6f2..e03f8fb3 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -1301,10 +1301,11 @@ document.addEventListener("DOMContentLoaded", () => {
(function () {
const invoke = window.__TAURI__?.core?.invoke;
if (!invoke) return;
+ // Every webview Pake targets has EventTarget. Bail out instead of letting a
+ // ReferenceError from the class below abort the rest of this injected script.
+ if (typeof EventTarget !== "function" || typeof Event !== "function") return;
let permVal = "granted";
- let lastNotifTime = 0;
- let lastNotif = null;
// Pages that drive the badge directly via setAppBadge own its lifecycle;
// notifications-driven counts auto-clear on the next user interaction.
let pageManagedBadge = false;
@@ -1334,14 +1335,53 @@ document.addEventListener("DOMContentLoaded", () => {
return invoke("increment_dock_badge").catch(() => {});
};
+ // Notification click routing.
+ //
+ // On macOS the native center reports which notification was clicked and calls
+ // __pakeNotificationClick with its exact id (see app/notification.rs).
+ // Elsewhere the platform tells us nothing, so we approximate: a window that
+ // regains focus shortly after a notification arrived while it was in the
+ // background is treated as a click on that notification. The approximation is
+ // deliberately narrow -- one shot, time-limited, and cancelled by any in-page
+ // interaction -- because it cannot tell a notification click apart from the
+ // user switching back by hand.
+ const FOCUS_CLICK_WINDOW_MS = 60000;
+ const MAX_TRACKED_NOTIFICATIONS = 200;
+ const liveNotifications = new Map();
+ let notifSeq = 0;
+ let pendingFocusClick = null;
+ let interactionSeq = 0;
+
+ const withdrawNotification = (id) =>
+ invoke("close_notification", { id }).catch((error) => {
+ console.warn("[Pake] Failed to withdraw notification:", error);
+ });
+
+ const forgetNotification = (id) => {
+ liveNotifications.delete(id);
+ if (pendingFocusClick?.id === id) pendingFocusClick = null;
+ };
+
+ const clickNotification = (id) => {
+ const notif = liveNotifications.get(id);
+ if (!notif) return;
+ pendingFocusClick = null;
+ notif.dispatchEvent(new Event("click"));
+ };
+
window.addEventListener("focus", () => {
- if (lastNotif?.onclick && Date.now() - lastNotifTime < 5000) {
- lastNotif.onclick(new Event("click"));
- lastNotif = null;
- }
+ interactionSeq++;
+ const pending = pendingFocusClick;
+ pendingFocusClick = null;
+ if (!pending || Date.now() - pending.at > FOCUS_CLICK_WINDOW_MS) return;
+ clickNotification(pending.id);
});
const clearAutoBadge = () => {
+ interactionSeq++;
+ // A real interaction means the user is already reading the page, so a later
+ // focus is an app switch rather than a notification click.
+ pendingFocusClick = null;
if (pageManagedBadge || !autoBadgeActive) return;
autoBadgeActive = false;
clearBadge();
@@ -1349,35 +1389,124 @@ document.addEventListener("DOMContentLoaded", () => {
document.addEventListener("click", clearAutoBadge, true);
document.addEventListener("keydown", clearAutoBadge, true);
- const wrappedNotification = function (title, options) {
- const body = options?.body || "";
- let icon = options?.icon || "";
- if (icon.startsWith("/")) {
- icon = window.location.origin + icon;
+ // A real EventTarget, not a bare object with an onclick slot: pages commonly
+ // register their routing with addEventListener("click"), and the click
+ // handler needs event.target to be the notification it fired for.
+ class PakeNotification extends EventTarget {
+ constructor(title, options) {
+ super();
+ const opts = options || {};
+ Object.defineProperty(this, "_handlers", {
+ value: new Map(),
+ enumerable: false,
+ });
+
+ this.title = title === undefined ? "" : String(title);
+ this.body = opts.body ?? "";
+ this.tag = opts.tag ?? "";
+ this.data = opts.data ?? null;
+ this.dir = opts.dir ?? "auto";
+ this.lang = opts.lang ?? "";
+ this.silent = opts.silent ?? false;
+ this.requireInteraction = opts.requireInteraction ?? false;
+ this.timestamp = opts.timestamp ?? Date.now();
+
+ let icon = opts.icon || "";
+ if (icon.startsWith("/")) {
+ icon = window.location.origin + icon;
+ }
+ this.icon = icon;
+
+ // Must match the id charset validated in app/notification.rs.
+ const id = `pake-${++notifSeq}-${Math.random().toString(36).slice(2, 10)}`;
+ Object.defineProperty(this, "_id", { value: id, enumerable: false });
+
+ // A new notification with the same tag replaces the previous one, which
+ // must therefore stop being a click target.
+ if (this.tag) {
+ for (const other of liveNotifications.values()) {
+ if (other.tag === this.tag) other.close();
+ }
+ }
+ liveNotifications.set(id, this);
+ while (liveNotifications.size > MAX_TRACKED_NOTIFICATIONS) {
+ liveNotifications.values().next().value.close();
+ }
+
+ const raisedInBackground =
+ typeof document.hasFocus === "function" ? !document.hasFocus() : true;
+ const raisedAt = Date.now();
+ const raisedAfterInteraction = interactionSeq;
+ const sequence = notifSeq;
+ // Clear the older candidate immediately, rather than when this IPC reply
+ // arrives. Replies and native delivery may complete out of order.
+ pendingFocusClick = null;
+
+ invoke("send_notification", {
+ params: { id, title: this.title, body: this.body, icon: this.icon },
+ })
+ .then((outcome) => {
+ if (liveNotifications.get(id) !== this) {
+ // close/replacement may precede native delivery. Withdraw again
+ // after its acknowledgement, using this object's unique id.
+ return withdrawNotification(id);
+ }
+ const unread = raisedAfterInteraction === interactionSeq;
+ if (
+ unread &&
+ sequence === notifSeq &&
+ raisedInBackground &&
+ !outcome?.nativeClick
+ ) {
+ pendingFocusClick = { id, at: raisedAt };
+ }
+ this.dispatchEvent(new Event("show"));
+ if (unread) return incrementAutoBadge();
+ })
+ .catch(() => {
+ if (liveNotifications.get(id) !== this) return;
+ forgetNotification(id);
+ this.dispatchEvent(new Event("error"));
+ });
+ }
+
+ close() {
+ if (liveNotifications.get(this._id) !== this) return;
+ forgetNotification(this._id);
+ withdrawNotification(this._id);
+ // Notification events are tasks. A synchronous close handler can create
+ // another same-tag notification while the constructor is replacing it.
+ setTimeout(() => this.dispatchEvent(new Event("close")), 0);
}
+ }
- const notif = {
- onclick: null,
- onclose: null,
- onshow: null,
- onerror: null,
- close: () => {},
- };
-
- lastNotifTime = Date.now();
- lastNotif = notif;
- invoke("send_notification", { params: { title, body, icon } })
- .then(() => incrementAutoBadge())
- .then(() => {
- if (notif.onshow) notif.onshow(new Event("show"));
- });
+ for (const type of ["click", "close", "show", "error"]) {
+ Object.defineProperty(PakeNotification.prototype, `on${type}`, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ return this._handlers.get(type) || null;
+ },
+ set(handler) {
+ const previous = this._handlers.get(type);
+ if (previous) this.removeEventListener(type, previous);
+ if (typeof handler === "function") {
+ this._handlers.set(type, handler);
+ this.addEventListener(type, handler);
+ } else {
+ this._handlers.delete(type);
+ }
+ },
+ });
+ }
- return notif;
+ PakeNotification.requestPermission = (callback) => {
+ if (typeof callback === "function") callback(permVal);
+ return Promise.resolve(permVal);
};
-
- wrappedNotification.requestPermission = async () => "granted";
- Object.defineProperty(wrappedNotification, "permission", {
+ Object.defineProperty(PakeNotification, "permission", {
enumerable: true,
+ configurable: true,
get: () => permVal,
set: (v) => {
permVal = v;
@@ -1388,7 +1517,15 @@ document.addEventListener("DOMContentLoaded", () => {
Object.defineProperty(window, "Notification", {
configurable: true,
writable: true,
- value: wrappedNotification,
+ value: PakeNotification,
+ });
+ } catch (_) {}
+
+ try {
+ Object.defineProperty(window, "__pakeNotificationClick", {
+ configurable: true,
+ writable: true,
+ value: clickNotification,
});
} catch (_) {}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 9da1d13a..2aabc064 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -29,8 +29,9 @@ const GDK_BACKEND: &str = "GDK_BACKEND";
use app::{
invoke::{
- clear_dock_badge, download_file, increment_dock_badge, send_notification, set_dock_badge,
- set_dock_badge_label, set_zoom, update_theme_mode, webview_navigate,
+ clear_dock_badge, close_notification, download_file, increment_dock_badge,
+ send_notification, set_dock_badge, set_dock_badge_label, set_zoom, update_theme_mode,
+ webview_navigate,
},
setup::{set_global_shortcut, set_system_tray},
window::{
@@ -388,6 +389,7 @@ pub fn run_app() {
.invoke_handler(tauri::generate_handler![
download_file,
send_notification,
+ close_notification,
increment_dock_badge,
set_dock_badge,
set_dock_badge_label,
@@ -407,6 +409,10 @@ pub fn run_app() {
tauri_config.clone(),
));
+ // Main thread: installs the native notification-click delegate so a
+ // click can be routed back to the page that raised the notification.
+ app::notification::init_native_click(app.app_handle());
+
// --- Menu Construction Start ---
#[cfg(target_os = "macos")]
{
diff --git a/tests/integration/ipc-security.mjs b/tests/integration/ipc-security.mjs
index dab58307..f03da366 100644
--- a/tests/integration/ipc-security.mjs
+++ b/tests/integration/ipc-security.mjs
@@ -34,6 +34,7 @@ function page(stage, origin) {
url: ${JSON.stringify(origin + "/payload")}, filename: ${JSON.stringify(stage + ".txt")}
}});
results.zoom = await check("set_zoom", {percent: 100});
+ results.closeNotification = await check("close_notification", {id: "pake-probe-not-delivered"});
results.window = await check("plugin:window|is_fullscreen", {label: "pake"});
${
stage === "entry"
@@ -178,10 +179,16 @@ try {
assert.ok(reports.has("attacker"), "cross-origin page did not report");
const trusted = reports.get("entry");
const untrusted = reports.get("attacker");
- for (const command of ["download", "zoom", "window", "traversal"]) {
+ for (const command of [
+ "download",
+ "zoom",
+ "window",
+ "traversal",
+ "closeNotification",
+ ]) {
assert.equal(trusted[command], "allowed", `configured origin: ${command}`);
}
- for (const command of ["download", "zoom", "window"]) {
+ for (const command of ["download", "zoom", "window", "closeNotification"]) {
assert.match(
untrusted[command],
/^denied: .*not allowed/i,
diff --git a/tests/unit/event-clipboard-shortcuts.test.js b/tests/unit/event-clipboard-shortcuts.test.js
index 6eaf9645..929c13b9 100644
--- a/tests/unit/event-clipboard-shortcuts.test.js
+++ b/tests/unit/event-clipboard-shortcuts.test.js
@@ -69,7 +69,8 @@ function loadEventHelpers({
URL,
// Main-realm Date so tests can shift time seen by the fallback TTL.
Date,
- Event: class {},
+ Event,
+ EventTarget,
Notification: function Notification() {},
setTimeout,
clearTimeout,
diff --git a/tests/unit/event-fullscreen-shortcuts.test.js b/tests/unit/event-fullscreen-shortcuts.test.js
index 59a6c20a..a7900898 100644
--- a/tests/unit/event-fullscreen-shortcuts.test.js
+++ b/tests/unit/event-fullscreen-shortcuts.test.js
@@ -65,7 +65,8 @@ function loadEventHelpers({
const context = {
console,
URL,
- Event: class {},
+ Event,
+ EventTarget,
Notification: function Notification() {},
setTimeout,
clearTimeout,
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
index fa60c659..b916e85d 100644
--- a/tests/unit/event-link-guard.test.js
+++ b/tests/unit/event-link-guard.test.js
@@ -74,7 +74,8 @@ function loadEventHelpers({
const context = {
console,
URL,
- Event: class {},
+ Event,
+ EventTarget,
Notification: function Notification() {},
setTimeout,
clearTimeout,
@@ -836,6 +837,8 @@ describe("event link guard", () => {
"send_notification",
{
params: {
+ // Correlates the native click callback back to this instance.
+ id: expect.stringMatching(/^[A-Za-z0-9_-]{1,64}$/),
title: "Hello",
body: "World",
icon: "https://example.com/icon.png",
diff --git a/tests/unit/notification-bridge.test.js b/tests/unit/notification-bridge.test.js
new file mode 100644
index 00000000..3a7e5ef7
--- /dev/null
+++ b/tests/unit/notification-bridge.test.js
@@ -0,0 +1,436 @@
+import fs from "fs";
+import path from "path";
+import { runInNewContext } from "node:vm";
+import { describe, expect, it, vi } from "vitest";
+
+function createElement(tagName = "div") {
+ return {
+ tagName: tagName.toUpperCase(),
+ style: {},
+ children: [],
+ isContentEditable: false,
+ addEventListener: () => {},
+ appendChild(child) {
+ this.children.push(child);
+ return child;
+ },
+ removeChild(child) {
+ this.children = this.children.filter((item) => item !== child);
+ },
+ };
+}
+
+function loadNotificationBridge({
+ nativeClick = false,
+ hasFocus = false,
+ deferSend = false,
+} = {}) {
+ const source = ["link_policy.js", "event.js"]
+ .map((file) =>
+ fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject", file),
+ "utf-8",
+ ),
+ )
+ .join("\n");
+
+ const windowListeners = {};
+ const documentListeners = {};
+ const invokeCalls = [];
+ const sendRequests = [];
+ const body = createElement("body");
+
+ const context = {
+ console,
+ URL,
+ Event,
+ EventTarget,
+ setTimeout,
+ clearTimeout,
+ scrollTo: () => {},
+ navigator: {
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
+ platform: "MacIntel",
+ language: "en-US",
+ clipboard: { readText: () => Promise.resolve("") },
+ },
+ window: {
+ history: { back: () => {}, forward: () => {} },
+ location: {
+ href: "https://app.slack.com/client",
+ origin: "https://app.slack.com",
+ pathname: "/client",
+ reload: () => {},
+ },
+ localStorage: { getItem: () => null, setItem: () => {} },
+ addEventListener: (type, handler) => {
+ (windowListeners[type] = windowListeners[type] || []).push(handler);
+ },
+ dispatchEvent: () => {},
+ getSelection: () => ({ toString: () => "" }),
+ open: () => ({}),
+ isAuthLink: () => false,
+ isAuthPopup: () => false,
+ pakeConfig: {},
+ __TAURI__: {
+ core: {
+ invoke: (command, payload) => {
+ invokeCalls.push({ command, payload });
+ if (command === "send_notification") {
+ if (deferSend) {
+ return new Promise((resolve, reject) => {
+ sendRequests.push({ resolve, reject, payload });
+ });
+ }
+ return Promise.resolve({ nativeClick });
+ }
+ return Promise.resolve();
+ },
+ },
+ window: {
+ getCurrentWindow: () => ({
+ startDragging: () => {},
+ isFullscreen: () => Promise.resolve(false),
+ setFullscreen: () => Promise.resolve(),
+ }),
+ },
+ },
+ },
+ document: {
+ addEventListener: (type, handler) => {
+ (documentListeners[type] = documentListeners[type] || []).push(handler);
+ },
+ hasFocus: () => hasFocus,
+ createElement: (tagName) => createElement(tagName),
+ createRange: () => ({ selectNodeContents: vi.fn() }),
+ getElementById: () => null,
+ getElementsByTagName: () => [{ style: {} }],
+ body,
+ activeElement: body,
+ execCommand: () => true,
+ },
+ };
+ context.window.navigator = context.navigator;
+
+ runInNewContext(source, context);
+
+ const fire = (listeners, type, event) => {
+ for (const handler of listeners[type] || []) handler(event);
+ };
+
+ return {
+ Notification: context.window.Notification,
+ notificationClick: context.window.__pakeNotificationClick,
+ invokeCalls,
+ sendRequests,
+ focusWindow: () => fire(windowListeners, "focus", new Event("focus")),
+ clickInPage: () => fire(documentListeners, "click", new Event("click")),
+ // Drain the invoke promise chain that records the fallback state.
+ settle: () => new Promise((resolve) => setTimeout(resolve, 0)),
+ };
+}
+
+describe("notification bridge", () => {
+ it("queues close events so replacement cannot synchronously reenter Map iteration", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ let closeCalls = 0;
+ const retry = () => {
+ const notification = new bridge.Notification("retry", { tag: "thread" });
+ notification.onclose = () => {
+ closeCalls++;
+ if (closeCalls < 4) retry();
+ };
+ };
+ retry();
+ new bridge.Notification("replacement", { tag: "thread" });
+ expect(closeCalls).toBe(0);
+ await bridge.settle();
+ expect(closeCalls).toBe(1);
+ });
+ it("keeps the newest focus target when replies arrive out of order", async () => {
+ const bridge = loadNotificationBridge({ deferSend: true });
+ const older = new bridge.Notification("older");
+ const newer = new bridge.Notification("newer");
+ const oldClick = vi.fn();
+ const newClick = vi.fn();
+ older.onclick = oldClick;
+ newer.onclick = newClick;
+ bridge.sendRequests[1].resolve({ nativeClick: false });
+ await bridge.settle();
+ bridge.sendRequests[0].resolve({ nativeClick: false });
+ await bridge.settle();
+ bridge.focusWindow();
+ expect(oldClick).not.toHaveBeenCalled();
+ expect(newClick).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not revive a closed notification when delivery completes", async () => {
+ const bridge = loadNotificationBridge({ deferSend: true });
+ const notif = new bridge.Notification("closed");
+ const show = vi.fn();
+ const close = vi.fn();
+ notif.onshow = show;
+ notif.onclose = close;
+ notif.close();
+ notif.close();
+ bridge.sendRequests[0].resolve({ nativeClick: true });
+ await bridge.settle();
+ expect(show).not.toHaveBeenCalled();
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(
+ bridge.invokeCalls.filter(
+ (call) => call.command === "increment_dock_badge",
+ ),
+ ).toHaveLength(0);
+ expect(bridge.invokeCalls).toContainEqual({
+ command: "close_notification",
+ payload: { id: bridge.sendRequests[0].payload.params.id },
+ });
+ });
+
+ it("does not rearm a focus click or badge after an interaction before the reply", async () => {
+ const bridge = loadNotificationBridge({ deferSend: true });
+ const notif = new bridge.Notification("already read");
+ const click = vi.fn();
+ notif.onclick = click;
+ bridge.clickInPage();
+ bridge.sendRequests[0].resolve({ nativeClick: false });
+ await bridge.settle();
+ bridge.focusWindow();
+ expect(click).not.toHaveBeenCalled();
+ expect(
+ bridge.invokeCalls.filter(
+ (call) => call.command === "increment_dock_badge",
+ ),
+ ).toHaveLength(0);
+ });
+
+ it("withdraws the old native notification on a tag replacement", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ new bridge.Notification("older", { tag: "thread" });
+ await bridge.settle();
+ const oldId = bridge.invokeCalls[0].payload.params.id;
+ new bridge.Notification("newer", { tag: "thread" });
+ await bridge.settle();
+ expect(bridge.invokeCalls).toContainEqual({
+ command: "close_notification",
+ payload: { id: oldId },
+ });
+ });
+
+ it("does not revive replaced notifications on late errors or successful deliveries", async () => {
+ const bridge = loadNotificationBridge({ deferSend: true });
+ const older = new bridge.Notification("older", { tag: "thread" });
+ const middle = new bridge.Notification("middle", { tag: "thread" });
+ const newest = new bridge.Notification("newest", { tag: "thread" });
+ const oldError = vi.fn();
+ const middleShow = vi.fn();
+ const newestClick = vi.fn();
+ older.onerror = oldError;
+ middle.onshow = middleShow;
+ newest.onclick = newestClick;
+ bridge.sendRequests[2].resolve({ nativeClick: true });
+ bridge.sendRequests[1].resolve({ nativeClick: true });
+ bridge.sendRequests[0].reject(new Error("late delivery failure"));
+ await bridge.settle();
+ bridge.notificationClick(bridge.sendRequests[2].payload.params.id);
+ expect(oldError).not.toHaveBeenCalled();
+ expect(middleShow).not.toHaveBeenCalled();
+ expect(newestClick).toHaveBeenCalledTimes(1);
+ expect(
+ bridge.invokeCalls.filter(
+ (call) =>
+ call.command === "close_notification" &&
+ call.payload.id === bridge.sendRequests[1].payload.params.id,
+ ),
+ ).toHaveLength(2);
+ });
+
+ it("validates native click callback ids even if they come from old stored notifications", () => {
+ const source = fs.readFileSync("src-tauri/src/app/notification.rs", "utf8");
+ const callback = source.slice(
+ source.indexOf("fn did_activate("),
+ source.indexOf("fn should_present("),
+ );
+ expect(callback).toContain("validate_id(id)");
+ });
+
+ it("routes an addEventListener click handler with the notification as target", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ const notif = new bridge.Notification("Ann", { body: "hi" });
+ await bridge.settle();
+
+ const handler = vi.fn();
+ notif.addEventListener("click", handler);
+
+ const { id } = bridge.invokeCalls[0].payload.params;
+ bridge.notificationClick(id);
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(handler.mock.calls[0][0].target).toBe(notif);
+ });
+
+ it("supports the onclick property and reassignment", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ const notif = new bridge.Notification("Ann");
+ await bridge.settle();
+
+ const first = vi.fn();
+ const second = vi.fn();
+ notif.onclick = first;
+ expect(notif.onclick).toBe(first);
+ notif.onclick = second;
+
+ bridge.notificationClick(bridge.invokeCalls[0].payload.params.id);
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+
+ it("sends an id the Rust validator accepts", async () => {
+ const bridge = loadNotificationBridge();
+ new bridge.Notification("Ann");
+ await bridge.settle();
+
+ const { id } = bridge.invokeCalls[0].payload.params;
+ expect(id).toMatch(/^[A-Za-z0-9_-]{1,64}$/);
+ });
+
+ it("does not fire a phantom click on focus when the platform reports clicks", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ const notif = new bridge.Notification("Ann");
+ const handler = vi.fn();
+ notif.onclick = handler;
+ await bridge.settle();
+
+ bridge.focusWindow();
+
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("falls back to focus when the platform reports no click", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: false });
+ const notif = new bridge.Notification("Ann");
+ const handler = vi.fn();
+ notif.onclick = handler;
+ await bridge.settle();
+
+ bridge.focusWindow();
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it("fires the focus fallback only once", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: false });
+ const notif = new bridge.Notification("Ann");
+ const handler = vi.fn();
+ notif.onclick = handler;
+ await bridge.settle();
+
+ bridge.focusWindow();
+ bridge.focusWindow();
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it("skips the focus fallback for notifications raised while the page was focused", async () => {
+ const bridge = loadNotificationBridge({
+ nativeClick: false,
+ hasFocus: true,
+ });
+ const notif = new bridge.Notification("Ann");
+ const handler = vi.fn();
+ notif.onclick = handler;
+ await bridge.settle();
+
+ bridge.focusWindow();
+
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("cancels the focus fallback after the user interacts with the page", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: false });
+ const notif = new bridge.Notification("Ann");
+ const handler = vi.fn();
+ notif.onclick = handler;
+ await bridge.settle();
+
+ bridge.clickInPage();
+ bridge.focusWindow();
+
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("targets the newest notification when several are pending", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: false });
+ const older = new bridge.Notification("Ann");
+ const newer = new bridge.Notification("Bo");
+ const olderHandler = vi.fn();
+ const newerHandler = vi.fn();
+ older.onclick = olderHandler;
+ newer.onclick = newerHandler;
+ await bridge.settle();
+
+ bridge.focusWindow();
+
+ expect(olderHandler).not.toHaveBeenCalled();
+ expect(newerHandler).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops routing clicks to a notification replaced by the same tag", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ const older = new bridge.Notification("Ann", { tag: "dm-ann" });
+ const olderHandler = vi.fn();
+ older.onclick = olderHandler;
+ await bridge.settle();
+ const olderId = bridge.invokeCalls[0].payload.params.id;
+
+ new bridge.Notification("Ann again", { tag: "dm-ann" });
+ await bridge.settle();
+
+ bridge.notificationClick(olderId);
+
+ expect(olderHandler).not.toHaveBeenCalled();
+ });
+
+ it("stops routing clicks after close() and reports the close", async () => {
+ const bridge = loadNotificationBridge({ nativeClick: true });
+ const notif = new bridge.Notification("Ann");
+ await bridge.settle();
+ const { id } = bridge.invokeCalls[0].payload.params;
+
+ const clickHandler = vi.fn();
+ const closeHandler = vi.fn();
+ notif.onclick = clickHandler;
+ notif.onclose = closeHandler;
+
+ notif.close();
+ await bridge.settle();
+ bridge.notificationClick(id);
+
+ expect(closeHandler).toHaveBeenCalledTimes(1);
+ expect(clickHandler).not.toHaveBeenCalled();
+ });
+
+ it("exposes the standard permission surface", async () => {
+ const bridge = loadNotificationBridge();
+
+ expect(bridge.Notification.permission).toBe("granted");
+ await expect(bridge.Notification.requestPermission()).resolves.toBe(
+ "granted",
+ );
+ const callback = vi.fn();
+ await bridge.Notification.requestPermission(callback);
+ expect(callback).toHaveBeenCalledWith("granted");
+ });
+
+ it("resolves a root-relative icon against the page origin", async () => {
+ const bridge = loadNotificationBridge();
+ new bridge.Notification("Ann", { icon: "/avatar.png" });
+ await bridge.settle();
+
+ expect(bridge.invokeCalls[0].payload.params.icon).toBe(
+ "https://app.slack.com/avatar.png",
+ );
+ });
+});