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: macOS --new-window crash and Rust panic safety (#1194)
Tw93847154ee0b0d
diff --git a/src-tauri/src/app/setup.rs b/src-tauri/src/app/setup.rsindex ff6e5e6a..87f27bb8 100644--- a/src-tauri/src/app/setup.rs+++ b/src-tauri/src/app/setup.rs@@ -119,49 +119,54 @@ pub fn set_global_shortcut(let app_handle = app.clone();let shortcut_hotkey = match Shortcut::from_str(&shortcut) {Ok(s) => s,- Err(_) => return Ok(()),+ Err(error) => {+ eprintln!("[Pake] Invalid activation shortcut '{shortcut}': {error}");+ return Ok(());+ }};let last_triggered = Arc::new(Mutex::new(Instant::now()));- app_handle- .plugin(- tauri_plugin_global_shortcut::Builder::new()- .with_handler({- let last_triggered = Arc::clone(&last_triggered);- move |app, event, _shortcut| {- let Ok(mut last_triggered) = last_triggered.lock() else {- return;- };- if Instant::now().duration_since(*last_triggered)- < Duration::from_millis(300)- {- return;- }- *last_triggered = Instant::now();+ if let Err(error) = app_handle.plugin(+ tauri_plugin_global_shortcut::Builder::new()+ .with_handler({+ let last_triggered = Arc::clone(&last_triggered);+ move |app, event, _shortcut| {+ let Ok(mut last_triggered) = last_triggered.lock() else {+ return;+ };+ if Instant::now().duration_since(*last_triggered) < Duration::from_millis(300) {+ return;+ }+ *last_triggered = Instant::now();- if shortcut_hotkey.eq(event) {- if let Some(window) = app.get_webview_window("pake") {- let is_visible = window.is_visible().unwrap_or(false);- if is_visible {- let _ = window.hide();- } else {- let _ = window.show();- let _ = window.set_focus();- #[cfg(target_os = "linux")]- if _init_fullscreen && !window.is_fullscreen().unwrap_or(false)- {- let _ = window.set_fullscreen(true);- }+ if shortcut_hotkey.eq(event) {+ if let Some(window) = app.get_webview_window("pake") {+ let is_visible = window.is_visible().unwrap_or(false);+ if is_visible {+ let _ = window.hide();+ } else {+ let _ = window.show();+ let _ = window.set_focus();+ #[cfg(target_os = "linux")]+ if _init_fullscreen && !window.is_fullscreen().unwrap_or(false) {+ let _ = window.set_fullscreen(true);}}}}- })- .build(),- )- .expect("Failed to set global shortcut");+ }+ })+ .build(),+ ) {+ eprintln!(+ "[Pake] Failed to register global shortcut plugin '{shortcut}': {error}; continuing without it."+ );+ return Ok(());+ }- let _ = app.global_shortcut().register(shortcut_hotkey);+ if let Err(error) = app.global_shortcut().register(shortcut_hotkey) {+ eprintln!("[Pake] Failed to bind global shortcut '{shortcut}': {error}");+ }Ok(())}diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex d98cd65b..2535d981 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -50,8 +50,12 @@ impl MultiWindowState {}}-pub fn set_window(app: &AppHandle, config: &PakeConfig, tauri_config: &Config) -> WebviewWindow {- build_window_with_label(app, config, tauri_config, "pake").expect("Failed to build window")+pub fn set_window(+ app: &AppHandle,+ config: &PakeConfig,+ tauri_config: &Config,+) -> tauri::Result<WebviewWindow> {+ build_window_with_label(app, config, tauri_config, "pake")}pub fn open_additional_window(app: &AppHandle) -> tauri::Result<WebviewWindow> {@@ -67,7 +71,6 @@ struct WindowBuildOptions<'a> {new_window_features: Option<NewWindowFeatures>,}-#[cfg(not(target_os = "macos"))]fn open_requested_window(app: &AppHandle,config: &PakeConfig,@@ -123,10 +126,12 @@ fn build_window_with_label(tauri_config: &Config,label: &str,) -> tauri::Result<WebviewWindow> {- let window_config = config- .windows- .first()- .expect("At least one window configuration is required");+ let window_config = config.windows.first().ok_or_else(|| {+ tauri::Error::Io(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "pake.json must define at least one window configuration",+ ))+ })?;let url = match window_config.url_type.as_str() {"web" => {let parsed = window_config.url.parse().map_err(|err| {@@ -178,12 +183,14 @@ fn build_window(.product_name.clone().unwrap_or_else(|| "pake".to_string());- let _data_dir = get_data_dir(app, package_name);+ let _data_dir = get_data_dir(app, package_name).map_err(tauri::Error::Io)?;- let window_config = config- .windows- .first()- .expect("At least one window configuration is required");+ let window_config = config.windows.first().ok_or_else(|| {+ tauri::Error::Io(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "pake.json must define at least one window configuration",+ ))+ })?;let user_agent = config.user_agent.get();@@ -254,40 +261,34 @@ fn build_window(}if window_config.new_window {- #[cfg(target_os = "macos")]- {- window_builder =- window_builder.on_new_window(|_target_url, _features| NewWindowResponse::Allow);- }-- #[cfg(not(target_os = "macos"))]- {- let app_handle = app.clone();- let popup_config = config.clone();- let popup_tauri_config = tauri_config.clone();- window_builder =- window_builder.on_new_window(- move |target_url, features| match open_requested_window(- &app_handle,- &popup_config,- &popup_tauri_config,- target_url,- features,- ) {- Ok(window) => NewWindowResponse::Create { window },- Err(error) => {- eprintln!("[Pake] Failed to open requested window: {error}");- NewWindowResponse::Deny- }- },- );- }+ let app_handle = app.clone();+ let popup_config = config.clone();+ let popup_tauri_config = tauri_config.clone();+ window_builder = window_builder.on_new_window(move |target_url, features| {+ match open_requested_window(+ &app_handle,+ &popup_config,+ &popup_tauri_config,+ target_url,+ features,+ ) {+ Ok(window) => NewWindowResponse::Create { window },+ Err(error) => {+ eprintln!("[Pake] Failed to open requested window: {error}");+ NewWindowResponse::Deny+ }+ }+ });}- // Add initialization scripts+ // Add initialization scripts. Order matters: pakeConfig must land before+ // any script that reads it (e.g. fullscreen polyfill checks for an opt-out+ // flag), and toast must register `window.pakeToast` before Rust code+ // calls show_toast().window_builder = window_builder.initialization_script(&config_script)- .initialization_script(include_str!("../inject/component.js"))+ .initialization_script(include_str!("../inject/toast.js"))+ .initialization_script(include_str!("../inject/fullscreen.js")).initialization_script(include_str!("../inject/event.js")).initialization_script(include_str!("../inject/style.js")).initialization_script(include_str!("../inject/theme_refresh.js"))@@ -402,7 +403,9 @@ fn build_window(}if let Some(features) = new_window_features {- // macOS popup webviews must reuse the opener webview configuration.+ // Reuse only opener-provided position/size on macOS; sharing the opener+ // WKWebViewConfiguration triggers duplicate WKScriptMessageHandler+ // registrations on macOS 26+ and crashes the app (issue #1194).#[cfg(target_os = "macos")]{if let Some(position) = features.position() {@@ -413,9 +416,7 @@ fn build_window(window_builder = window_builder.inner_size(size.width, size.height);}- window_builder = window_builder- .with_webview_configuration(features.opener().target_configuration.clone())- .focused(true);+ window_builder = window_builder.focused(true);}#[cfg(not(target_os = "macos"))]@@ -428,3 +429,37 @@ fn build_window(window_builder.build()}++#[cfg(all(test, target_os = "windows"))]+mod proxy_arg_tests {+ use super::*;++ fn parse(url: &str) -> Url {+ Url::from_str(url).unwrap()+ }++ #[test]+ fn http_url_with_explicit_port() {+ let arg = build_proxy_browser_arg(&parse("http://127.0.0.1:7890")).unwrap();+ assert_eq!(arg, "--proxy-server=http://127.0.0.1:7890");+ }++ #[test]+ fn http_url_uses_default_port_when_missing() {+ let arg = build_proxy_browser_arg(&parse("http://proxy.local")).unwrap();+ assert_eq!(arg, "--proxy-server=http://proxy.local:80");+ }++ #[test]+ fn socks5_url_uses_default_port_when_missing() {+ let arg = build_proxy_browser_arg(&parse("socks5://proxy.local")).unwrap();+ assert_eq!(arg, "--proxy-server=socks5://proxy.local:1080");+ }++ #[test]+ fn https_scheme_is_not_supported_yet() {+ // https proxies fall back to platform proxy_url; we only emit a CLI arg+ // for http/socks5 today.+ assert!(build_proxy_browser_arg(&parse("https://proxy.local:8443")).is_none());+ }+}diff --git a/src-tauri/src/inject/component.js b/src-tauri/src/inject/fullscreen.jssimilarity index 83%rename from src-tauri/src/inject/component.jsrename to src-tauri/src/inject/fullscreen.jsindex 8a068fcd..c9f2485a 100644--- a/src-tauri/src/inject/component.js+++ b/src-tauri/src/inject/fullscreen.js@@ -1,28 +1,10 @@-document.addEventListener("DOMContentLoaded", () => {- // Toast- function pakeToast(msg) {- const m = document.createElement("div");- m.innerHTML = msg;- m.style.cssText =- "max-width:60%;min-width: 80px;padding:0 12px;height: 32px;color: rgb(255, 255, 255);line-height: 32px;text-align: center;border-radius: 8px;position: fixed; bottom:24px;right: 28px;z-index: 999999;background: rgba(0, 0, 0,.8);font-size: 13px;";- document.body.appendChild(m);- setTimeout(function () {- const d = 0.5;- m.style.transition =- "transform " + d + "s ease-in, opacity " + d + "s ease-in";- m.style.opacity = "0";- setTimeout(function () {- document.body.removeChild(m);- }, d * 1000);- }, 3000);- }-- window.pakeToast = pakeToast;-});--// Polyfill for HTML5 Fullscreen API in Tauri webview-// This bridges the HTML5 Fullscreen API to Tauri's native window fullscreen-// Works for all video sites (YouTube, Vimeo, Bilibili, etc.)+// Polyfill for HTML5 Fullscreen API in Tauri webview.+// Bridges the standard requestFullscreen / exitFullscreen DOM API to Tauri's+// native window fullscreen so video sites (YouTube, Vimeo, Bilibili, etc.) can+// go true fullscreen on their player buttons.+//+// Split out from component.js so a future CLI flag (or custom.js override)+// can short-circuit the polyfill for apps that don't need video fullscreen.(function () {if (window.__PAKE_FULLSCREEN_POLYFILL__) return;window.__PAKE_FULLSCREEN_POLYFILL__ = true;@@ -42,7 +24,6 @@ document.addEventListener("DOMContentLoaded", () => {let wasInBody = false;let monitorId = null;- // Inject fullscreen stylesif (!document.getElementById("pake-fullscreen-style")) {const styleEl = document.createElement("style");styleEl.id = "pake-fullscreen-style";@@ -93,7 +74,6 @@ document.addEventListener("DOMContentLoaded", () => {monitorId = null;}- // Find the actual video elementfunction findMediaElement() {const videos = document.querySelectorAll("video");if (videos.length > 0) {@@ -112,11 +92,9 @@ document.addEventListener("DOMContentLoaded", () => {return null;}- // Enter fullscreenfunction enterFullscreen(element) {fullscreenElement = element;- // If html/body element, find the video insteadlet targetElement = element;if (element === document.documentElement || element === document.body) {const mediaElement = findMediaElement();@@ -130,7 +108,6 @@ document.addEventListener("DOMContentLoaded", () => {actualFullscreenElement = element;}- // Save original stateoriginalStyles = {position: targetElement.style.position,top: targetElement.style.top,@@ -152,7 +129,6 @@ document.addEventListener("DOMContentLoaded", () => {originalNextSibling = targetElement.nextSibling;}- // Apply fullscreentargetElement.classList.add("pake-fullscreen-element");document.body.classList.add("pake-fullscreen-active");@@ -160,7 +136,6 @@ document.addEventListener("DOMContentLoaded", () => {document.body.appendChild(targetElement);}- // Fullscreen windowappWindow.setFullscreen(true).then(() => {startFullscreenMonitor();const event = new Event("fullscreenchange", { bubbles: true });@@ -177,7 +152,6 @@ document.addEventListener("DOMContentLoaded", () => {return Promise.resolve();}- // Exit fullscreenfunction exitFullscreen() {if (!fullscreenElement) {return Promise.resolve();@@ -188,7 +162,6 @@ document.addEventListener("DOMContentLoaded", () => {const exitingElement = fullscreenElement;const targetElement = actualFullscreenElement;- // Restore styles and positiontargetElement.classList.remove("pake-fullscreen-element");document.body.classList.remove("pake-fullscreen-active");@@ -209,7 +182,6 @@ document.addEventListener("DOMContentLoaded", () => {}}- // Reset statefullscreenElement = null;actualFullscreenElement = null;originalStyles = null;@@ -217,7 +189,6 @@ document.addEventListener("DOMContentLoaded", () => {originalNextSibling = null;wasInBody = false;- // Exit window fullscreenreturn appWindow.setFullscreen(false).then(() => {const event = new Event("fullscreenchange", { bubbles: true });document.dispatchEvent(event);@@ -231,7 +202,6 @@ document.addEventListener("DOMContentLoaded", () => {});}- // Override fullscreenEnabledObject.defineProperty(document, "fullscreenEnabled", {get: () => true,configurable: true,@@ -241,7 +211,6 @@ document.addEventListener("DOMContentLoaded", () => {configurable: true,});- // Override fullscreenElementObject.defineProperty(document, "fullscreenElement", {get: () => fullscreenElement,configurable: true,@@ -255,7 +224,6 @@ document.addEventListener("DOMContentLoaded", () => {configurable: true,});- // Override requestFullscreenElement.prototype.requestFullscreen = function () {return enterFullscreen(this);};@@ -266,12 +234,10 @@ document.addEventListener("DOMContentLoaded", () => {return enterFullscreen(this);};- // Override exitFullscreendocument.exitFullscreen = exitFullscreen;document.webkitExitFullscreen = exitFullscreen;document.webkitCancelFullScreen = exitFullscreen;- // Handle Escape keydocument.addEventListener("keydown",(e) => {diff --git a/src-tauri/src/inject/toast.js b/src-tauri/src/inject/toast.jsnew file mode 100644index 00000000..b0758e44--- /dev/null+++ b/src-tauri/src/inject/toast.js@@ -0,0 +1,22 @@+// Lightweight in-page toast used by Rust `show_toast` (download status, etc).+// Kept tiny and always loaded so the Rust side can rely on `window.pakeToast`.+document.addEventListener("DOMContentLoaded", () => {+ function pakeToast(msg) {+ const m = document.createElement("div");+ m.innerHTML = msg;+ m.style.cssText =+ "max-width:60%;min-width: 80px;padding:0 12px;height: 32px;color: rgb(255, 255, 255);line-height: 32px;text-align: center;border-radius: 8px;position: fixed; bottom:24px;right: 28px;z-index: 999999;background: rgba(0, 0, 0,.8);font-size: 13px;";+ document.body.appendChild(m);+ setTimeout(function () {+ const d = 0.5;+ m.style.transition =+ "transform " + d + "s ease-in, opacity " + d + "s ease-in";+ m.style.opacity = "0";+ setTimeout(function () {+ document.body.removeChild(m);+ }, d * 1000);+ }, 3000);+ }++ window.pakeToast = pakeToast;+});diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 1fc4cf75..d4272cb3 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -103,7 +103,7 @@ pub fn run_app() {}// --- Menu Construction End ---- let window = set_window(app.app_handle(), &pake_config, &tauri_config);+ let window = set_window(app.app_handle(), &pake_config, &tauri_config)?;set_system_tray(app.app_handle(),show_system_tray,@@ -174,7 +174,10 @@ pub fn run_app() {}}).build(tauri::generate_context!())- .expect("error while building tauri application")+ .unwrap_or_else(|error| {+ eprintln!("[Pake] Fatal error while building Tauri application: {error}");+ std::process::exit(1);+ }).run(|_app, _event| {// Handle macOS dock icon click to reopen hidden window#[cfg(target_os = "macos")]diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rsindex 22b48d23..3e178572 100644--- a/src-tauri/src/util.rs+++ b/src-tauri/src/util.rs@@ -23,25 +23,35 @@ pub fn get_pake_config() -> (PakeConfig, Config) {(pake_config, tauri_config)}-pub fn get_data_dir(app: &AppHandle, package_name: String) -> PathBuf {- {- let data_dir = app- .path()- .config_dir()- .expect("Failed to get data dirname")- .join(package_name);-- if !data_dir.exists() {- std::fs::create_dir(&data_dir)- .unwrap_or_else(|_| panic!("Can't create dir {}", data_dir.display()));- }- data_dir+pub fn get_data_dir(app: &AppHandle, package_name: String) -> std::io::Result<PathBuf> {+ let data_dir = app+ .path()+ .config_dir()+ .map_err(|err| {+ std::io::Error::new(+ std::io::ErrorKind::NotFound,+ format!("Failed to resolve config dir: {err}"),+ )+ })?+ .join(package_name);++ if !data_dir.exists() {+ std::fs::create_dir_all(&data_dir).map_err(|err| {+ std::io::Error::new(+ err.kind(),+ format!("Can't create dir {}: {err}", data_dir.display()),+ )+ })?;}++ Ok(data_dir)}pub fn show_toast(window: &WebviewWindow, message: &str) {let script = format!(r#"pakeToast("{message}");"#);- window.eval(&script).unwrap();+ if let Err(error) = window.eval(&script) {+ eprintln!("[Pake] Failed to show toast: {error}");+ }}pub enum MessageType {@@ -101,10 +111,16 @@ pub fn get_download_message_with_lang(.to_string()}-// Check if the file exists, if it exists, add a number to file name+/// Check if the file exists. If it does, append `-N` to the stem until a free+/// path is found.+///+/// Robustness notes:+/// - Files without an extension are handled (we keep them extensionless).+/// - If the numeric suffix would overflow `u32::MAX` we fall back to the+/// original file_path so the caller never enters an infinite loop on+/// pathologically large filenames (regression guard for #1183).pub fn check_file_or_append(file_path: &str) -> String {let mut new_path = PathBuf::from(file_path);- let mut counter = 0;while new_path.exists() {let file_stem = new_path@@ -116,16 +132,24 @@ pub fn check_file_or_append(file_path: &str) -> String {.map(|e| e.to_string_lossy().to_string());let parent_dir = new_path.parent().unwrap_or(Path::new(""));- let new_file_stem = match file_stem.rfind('-') {- Some(index) if file_stem[index + 1..].parse::<u32>().is_ok() => {+ let parsed_suffix = file_stem.rfind('-').and_then(|index| {+ file_stem[index + 1..]+ .parse::<u32>()+ .ok()+ .map(|n| (index, n))+ });++ let new_file_stem = match parsed_suffix {+ Some((index, current)) => {+ let Some(next) = current.checked_add(1) else {+ // u32::MAX collisions are a sign of something pathological;+ // bail with the original path instead of looping forever.+ return file_path.to_string();+ };let base_name = &file_stem[..index];- counter = file_stem[index + 1..].parse::<u32>().unwrap() + 1;- format!("{base_name}-{counter}")- }- _ => {- counter += 1;- format!("{file_stem}-{counter}")+ format!("{base_name}-{next}")}+ None => format!("{file_stem}-1"),};new_path = match &extension {@@ -136,3 +160,86 @@ pub fn check_file_or_append(file_path: &str) -> String {new_path.to_string_lossy().into_owned()}++#[cfg(test)]+mod tests {+ use super::*;+ use std::env;+ use std::fs;+ use std::path::PathBuf;++ fn temp_path(name: &str) -> PathBuf {+ let mut dir = env::temp_dir();+ dir.push(format!(+ "pake-util-test-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ fs::create_dir_all(&dir).unwrap();+ dir.push(name);+ dir+ }++ #[test]+ fn check_file_or_append_returns_input_when_missing() {+ let path = temp_path("ghost.txt");+ let resolved = check_file_or_append(path.to_str().unwrap());+ assert_eq!(resolved, path.to_string_lossy());+ let _ = fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn check_file_or_append_increments_suffix() {+ let path = temp_path("dup.txt");+ fs::write(&path, b"existing").unwrap();+ let resolved = check_file_or_append(path.to_str().unwrap());+ assert!(resolved.ends_with("dup-1.txt"), "got {resolved}");+ let _ = fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn check_file_or_append_handles_files_without_extension() {+ let path = temp_path("README");+ fs::write(&path, b"existing").unwrap();+ let resolved = check_file_or_append(path.to_str().unwrap());+ assert!(resolved.ends_with("README-1"), "got {resolved}");+ let _ = fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn check_file_or_append_does_not_panic_on_huge_suffix() {+ let path = temp_path(&format!("huge-{}.txt", u32::MAX));+ fs::write(&path, b"existing").unwrap();+ let resolved = check_file_or_append(path.to_str().unwrap());+ assert!(resolved.contains("huge-"));+ let _ = fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn download_message_falls_back_to_english_for_unknown_locale() {+ let msg = get_download_message_with_lang(MessageType::Start, Some("fr-FR".to_string()));+ assert_eq!(msg, "Start downloading~");+ }++ #[test]+ fn download_message_picks_chinese_for_zh_locales() {+ for tag in ["zh", "zh-CN", "zh-TW", "en-CN", "en-HK"] {+ let msg = get_download_message_with_lang(MessageType::Success, Some(tag.to_string()));+ assert_eq!(+ msg, "下载成功,已保存到下载目录~",+ "expected Chinese for {tag}"+ );+ }+ }++ #[test]+ fn download_message_failure_localized() {+ let en = get_download_message_with_lang(MessageType::Failure, Some("en".into()));+ let zh = get_download_message_with_lang(MessageType::Failure, Some("zh".into()));+ assert!(en.contains("Download failed"));+ assert!(zh.contains("下载失败"));+ }+}diff --git a/tests/unit/new-window-macos.test.js b/tests/unit/new-window-macos.test.jsindex 4016953e..eefc6e74 100644--- a/tests/unit/new-window-macos.test.js+++ b/tests/unit/new-window-macos.test.js@@ -2,30 +2,40 @@ import fs from "fs";import path from "path";import { describe, expect, it } from "vitest";-describe("macOS new-window handling", () => {- it("uses the default WebKit popup path instead of manually creating a Tauri window", () => {- const source = fs.readFileSync(- path.join(process.cwd(), "src-tauri/src/app/window.rs"),- "utf-8",- );+const sourcePath = path.join(process.cwd(), "src-tauri/src/app/window.rs");++describe("macOS new-window handling (regression: #1194)", () => {+ it("creates popups via open_requested_window on every platform", () => {+ const source = fs.readFileSync(sourcePath, "utf-8");const blockStart = source.indexOf("if window_config.new_window");const blockEnd = source.indexOf("// Add initialization scripts",blockStart,);- const newWindowBlock = source.slice(blockStart, blockEnd);+ expect(blockStart).toBeGreaterThan(-1);+ expect(blockEnd).toBeGreaterThan(blockStart);- expect(newWindowBlock).toMatch(- /#\[cfg\(target_os = "macos"\)\]\s*\{\s*window_builder\s*=\s*window_builder\.on_new_window\(\|_target_url, _features\| NewWindowResponse::Allow\);\s*\}/s,- );+ const newWindowBlock = source.slice(blockStart, blockEnd);- const macosBranch = newWindowBlock.slice(- newWindowBlock.indexOf('#[cfg(target_os = "macos")]'),- newWindowBlock.indexOf('#[cfg(not(target_os = "macos"))]'),- );+ // The fix for #1194 unifies all platforms behind open_requested_window so+ // popups never reuse the opener WKWebViewConfiguration. Guard against+ // accidental reintroduction of NewWindowResponse::Allow which crashes+ // macOS 26 with WKUserContentController duplicate handler errors.+ expect(newWindowBlock).toContain("open_requested_window");+ expect(newWindowBlock).toContain("NewWindowResponse::Create");+ expect(newWindowBlock).not.toMatch(/NewWindowResponse::Allow\b/);+ expect(newWindowBlock).not.toMatch(/#\[cfg\(target_os = "macos"\)\]/);+ });- expect(macosBranch).not.toContain("open_requested_window");- expect(macosBranch).not.toContain("with_webview_configuration");+ it("does not clone the opener WKWebViewConfiguration on macOS popup features", () => {+ // The popup-features handler in build_window must never call+ // .with_webview_configuration(features.opener().target_configuration)+ // because the cloned configuration carries the parent's+ // WKScriptMessageHandler set, which WebKit refuses to register twice and+ // aborts the process on macOS 26.+ const source = fs.readFileSync(sourcePath, "utf-8");+ expect(source).not.toContain("with_webview_configuration");+ expect(source).not.toContain("target_configuration.clone()");});});