From 6ea7f544b27c02905e8d078ae6b29086772c934b Mon Sep 17 00:00:00 2001 From: wonfen Date: Thu, 16 Jul 2026 04:27:47 +0800 Subject: [PATCH] fix: dispatch frontend events on main thread --- src-tauri/src/core/handle.rs | 2 +- src-tauri/src/core/notification.rs | 25 +++++++++++++++---------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src-tauri/src/core/handle.rs b/src-tauri/src/core/handle.rs index bb6d7d80c..f8a32ebef 100644 --- a/src-tauri/src/core/handle.rs +++ b/src-tauri/src/core/handle.rs @@ -90,7 +90,7 @@ impl Handle { return; } - NotificationSystem::send_event(event); + NotificationSystem::send_event(Self::app_handle().clone(), event); } } diff --git a/src-tauri/src/core/notification.rs b/src-tauri/src/core/notification.rs index a3d2edcbf..0c6263039 100644 --- a/src-tauri/src/core/notification.rs +++ b/src-tauri/src/core/notification.rs @@ -1,9 +1,8 @@ -use crate::utils::window_manager::WindowManager; use clash_verge_logging::{Type, logging}; use serde_json::json; use smartstring::alias::String; -use tauri::{Emitter as _, WebviewWindow}; +use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow}; #[derive(Debug)] pub enum FrontendEvent<'a> { @@ -21,11 +20,7 @@ pub enum FrontendEvent<'a> { pub struct NotificationSystem {} impl NotificationSystem { - fn emit_to_window(window: &WebviewWindow, event: FrontendEvent) { - let (event_name, Ok(payload)) = Self::serialize_event(event) else { - return; - }; - + fn emit_to_window(window: &WebviewWindow, event_name: &'static str, payload: serde_json::Value) { if let Err(e) = window.emit(event_name, payload) { logging!(warn, Type::Frontend, "Event emit failed: {}", e); } @@ -46,9 +41,19 @@ impl NotificationSystem { } } - pub(crate) fn send_event(event: FrontendEvent) { - if let Some(window) = WindowManager::get_main_window() { - Self::emit_to_window(&window, event); + pub(crate) fn send_event(app_handle: AppHandle, event: FrontendEvent) { + let (event_name, Ok(payload)) = Self::serialize_event(event) else { + return; + }; + let dispatch_handle = app_handle.clone(); + // Emitting from a runtime worker can deadlock on macOS when WebKit's protocol handler + // waits for Tauri's webview lock while emit waits synchronously for the main thread. + if let Err(err) = app_handle.run_on_main_thread(move || { + if let Some(window) = dispatch_handle.get_webview_window("main") { + Self::emit_to_window(&window, event_name, payload); + } + }) { + logging!(warn, Type::Frontend, "Failed to dispatch event on main thread: {err}"); } } }