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: support notification events on legacy WebKit

Tw93f454f05f290d
diff --git a/AGENTS.md b/AGENTS.md
index 8f1d412d..af1f4d2a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -127,7 +127,7 @@ Oracles per row live under `tests/unit/` (for example `event-link-guard.test.js`
- WebKit subframes need `initialization_script_for_all_frames` for the lightweight config/auth/link bridge. Keep page UI and clipboard injection separate. `link_policy.js` owns internal URL matching for the main page and `frame_links.js`; the receiver must recheck descendant source, protocol, internal/auth classification, and force policy before calling the external opener. Never route frame messages through top-level internal navigation: sandboxed content can forge them. Preserve native blank/two-stage, named-frame, auth, and download behavior; known external iframe links are the repaired surface. Cover pre-DOMContentLoaded messages and discard queued messages when the document leaves.
- Find's DOM-mark fallback must not observe its own highlighter mutations. Pause observation while rescanning/updating marks, then resume only while Find is open; real page edits must still refresh results. A mock without MutationObserver cannot prove this path. Icon download deadlines likewise cover response bodies, not just response headers.
- Safe clipboard shortcuts (Ctrl+C/X/V/A) on Linux/Windows are bridged in `src-tauri/src/inject/event.js`. Copy/cut/select-all stay in the trusted `handleClipboardShortcut` keydown path; Ctrl+V must leave keydown unhandled so the native WebView paste event preserves images, files, and rich formats, with text-only `navigator.clipboard.readText()` fallback allowed only from a trusted keyup when no native paste event fired. The bridge is gated on `isNonMacDesktop()` and `event.isTrusted`, only acts on editable/selected targets, and must never fire on macOS (native shortcuts already work). Locked by `event-clipboard-shortcuts.test.js` tests `lets native paste preserve non-text clipboard data` and `falls back to clipboard text only when native paste does not fire`.
-- Notification flows cross injected JS, Tauri invokes, capabilities, and native notification plugins. Verify the Rust capability and JS caller together. macOS clicks and withdrawals use the originating window label plus a validated notification id; closed or tag-replaced objects must remain closed when IPC replies arrive late. Queue `close` events as tasks so handlers cannot mutate a live Map during replacement. Windows/Linux retain a limited focus heuristic, not a native click callback. Cover deferred replies and close-handler reentry in `tests/unit/notification-bridge.test.js`, and verify macOS click routing, hidden-window reveal, and withdrawal with a real bundled app.
+- Notification flows cross injected JS, Tauri invokes, capabilities, and native notification plugins. Verify the Rust capability and JS caller together. macOS clicks and withdrawals use the originating window label plus a validated notification id; closed or tag-replaced objects must remain closed when IPC replies arrive late. Queue `close` events as tasks so handlers cannot mutate a live Map during replacement. Safari before 14 exposes an `EventTarget` interface without a usable constructor; retain a native DOM event target fallback for the macOS 10.13 deployment floor, and cover both paths with `node --test tests/browser/notification-bridge.mjs`. Windows/Linux retain a limited focus heuristic, not a native click callback. Cover deferred replies and close-handler reentry in `tests/unit/notification-bridge.test.js`, and verify macOS click routing, hidden-window reveal, and withdrawal with a real bundled app.
- WebKit compositing behavior is platform-sensitive on Linux/Wayland. Runtime flag decisions live in `src-tauri/src/lib.rs`; keep the default conservative, cover compositor exceptions with unit tests, and document user-facing fallbacks in `docs/faq*.md`. WebKitGTK 2.52+ uses SHM instead of disabling the renderer on both X11 and Wayland (#1374, #1386): either legacy flag turns hardware acceleration off and crashes video. Use the loaded library version, preserve explicit variables, and keep older WebKit on its existing path. Keep the niri exception in both legacy gates and test the combined mode, including safe-mode overrides.
- Linux AppImage reports often include harmless GTK, appindicator, or GStreamer warnings. Separate optional runtime warnings from the actual symptom before changing code; input/click failures on pure Wayland compositors are not the same class as blank-window failures.
- Stable `V*` Docker publication updates both the version tag and `latest`; verify matching registry manifest digests and the image's source revision. Quality validates the actual image CLI and both DEB/AppImage artifacts before a release tag is pushed. AppImage bundling requires `xdg-open` from `xdg-utils` in the image: a successful image build or DEB alone does not cover that dependency. Require both requested artifacts because the CLI intentionally allows partial success across formats.
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index e03f8fb3..40e2ce1b 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -1301,10 +1301,24 @@ 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 NotificationEventTarget = EventTarget;
+ try {
+ new EventTarget();
+ } catch (_) {
+ // Safari before 14 exposes EventTarget but its constructor throws. A
+ // fragment already has native event state and keeps event.target exact.
+ NotificationEventTarget = class extends EventTarget {
+ constructor() {
+ return Object.setPrototypeOf(
+ document.createDocumentFragment(),
+ new.target.prototype,
+ );
+ }
+ };
+ }
+
let permVal = "granted";
// Pages that drive the badge directly via setAppBadge own its lifecycle;
// notifications-driven counts auto-clear on the next user interaction.
@@ -1392,7 +1406,7 @@ document.addEventListener("DOMContentLoaded", () => {
// 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 {
+ class PakeNotification extends NotificationEventTarget {
constructor(title, options) {
super();
const opts = options || {};
diff --git a/tests/browser/notification-bridge.mjs b/tests/browser/notification-bridge.mjs
new file mode 100644
index 00000000..506a12c6
--- /dev/null
+++ b/tests/browser/notification-bridge.mjs
@@ -0,0 +1,95 @@
+// Real DOM coverage for constructible and legacy non-constructible EventTarget.
+import assert from "node:assert/strict";
+import fs from "node:fs/promises";
+import { pathToFileURL } from "node:url";
+import { test, before, after } from "node:test";
+
+const { chromium } = await import(
+ process.env.PAKE_PLAYWRIGHT_MODULE
+ ? pathToFileURL(process.env.PAKE_PLAYWRIGHT_MODULE).href
+ : "playwright"
+);
+const source = await Promise.all(
+ ["link_policy.js", "event.js"].map((name) =>
+ fs.readFile(
+ `${process.env.PAKE_INJECT_ROOT || "src-tauri/src/inject"}/${name}`,
+ "utf8",
+ ),
+ ),
+);
+let browser;
+before(async () => {
+ browser = await chromium.launch({
+ headless: true,
+ ...(process.env.PAKE_BROWSER_EXECUTABLE
+ ? { executablePath: process.env.PAKE_BROWSER_EXECUTABLE }
+ : {}),
+ });
+});
+after(async () => browser?.close());
+
+for (const legacy of [false, true]) {
+ test(`notification event identity, legacy constructor ${legacy}`, async () => {
+ const page = await browser.newPage();
+ try {
+ await page.route("**/*", (route) =>
+ route.fulfill({ contentType: "text/html", body: "<!doctype html>" }),
+ );
+ await page.goto("https://pake-notification.test/");
+ const result = await page.evaluate(
+ async ({ source, legacy }) => {
+ if (legacy) {
+ window.EventTarget = class extends EventTarget {
+ constructor() {
+ throw new TypeError("Illegal constructor");
+ }
+ };
+ }
+ window.__TAURI__ = {
+ core: { invoke: () => Promise.resolve({ nativeClick: true }) },
+ };
+ for (const script of source) (0, eval)(script);
+ class Derived extends Notification {}
+ const notification = new Derived("Event identity");
+ let calls = 0;
+ let exactIdentity = false;
+ function once(event) {
+ calls++;
+ exactIdentity =
+ event.target === notification &&
+ event.currentTarget === notification &&
+ this === notification;
+ }
+ notification.addEventListener("click", once, { once: true });
+ const removed = () => {
+ calls += 10;
+ };
+ notification.addEventListener("click", removed);
+ notification.removeEventListener("click", removed);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ window.__pakeNotificationClick(notification._id);
+ window.__pakeNotificationClick(notification._id);
+ notification.close();
+ window.__pakeNotificationClick(notification._id);
+ return {
+ calls,
+ exactIdentity,
+ notificationInstance: notification instanceof Notification,
+ eventTargetInstance: notification instanceof EventTarget,
+ derivedInstance: notification instanceof Derived,
+ };
+ },
+ { source, legacy },
+ );
+ assert.deepEqual(result, {
+ calls: 1,
+ exactIdentity: true,
+ notificationInstance: true,
+ eventTargetInstance: true,
+ derivedInstance: true,
+ });
+ } finally {
+ await page.close();
+ }
+ });
+}
diff --git a/tests/unit/notification-bridge.test.js b/tests/unit/notification-bridge.test.js
index 3a7e5ef7..33bd9a88 100644
--- a/tests/unit/notification-bridge.test.js
+++ b/tests/unit/notification-bridge.test.js
@@ -24,6 +24,7 @@ function loadNotificationBridge({
nativeClick = false,
hasFocus = false,
deferSend = false,
+ legacyEventTarget = false,
} = {}) {
const source = ["link_policy.js", "event.js"]
.map((file) =>
@@ -44,7 +45,13 @@ function loadNotificationBridge({
console,
URL,
Event,
- EventTarget,
+ EventTarget: legacyEventTarget
+ ? class extends EventTarget {
+ constructor() {
+ throw new TypeError("Illegal constructor");
+ }
+ }
+ : EventTarget,
setTimeout,
clearTimeout,
scrollTo: () => {},
@@ -102,6 +109,7 @@ function loadNotificationBridge({
},
hasFocus: () => hasFocus,
createElement: (tagName) => createElement(tagName),
+ createDocumentFragment: () => new EventTarget(),
createRange: () => ({ selectNodeContents: vi.fn() }),
getElementById: () => null,
getElementsByTagName: () => [{ style: {} }],
@@ -131,6 +139,26 @@ function loadNotificationBridge({
}
describe("notification bridge", () => {
+ it("preserves native event identity when EventTarget is not constructible", async () => {
+ const bridge = loadNotificationBridge({
+ nativeClick: true,
+ legacyEventTarget: true,
+ });
+ const notification = new bridge.Notification("Legacy WebKit");
+ const clicks = [];
+ notification.addEventListener("click", (event) => {
+ clicks.push([event.target, event.currentTarget]);
+ });
+ await bridge.settle();
+ bridge.notificationClick(notification._id);
+ expect(clicks).toEqual([[notification, notification]]);
+ notification.close();
+ expect(bridge.invokeCalls.at(-1)).toEqual({
+ command: "close_notification",
+ payload: { id: notification._id },
+ });
+ });
+
it("queues close events so replacement cannot synchronously reenter Map iteration", async () => {
const bridge = loadNotificationBridge({ nativeClick: true });
let closeCalls = 0;