From 2c6405a2de6c32c45028fa0a4bcdb69c759fbc8e Mon Sep 17 00:00:00 2001 From: Osei Fortune Date: Sat, 21 Nov 2026 14:35:14 -0400 Subject: [PATCH] fix(runtime): don't pump messages inside XAML's dispatcher; keep Application.Current an Application WinUI 3 apps froze a few seconds after they started rendering every frame: timers, requestAnimationFrame and native callbacks all stopped while the UI thread sat idle in GetMessage. WinUI's dispatcher is a Microsoft.UI.Dispatching.DispatcherQueue, so init_ui_dispatcher finds no Windows.System.DispatcherQueue and makes its own controller. needs_win32_pump() was then true under XAML too, and runtime_pump_timers (and the napi engines' host pump) drained the thread's messages with PeekMessage/DispatchMessage from inside the host's DispatcherQueue work item. Dispatching the queues' wake messages re-entrantly can lose a wake, after which XAML's queue, its timers and the runtime's own queue never run again. A frame loop makes it happen within seconds. host_pumps_messages() now detects a XAML host (Microsoft.UI.Xaml.dll loaded), and the host pumps leave messages to XAML's loop there. Console executables and workers keep pumping. Also: Application.Current came back as Microsoft.UI.Xaml. IApplicationOverrides, with no Exit, so core could never end the app when its last window closed. The template's C# App has no WinMD, so CsWinRT reports one of its interfaces as the runtime class name. resolve_runtime_class no longer swaps a declared class for an interface name. --- nativescript/src/lib.rs | 3 ++- runtime/src/napi_engine/event_loop.rs | 14 +++++++++++- runtime/src/napi_engine/host_abi.rs | 2 +- runtime/src/ns_proxy.rs | 19 ++++++++++++++- runtime/src/ui_dispatcher.rs | 33 +++++++++++++++++++++++++++ 5 files changed, 67 insertions(+), 4 deletions(-) diff --git a/nativescript/src/lib.rs b/nativescript/src/lib.rs index 3969bdb..fd6cc07 100644 --- a/nativescript/src/lib.rs +++ b/nativescript/src/lib.rs @@ -443,7 +443,8 @@ pub extern "C" fn runtime_pump_timers() { runtime::node_api::drain(); // This frame's requestAnimationFrame callbacks, then their microtasks. runtime::animation_frames::pump(); - if runtime::ui_dispatcher::needs_win32_pump() { + // (a WinUI host has a runtime-made dispatcher too: see `host_pumps_messages`) + if runtime::ui_dispatcher::needs_win32_pump() && !runtime::ui_dispatcher::host_pumps_messages() { runtime::pump_messages(); } else { runtime::pump_dispatcher(); diff --git a/runtime/src/napi_engine/event_loop.rs b/runtime/src/napi_engine/event_loop.rs index 5940512..adaa5ba 100644 --- a/runtime/src/napi_engine/event_loop.rs +++ b/runtime/src/napi_engine/event_loop.rs @@ -66,8 +66,20 @@ pub fn install_loop_natives(env: &Env) -> napi::Result<()> { /// `run_event_loop` repeats; hosts that own their own frame loop (e.g. the WinUI 3 DLL, driven /// from `CompositionTarget.Rendering`) call it directly once per frame instead. pub fn pump_once(env: &Env, drain_microtasks: &mut F) { + pump_iteration(env, drain_microtasks, true); +} + +/// `pump_once` for a host that calls it from its own message loop: Win32 messages are left to that +/// loop when it is XAML's (see `ui_dispatcher::host_pumps_messages`). +pub fn pump_once_from_host(env: &Env, drain_microtasks: &mut F) { + pump_iteration(env, drain_microtasks, !crate::ui_dispatcher::host_pumps_messages()); +} + +fn pump_iteration(env: &Env, drain_microtasks: &mut F, pump_messages: bool) { drain_microtasks(); - crate::pump_messages(); + if pump_messages { + crate::pump_messages(); + } drain_microtasks(); crate::napi_engine::websocket::pump(env); drain_microtasks(); diff --git a/runtime/src/napi_engine/host_abi.rs b/runtime/src/napi_engine/host_abi.rs index db8475c..8feeecc 100644 --- a/runtime/src/napi_engine/host_abi.rs +++ b/runtime/src/napi_engine/host_abi.rs @@ -59,7 +59,7 @@ pub fn initialize_runtime(env: &Env, app_root: &str) -> napi::Result<()> { /// call this once per frame from `CompositionTarget.Rendering`; it never blocks. `drain_microtasks` /// is the engine's microtask pump (e.g. `js_execute_pending_jobs` / `jsr_drain_microtasks`). pub fn pump_once(env: &Env, drain_microtasks: &mut F) { - event_loop::pump_once(env, drain_microtasks); + event_loop::pump_once_from_host(env, drain_microtasks); } /// True when the loop has no outstanding work (no timers, zero keep-alive count) — a self-hosted diff --git a/runtime/src/ns_proxy.rs b/runtime/src/ns_proxy.rs index 7e5a214..1c76396 100644 --- a/runtime/src/ns_proxy.rs +++ b/runtime/src/ns_proxy.rs @@ -2039,6 +2039,12 @@ pub(crate) fn create_ns_object<'a>( /// The metadata class named by `instance`'s GetRuntimeClassName, when it differs from /// `declared` and neither name is a generic instance. +/// +/// An interface name only replaces a declared interface (or an undeclared type), never a declared +/// class. A type authored outside WinMD, like the app template's C# `App : Application`, can't +/// name itself, so CsWinRT reports one of its interfaces, e.g. +/// `Microsoft.UI.Xaml.IApplicationOverrides`. Wrapping `Application.Current` as that interface +/// would drop every `Application` member, such as `Exit`, `Resources` and `RequestedTheme`. pub(crate) fn resolve_runtime_class( instance: &IUnknown, declared: &str, @@ -2053,7 +2059,18 @@ pub(crate) fn resolve_runtime_class( .map(|cn| cn.to_string_lossy()) .filter(|cn| !cn.is_empty() && cn != declared && !cn.contains('<')) .and_then(|cn| MetadataReader::find_by_name(&cn).map(|d| (cn, d))) - .filter(|(_, d)| !matches!(d.read().kind(), DeclarationKind::Struct)) + .filter(|(_, d)| match d.read().kind() { + DeclarationKind::Struct => false, + DeclarationKind::Interface | DeclarationKind::GenericInterfaceInstance => { + !declared_is_class(declared) + } + _ => true, + }) +} + +fn declared_is_class(declared: &str) -> bool { + MetadataReader::find_by_name(declared) + .is_some_and(|d| matches!(d.read().kind(), DeclarationKind::Class)) } pub(crate) fn create_ns_ctor_instance_object<'a>( diff --git a/runtime/src/ui_dispatcher.rs b/runtime/src/ui_dispatcher.rs index 7949dc2..56fafd2 100644 --- a/runtime/src/ui_dispatcher.rs +++ b/runtime/src/ui_dispatcher.rs @@ -217,6 +217,33 @@ pub fn needs_win32_pump() -> bool { UI_DQ_CONTROLLER.get().is_some() } +/// True when a XAML host runs the UI thread's message loop, so the runtime's pump must not drain +/// Win32 messages itself. +/// +/// WinUI 3's own dispatcher is a `Microsoft.UI.Dispatching.DispatcherQueue`, so +/// `init_ui_dispatcher` finds no `Windows.System.DispatcherQueue` there and makes its own +/// controller, which makes `needs_win32_pump` true even under XAML. XAML's loop dispatches that +/// controller's work as well. +/// +/// The host calls the pump from inside a `DispatcherQueue` work item. Pumping messages there +/// dispatches the queues' wake messages re-entrantly, and a wake can be lost: XAML's queue, its +/// timers and the runtime's own queue then never run again. Timers, frames and native callbacks +/// all stop while the UI thread sits idle in `GetMessage`. Console hosts have no such loop and +/// keep pumping. +/// +/// Settled on the first call. Every caller is a pump, and a WinUI host only starts pumping from +/// inside `Application.Start`, after XAML has loaded. +pub fn host_pumps_messages() -> bool { + static XAML_HOST: OnceLock = OnceLock::new(); + *XAML_HOST.get_or_init(xaml_loaded) +} + +fn xaml_loaded() -> bool { + use windows::core::w; + use windows::Win32::System::LibraryLoader::GetModuleHandleW; + unsafe { GetModuleHandleW(w!("Microsoft.UI.Xaml.dll")) }.is_ok() +} + #[cfg(test)] mod tests { use super::*; @@ -232,6 +259,12 @@ mod tests { assert!(UI_THREAD_ID.get().is_none()); } + #[test] + fn console_host_keeps_pumping_messages() { + // No XAML in a test process: the runtime's pump still drains Win32 messages. + assert!(!host_pumps_messages()); + } + #[test] fn post_fallback_runs_closure_inline() { let fired = Arc::new(AtomicBool::new(false));