Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: show alert, confirm and prompt in macOS apps
Tw933e7ab18d09d8
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.mdindex 970a612e..a970822a 100644--- a/.claude/rules/tauri-runtime.md+++ b/.claude/rules/tauri-runtime.md@@ -8,6 +8,7 @@ paths:- Native IPC is gated by the application command manifest in `src-tauri/build.rs`. Keep every registered app command in that manifest and grant only its required permissions. The packaged capability is local-only; `PakeConfig::remote_capability` grants the same permission set to exact configured entry origins (scheme, host, and port) before webviews load. Navigation flags, login redirects, subdomains, and restored URLs must not expand that grant. Keep local pages, secondary windows, loopback/IPv6 URLs, and literal hostname handling covered. ACL-denied downloads may fall back to browser attachments, but transient download anchors must bypass the IPC click interceptor to avoid recursion. Fullscreen must acquire native permission before mutating the player DOM; untrusted frame messages must never gain a top-level navigation fallback. Run `cargo test --lib` and `node tests/integration/ipc-security.mjs` (real macOS WebView); hiding `window.__TAURI__` or narrowing plugin capabilities alone does not gate application commands.- Injected CSS uses `src-tauri/src/inject/styles.js`: preserve DOM stylesheet order on ordinary pages; use constructable sheets only when CSP blocks the style element. `replaceSync` silently drops `@import`, so keep import-bearing CSS on its original DOM path, including escaped/case-insensitive at-keywords. Strict CSP plus imports remains unsupported. Run `node tests/browser/style-injection.mjs` with an installed Playwright runtime; mock CSSStyleSheet tests do not validate CSP or cascade behavior.- The `runtime-template` Cargo feature builds a prebuilt runtime that a separate builder customizes without a compiler: at launch it reads `pake-runtime/{pake.json, app.json, custom.js?, tray.png?}` from `Contents/Resources` on macOS or next to the executable elsewhere, and applies app.json's `identifier` and `productName` to the Tauri context before build. The CLI never enables the feature, so CLI-built apps keep their compiled configuration even if such a folder appears. A present but invalid override exits with a `[Pake]` message instead of falling back to the template's identity. A runtime app keys its WebView profile folder under the config dir (`%APPDATA%\<identifier>\EBWebView` on Windows) by identifier instead of product name (`data_dir_name`), so a rename keeps logins and a generated name cannot share another program's folder; CLI apps keep the product-name folder. On Windows a runtime app also sets the process AppUserModelID to its identifier before any window exists, so shortcuts carrying that ID group with the running window and toasts are attributed to it. Logic and tests live in `src-tauri/src/util.rs` (`apply_runtime_override`, `data_dir_name`, `set_app_user_model_id`); `PakeConfig::runtime_app` is the single runtime-app flag, and `run_app` copies the overridden identity from the returned Tauri config into the context; keep `cargo clippy` and `cargo test --lib` green both with and without `--features runtime-template`.+- A page's `alert()`, `confirm()` and `prompt()` show nothing in a WKWebView unless its UI delegate implements the three `runJavaScript…Panel` methods, and Wry 0.54.2's does not: `alert` returned at once, `confirm` returned false and `prompt` null in a millisecond, so a site that confirms before logging out did nothing (a user's report, 2026-11-17; WebView2 and WebKitGTK show their own). `src-tauri/src/app/script_dialogs.rs` adds the three methods to the delegate's class where it lacks them, for every webview from `build_window`, and then sets the same delegate on the webview again: WebKit records which methods a delegate answers when it is set, and without the reset the added methods are never called. Each panel is an NSAlert sheet on the page's window whose completion calls WebKit's handler exactly once (WebKit raises on zero or two calls), which keeps the script waiting as a browser does. The sheet goes on the window even when it is hidden, as a closed window is with hide-on-close: AppKit then shows the window with its sheet (measured: a window hidden with Cmd+W came back on screen when its page called `confirm()`), where an app-modal panel would float over whatever else the user is doing; only a webview with no window falls back to `runModal`. Cancel carries an explicit Escape key equivalent, because AppKit gives Escape only to a button titled Cancel and the Chinese title is 取消. Verify on a real bundle with a page that calls all three and writes what it got back: OK gives `true`, Cancel `false`, a prompt its field's text or `null`, and each wait is seconds, not a millisecond. Send the keys with a CGEvent tool of your own: Escape must give `false` and `null`, Return `true`. Cover it with `tests/unit/macos-script-dialogs.test.ts`.- `navigation_buttons` is a runtime-only macOS window field (no CLI flag; the paid apps set it, off by default): `src-tauri/src/app/nav_buttons.rs` adds Back and Forward to the title bar in a leading accessory beside the traffic lights, for people with a plain mouse who have neither the swipe nor Cmd-[. The buttons call `history_step`, the native step the Navigation menu uses, so they work on a blank error page; their action lives on the window's class as `tab_bar.rs`'s does. Enabled state follows the WKWebView's `canGoBack` and `canGoForward` by key-value observing; do not poll. The webview owns the observer through an associated object, which means the observer drops only while the webview is deallocating, when a weak reference to it already reads nil: removal in `Drop` never runs, so the observer unregisters on `NSWindowWillCloseNotification`, behind one flag because removing an unregistered observer raises (`auth.rs`'s delegate still has only the `Drop` removal). Alignment is to ink, checked on a 2x capture: each chevron's middle goes on the close button's centre line, read from `standardWindowButton:` (the lights sit 16 points down a 32 point bar on macOS 26) and from the cell's `imageRectForBounds:` (NSButton sets a 16 point image half a point above a 22 point button's middle), and redone on resize and around full screen. The chevrons are drawn, not `chevron.left`, because that symbol sits on a text baseline 1.5 points high. Labels are the system's own, 返回 and 前进, 上一頁 and 下一頁, through `UiLanguage`. A real-bundle check measures the rows of the red light and of each chevron in a `screencapture -l` PNG, whose centres must be equal, and opens then closes a Cmd+N window with the app still running. Under `hide_title_bar` the buttons sit over the page beside the lights, and the per-site `immersive` paddings in `style.js` clear only the lights' width. Cover it with `tests/unit/macos-navigation-buttons.test.ts` and the `navigation_buttons_are_opt_in` Rust test.- `transparent_title_bar` is a runtime-only macOS window field (no CLI flag; the paid apps set it): Tauri's `Transparent` title bar keeps the page below the bar, and `src-tauri/src/inject/title_bar.js` paints the window background with the page's top-edge color through `set_title_bar_color`. `hide_title_bar` keeps precedence and its overlay behavior. The color is the majority of three top-edge samples, resolved through a canvas so `oklch()`/`color()` values work; do not skip sampling for `document.hidden`, or windows revealed after load stay uncolored. Cover it with `tests/unit/title-bar-color.test.js`; when checking a real bundle, window captures carry the display profile, so convert the sRGB page color before comparing pixels.- Window/runtime options with platform-sensitive behavior include `--incognito`, `--new-window`, `--min-width`, `--min-height`, `--maximize`, multi-window behavior, notification click handling, and Linux/Wayland WebKit compositing defaults.diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rsindex e057fb24..9dba1a3b 100644--- a/src-tauri/src/app/mod.rs+++ b/src-tauri/src/app/mod.rs@@ -19,6 +19,8 @@ pub mod navigation;pub mod notification;#[cfg(any(target_os = "linux", target_os = "windows", test))]pub mod recovery;+#[cfg(target_os = "macos")]+pub mod script_dialogs;pub mod setup;#[cfg(target_os = "macos")]pub mod tab_bar;diff --git a/src-tauri/src/app/script_dialogs.rs b/src-tauri/src/app/script_dialogs.rsnew file mode 100644index 00000000..3a691ace--- /dev/null+++ b/src-tauri/src/app/script_dialogs.rs@@ -0,0 +1,301 @@+//! `alert()`, `confirm()` and `prompt()` for pages in a macOS app.+//!+//! WKWebView shows none of the three by itself: it asks its UI delegate, and+//! when the delegate has no answer `alert` returns at once, `confirm` returns+//! false and `prompt` returns null. Wry's delegate implements none of them, so a+//! site that asks "Log out?" before logging out did nothing when clicked.+//!+//! The three delegate methods are added to the delegate's own class, resolved+//! from a live webview as `tab_bar.rs` resolves the window's, and only where+//! the class does not answer them already, so a Wry that grows its own keeps+//! it. WebKit notes which methods a delegate answers when the delegate is set,+//! so after adding them the same delegate is set again, or WebKit goes on+//! believing it has none. Each shows a native alert as a sheet on the page's window and hands+//! WebKit's completion handler the answer when it is dismissed, which is what+//! keeps the page's script waiting, as in a browser.++use block2::{Block, RcBlock};+use objc2::ffi::class_addMethod;+use objc2::rc::Retained;+use objc2::runtime::{AnyClass, AnyObject, Bool, Imp, Sel};+use objc2::{msg_send, sel, MainThreadMarker};+use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn, NSTextField};+use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};+use std::cell::Cell;+use std::ffi::c_char;++use crate::util::UiLanguage;++/// `void (id webView, NSString *message, WKFrameInfo *frame, block)`.+const MESSAGE_PANEL_TYPES: &[u8] = b"v@:@@@@?\0";+/// The text panel carries the default text before the frame.+const TEXT_PANEL_TYPES: &[u8] = b"v@:@@@@@?\0";+const PROMPT_FIELD_WIDTH: f64 = 260.0;+const PROMPT_FIELD_HEIGHT: f64 = 24.0;++/// The two buttons as AppKit names them in each language.+fn button_titles() -> (&'static str, &'static str) {+ match UiLanguage::system() {+ UiLanguage::English => ("OK", "Cancel"),+ UiLanguage::SimplifiedChinese | UiLanguage::TraditionalChinese => ("好", "取消"),+ }+}++/// What the page asked for; only `alert` has no way to say no.+#[derive(Clone, Copy, PartialEq)]+enum Panel {+ Alert,+ Confirm,+ Prompt,+}++/// Show one panel for `webview` and call `finish` exactly once with whether it+/// was accepted and, for a prompt, the text in its field.+///+/// # Safety+/// Main thread only; `webview` is the live WKWebView WebKit passed in, and the+/// strings are valid `NSString` pointers or null.+unsafe fn present(+ webview: *mut AnyObject,+ message: *mut NSString,+ default_text: *mut NSString,+ panel: Panel,+ finish: Box<dyn FnOnce(bool, Option<Retained<NSString>>)>,+) {+ let Some(mtm) = MainThreadMarker::new() else {+ finish(false, None);+ return;+ };+ let alert = NSAlert::new(mtm);+ match message.as_ref() {+ Some(message) => alert.setMessageText(message),+ None => alert.setMessageText(&NSString::new()),+ }+ let field = (panel == Panel::Prompt).then(|| {+ let field = NSTextField::initWithFrame(+ mtm.alloc(),+ NSRect::new(+ NSPoint::new(0.0, 0.0),+ NSSize::new(PROMPT_FIELD_WIDTH, PROMPT_FIELD_HEIGHT),+ ),+ );+ if let Some(text) = default_text.as_ref() {+ field.setStringValue(text);+ }+ alert.setAccessoryView(Some(&field));+ field+ });+ let (accept, cancel) = button_titles();+ alert.addButtonWithTitle(&NSString::from_str(accept));+ if panel != Panel::Alert {+ let cancel = alert.addButtonWithTitle(&NSString::from_str(cancel));+ // AppKit gives Escape to a button titled Cancel, which a translated+ // title is not, so it is bound here.+ cancel.setKeyEquivalent(&NSString::from_str("\u{1b}"));+ }+ if let Some(field) = &field {+ alert.layout();+ alert.window().makeFirstResponder(Some(field));+ }++ // WebKit raises if its handler is never called and again if it is called+ // twice, so the answer leaves through a slot that empties on first use.+ let finish = Cell::new(Some(finish));+ let shown = alert.clone();+ let answer = RcBlock::new(move |response: isize| {+ // Held until the panel is dismissed.+ let _ = &shown;+ let Some(finish) = finish.take() else {+ return;+ };+ let accepted = response == NSAlertFirstButtonReturn;+ let text = field+ .as_ref()+ .filter(|_| accepted)+ .map(|field| field.stringValue());+ finish(accepted, text);+ });++ let window: *mut AnyObject = if webview.is_null() {+ std::ptr::null_mut()+ } else {+ msg_send![webview, window]+ };+ if window.is_null() {+ // No window to hang a sheet on: an app-modal panel still answers.+ let response = alert.runModal();+ answer.call((response,));+ return;+ }+ // On the page's own window even when that window is hidden or minimised,+ // as a closed window is with hide-on-close: the sheet shows with the+ // window, and until then the page waits as a background tab's does. An+ // app-modal panel here would float over whatever else the user is doing.+ let _: () = msg_send![&*alert, beginSheetModalForWindow: window, completionHandler: &*answer];+}++extern "C" fn run_alert(+ _this: &AnyObject,+ _cmd: Sel,+ webview: *mut AnyObject,+ message: *mut NSString,+ _frame: *mut AnyObject,+ handler: *mut Block<dyn Fn()>,+) {+ // SAFETY: WebKit calls this on the main thread with a live webview and a+ // completion handler it expects back exactly once.+ unsafe {+ let Some(done) = RcBlock::copy(handler) else {+ return;+ };+ present(+ webview,+ message,+ std::ptr::null_mut(),+ Panel::Alert,+ Box::new(move |_, _| done.call(())),+ );+ }+}++extern "C" fn run_confirm(+ _this: &AnyObject,+ _cmd: Sel,+ webview: *mut AnyObject,+ message: *mut NSString,+ _frame: *mut AnyObject,+ handler: *mut Block<dyn Fn(Bool)>,+) {+ // SAFETY: as `run_alert`.+ unsafe {+ let Some(done) = RcBlock::copy(handler) else {+ return;+ };+ present(+ webview,+ message,+ std::ptr::null_mut(),+ Panel::Confirm,+ Box::new(move |accepted, _| done.call((Bool::new(accepted),))),+ );+ }+}++extern "C" fn run_prompt(+ _this: &AnyObject,+ _cmd: Sel,+ webview: *mut AnyObject,+ message: *mut NSString,+ default_text: *mut NSString,+ _frame: *mut AnyObject,+ handler: *mut Block<dyn Fn(*mut NSString)>,+) {+ // SAFETY: as `run_alert`.+ unsafe {+ let Some(done) = RcBlock::copy(handler) else {+ return;+ };+ present(+ webview,+ message,+ default_text,+ Panel::Prompt,+ Box::new(move |_, text| match text {+ Some(text) => done.call((Retained::as_ptr(&text) as *mut NSString,)),+ None => done.call((std::ptr::null_mut(),)),+ }),+ );+ }+}++/// Teach this webview's UI delegate to show the three script panels.+/// Idempotent: later webviews find the methods already on the class.+pub fn install(webview: &tauri::webview::PlatformWebview) {+ let view = webview.inner() as *mut AnyObject;+ if view.is_null() {+ eprintln!("[Pake] Failed to access WKWebView for its script dialogs");+ return;+ }+ // SAFETY: Tauri runs this on the main thread with the live WKWebView.+ unsafe {+ let delegate: *mut AnyObject = msg_send![view, UIDelegate];+ if delegate.is_null() {+ eprintln!("[Pake] The WKWebView has no UI delegate for its script dialogs");+ return;+ }+ let class: *const AnyClass = msg_send![delegate, class];+ let class = &*class;+ let alert: Imp = std::mem::transmute::<+ extern "C" fn(+ &AnyObject,+ Sel,+ *mut AnyObject,+ *mut NSString,+ *mut AnyObject,+ *mut Block<dyn Fn()>,+ ),+ Imp,+ >(run_alert);+ let confirm: Imp = std::mem::transmute::<+ extern "C" fn(+ &AnyObject,+ Sel,+ *mut AnyObject,+ *mut NSString,+ *mut AnyObject,+ *mut Block<dyn Fn(Bool)>,+ ),+ Imp,+ >(run_confirm);+ let prompt: Imp = std::mem::transmute::<+ extern "C" fn(+ &AnyObject,+ Sel,+ *mut AnyObject,+ *mut NSString,+ *mut NSString,+ *mut AnyObject,+ *mut Block<dyn Fn(*mut NSString)>,+ ),+ Imp,+ >(run_prompt);+ for (selector, imp, types) in [+ (+ sel!(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:),+ alert,+ MESSAGE_PANEL_TYPES,+ ),+ (+ sel!(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:),+ confirm,+ MESSAGE_PANEL_TYPES,+ ),+ (+ sel!(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:),+ prompt,+ TEXT_PANEL_TYPES,+ ),+ ] {+ if class.instance_method(selector).is_some() {+ continue;+ }+ let added = class_addMethod(+ class as *const AnyClass as *mut AnyClass,+ selector,+ imp,+ types.as_ptr() as *const c_char,+ );+ if !added.as_bool() {+ eprintln!("[Pake] Failed to install a script dialog on the UI delegate.");+ }+ }+ // Every webview, not only the first: each one cached its delegate's+ // answers when Wry set it, before the methods were there.+ let Some(delegate) = Retained::retain(delegate) else {+ return;+ };+ let none: *mut AnyObject = std::ptr::null_mut();+ let _: () = msg_send![view, setUIDelegate: none];+ let _: () = msg_send![view, setUIDelegate: &*delegate];+ }+}diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 489e7489..b680588a 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -1052,6 +1052,15 @@ fn build_window(eprintln!("[Pake] Failed to access WKWebView for history swipe gestures: {error}");}+ // A page's alert(), confirm() and prompt() show nothing in a WKWebView+ // unless its UI delegate answers, and Wry's does not: every window's does.+ #[cfg(target_os = "macos")]+ if let Err(error) = window.with_webview(|webview| {+ crate::app::script_dialogs::install(&webview);+ }) {+ eprintln!("[Pake] Failed to access WKWebView for its script dialogs: {error}");+ }+// The tab bar's + button exists only while some window class answers// `newWindowForTab:`. Install it for every tabbing window, the main one// included: its tab bar is the one the user sees first.diff --git a/tests/unit/macos-script-dialogs.test.ts b/tests/unit/macos-script-dialogs.test.tsnew file mode 100644index 00000000..3eb9bc9d--- /dev/null+++ b/tests/unit/macos-script-dialogs.test.ts@@ -0,0 +1,77 @@+import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++const rustRoot = path.join(process.cwd(), 'src-tauri', 'src');+const read = (relative: string) =>+ fs.readFileSync(path.join(rustRoot, relative), 'utf8');++describe('macOS alert(), confirm() and prompt()', () => {+ it('is installed on every webview the one window builder makes', () => {+ const modules = read('app/mod.rs');+ expect(modules).toMatch(+ /#\[cfg\(target_os = "macos"\)\]\npub mod script_dialogs;/,+ );++ const window = read('app/window.rs');+ const start = window.indexOf('fn build_window(');+ const end = window.indexOf('\n}\n', start);+ expect(window.slice(start, end)).toMatch(+ /#\[cfg\(target_os = "macos"\)\]\s+if let Err\(error\) = window\.with_webview\(\|webview\| \{\s+crate::app::script_dialogs::install\(&webview\);/,+ );+ });++ it('answers the three WKUIDelegate panels WebKit would otherwise skip', () => {+ const dialogs = read('app/script_dialogs.rs');+ for (const selector of [+ 'webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:',+ 'webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:',+ 'webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:',+ ]) {+ expect(dialogs).toContain(`sel!(${selector})`);+ }+ // Added only where the delegate's class has no answer of its own.+ expect(dialogs).toContain('if class.instance_method(selector).is_some() {');+ });++ it('sets the delegate again, since WebKit caches what it answers', () => {+ const dialogs = read('app/script_dialogs.rs');+ const added = dialogs.indexOf('class_addMethod(');+ const reset = dialogs.indexOf('msg_send![view, setUIDelegate: none]');+ const restored = dialogs.indexOf(+ 'msg_send![view, setUIDelegate: &*delegate]',+ );+ expect(added).toBeGreaterThan(-1);+ // Without this the methods exist and are never called: the page still+ // gets false from confirm() in a millisecond.+ expect(reset).toBeGreaterThan(added);+ expect(restored).toBeGreaterThan(reset);+ });++ it('hands WebKit its answer exactly once, when the sheet is dismissed', () => {+ const dialogs = read('app/script_dialogs.rs');+ expect(dialogs).toContain('beginSheetModalForWindow: window');+ expect(dialogs).toContain('let finish = Cell::new(Some(finish));');+ expect(dialogs).toContain('let Some(finish) = finish.take() else {');+ // Cancel is false for confirm() and null for prompt(), as in a browser.+ expect(dialogs).toContain(+ 'let accepted = response == NSAlertFirstButtonReturn;',+ );+ expect(dialogs).toContain('None => done.call((std::ptr::null_mut(),)),');+ });++ it('keeps the panel on the page window and Escape on Cancel', () => {+ const dialogs = read('app/script_dialogs.rs');+ // A hidden or minimised window still gets a sheet, which AppKit shows+ // with the window; only a webview with no window gets an app-modal panel.+ const fallback = dialogs.indexOf('if window.is_null() {');+ const modal = dialogs.indexOf('alert.runModal()');+ expect(fallback).toBeGreaterThan(-1);+ expect(modal).toBeGreaterThan(fallback);+ expect(dialogs).not.toMatch(/isVisible/);+ // AppKit binds Escape only to a button titled "Cancel"; 取消 is not.+ expect(dialogs).toContain(+ 'cancel.setKeyEquivalent(&NSString::from_str("\\u{1b}"));',+ );+ });+});