Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(tray): stop menu-bar menu flashing open-then-closed on first click (macOS) (#4618)

Ezra Ellette6b9662350c51
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 4a4798478..57756b108 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -10944,6 +10944,7 @@ dependencies = [
"chrono",
"cocoa 0.26.1",
"core-foundation 0.10.1",
+ "core-foundation-sys 0.8.7",
"core-graphics-helmer-fork",
"dark-light",
"dirs 5.0.1",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index ced567f20..5976c9a32 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -178,6 +178,7 @@ tauri-plugin-updater = "2.10.0"
[target.'cfg(target_os = "macos")'.dependencies]
tracing-oslog = "0.3.0"
core-foundation = "0.10"
+core-foundation-sys = "0.8"
cocoa = "0.26.0"
objc = "0.2.7"
block = "0.1"
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
index f14aabb8e..b522ef022 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
@@ -340,24 +340,43 @@ fn get_effective_recording_status() -> RecordingStatus {
real
}
-/// Keep the active tray menu alive and defer macOS menu replacement safely.
+/// Keep the active tray menu alive and replace the macOS menu only while it is
+/// CLOSED.
///
-/// muda's macOS backend stores raw `*const MenuChild` pointers as NSMenuItem
-/// instance variables. When `tray.set_menu(new_menu)` is called while the old
-/// menu is still displayed, the old `MenuChild` items can be freed while their
-/// NSMenuItems survive. Clicking an item in that stale menu makes
-/// `fire_menu_item_click` dereference freed memory inside an `extern "C"`
-/// callback, so catch_unwind cannot keep the process alive.
+/// Two hazards govern when `tray.set_menu(new_menu)` is safe on macOS:
///
-/// We avoid background `set_menu` on macOS. The poller caches the latest menu
-/// inputs, then the tray mouse-down handler installs that menu before AppKit
-/// opens the native menu.
+/// 1. Use-after-free (#3813): muda's macOS backend ties each NSMenuItem to a
+/// Rust `MenuChild`. Replacing the menu while it is *displayed* frees the old
+/// items while AppKit still references them — a click then dereferences freed
+/// memory in `fire_menu_item_click` (an `extern "C"` callback). The muda fork
+/// now keeps `MenuChild` alive via an `Rc`, but we still never want to swap a
+/// presented menu.
+/// 2. Flash: a status-item menu opens on mouse-DOWN via `performClick`, which
+/// enters AppKit's modal menu tracking synchronously. tao drains its event
+/// queue in `kCFRunLoopCommonModes` — which *includes* the menu's
+/// `NSEventTrackingRunLoopMode` — so a `set_menu` triggered from the
+/// mouse-down handler lands WHILE the menu is presenting and AppKit dismisses
+/// it. That was the "first click flashes then closes, second click opens" bug.
+///
+/// So the poller never calls `set_menu` directly; it caches the latest menu
+/// inputs in `PENDING_TRAY_MENU` and marks `TRAY_MENU_DIRTY`. A `CFRunLoopObserver`
+/// registered for `kCFRunLoopDefaultMode` ONLY (see `menu_refresh_observer`)
+/// installs the queued menu when the run loop is idle — i.e. when no menu is
+/// open. Default-mode observers never fire during menu tracking, so the swap can
+/// never overlap a presented menu: no flash, no UAF. Each open shows an
+/// up-to-date menu built from freshly-prefetched data.
static ACTIVE_TRAY_MENU: Lazy<Mutex<Option<tauri::menu::Menu<Wry>>>> =
Lazy::new(|| Mutex::new(None));
static PENDING_TRAY_MENU: Lazy<Mutex<Option<(MenuState, TrayMenuData)>>> =
Lazy::new(|| Mutex::new(None));
+/// Set when a fresh tray menu has been queued into `PENDING_TRAY_MENU` and not
+/// yet installed. Read by the main-run-loop observer so it rebuilds the menu
+/// only when something actually changed (the observer fires on every idle).
+#[cfg(target_os = "macos")]
+static TRAY_MENU_DIRTY: AtomicBool = AtomicBool::new(false);
+
fn install_tray_menu(tray: &TrayIcon, menu: tauri::menu::Menu<Wry>) -> Result<()> {
{
let mut active = ACTIVE_TRAY_MENU.lock().unwrap_or_else(|e| e.into_inner());
@@ -374,8 +393,21 @@ fn clear_pending_tray_menu() {
#[cfg(target_os = "macos")]
fn queue_pending_tray_menu(state: MenuState, data: TrayMenuData) {
- let mut pending = PENDING_TRAY_MENU.lock().unwrap_or_else(|e| e.into_inner());
- *pending = Some((state, data));
+ {
+ let mut pending = PENDING_TRAY_MENU.lock().unwrap_or_else(|e| e.into_inner());
+ *pending = Some((state, data));
+ }
+ TRAY_MENU_DIRTY.store(true, Ordering::Release);
+ // Wake the main run loop so the default-mode observer fires promptly (and
+ // installs the menu while it's closed) instead of waiting for the next
+ // unrelated event. CFRunLoop* are safe to call from this tokio thread.
+ unsafe {
+ use core_foundation_sys::runloop::{CFRunLoopGetMain, CFRunLoopWakeUp};
+ let main = CFRunLoopGetMain();
+ if !main.is_null() {
+ CFRunLoopWakeUp(main);
+ }
+ }
}
#[cfg(target_os = "macos")]
@@ -400,6 +432,83 @@ fn apply_pending_tray_menu(app: &AppHandle) -> Result<()> {
Ok(())
}
+/// Installs the queued tray menu while no menu is open — the only flash-free,
+/// crash-free moment to call `set_menu` on macOS (see the `ACTIVE_TRAY_MENU`
+/// doc above for the two hazards).
+///
+/// A `CFRunLoopObserver` registered for `kCFRunLoopDefaultMode` only fires when
+/// the main run loop is idle; it is skipped entirely while a status-item menu is
+/// in its `NSEventTrackingRunLoopMode` modal loop. So whenever the poller queues
+/// a fresh menu (and wakes the loop), this installs it moments later while the
+/// menu is closed — never overlapping a presented menu.
+#[cfg(target_os = "macos")]
+mod menu_refresh_observer {
+ use super::{apply_pending_tray_menu, TRAY_MENU_DIRTY};
+ use core_foundation_sys::runloop::{
+ kCFRunLoopBeforeWaiting, kCFRunLoopDefaultMode, CFRunLoopActivity, CFRunLoopAddObserver,
+ CFRunLoopGetMain, CFRunLoopObserverContext, CFRunLoopObserverCreate, CFRunLoopObserverRef,
+ };
+ use std::os::raw::c_void;
+ use std::sync::atomic::Ordering;
+ use std::sync::Once;
+ use tauri::AppHandle;
+ use tracing::error;
+
+ /// Fires on every main-loop idle (default mode only). Cheap no-op unless a
+ /// menu refresh was queued. Runs on the main thread, so the AppKit work in
+ /// `apply_pending_tray_menu` is safe here.
+ extern "C" fn on_idle(_observer: CFRunLoopObserverRef, _activity: CFRunLoopActivity, info: *mut c_void) {
+ if !TRAY_MENU_DIRTY.swap(false, Ordering::AcqRel) {
+ return;
+ }
+ if info.is_null() {
+ return;
+ }
+ // SAFETY: `info` is the leaked AppHandle from `install`, valid for the
+ // whole process lifetime.
+ let app = unsafe { &*(info as *const AppHandle) };
+ let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ if let Err(e) = apply_pending_tray_menu(app) {
+ error!("failed to install queued tray menu on idle: {}", e);
+ }
+ }));
+ }
+
+ /// Register the observer once on the main run loop.
+ pub fn install(app: &AppHandle) {
+ static INSTALLED: Once = Once::new();
+ INSTALLED.call_once(|| {
+ // Leak one AppHandle for the observer's (app-lifetime) callback.
+ let info = Box::into_raw(Box::new(app.clone())) as *mut c_void;
+ let mut context = CFRunLoopObserverContext {
+ version: 0,
+ info,
+ retain: None,
+ release: None,
+ copyDescription: None,
+ };
+ unsafe {
+ let observer = CFRunLoopObserverCreate(
+ std::ptr::null(), // default allocator
+ kCFRunLoopBeforeWaiting,
+ 1, // repeats
+ 0, // order
+ on_idle,
+ &mut context,
+ );
+ if observer.is_null() {
+ error!("failed to create tray-menu run-loop observer");
+ // Reclaim the leaked AppHandle so we don't leak on failure.
+ drop(Box::from_raw(info as *mut AppHandle));
+ return;
+ }
+ CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopDefaultMode);
+ // `observer` is intentionally leaked: it lives for the app's lifetime.
+ }
+ });
+ }
+}
+
#[derive(Default, PartialEq, Clone)]
struct MenuState {
shortcuts: HashMap<String, String>,
@@ -438,6 +547,11 @@ pub fn setup_tray(app: &AppHandle, update_item: Option<&tauri::menu::MenuItem<Wr
install_tray_menu(&main_tray, menu)?;
clear_pending_tray_menu();
+ // Install the idle observer that swaps in queued menus while no menu is
+ // open (flash-free, crash-free). Once-guarded, so recreate_tray is fine.
+ #[cfg(target_os = "macos")]
+ menu_refresh_observer::install(app);
+
// Setup click handlers
setup_tray_click_handlers(&main_tray)?;
@@ -900,28 +1014,13 @@ fn setup_tray_click_handlers(main_tray: &TrayIcon) -> Result<()> {
}
});
- #[cfg(target_os = "macos")]
- {
- main_tray.on_tray_icon_event(|tray, event| {
- if let tauri::tray::TrayIconEvent::Click {
- button_state: tauri::tray::MouseButtonState::Down,
- ..
- } = event
- {
- if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- let app = tray.app_handle().clone();
- if let Err(e) = apply_pending_tray_menu(&app) {
- error!("failed to refresh tray menu before open: {}", e);
- }
- })) {
- error!(
- "panic caught while refreshing tray menu before open: {:?}",
- e
- );
- }
- }
- });
- }
+ // macOS note: we deliberately do NOT install the queued menu from an
+ // on_tray_icon_event(Down) handler. That runs while AppKit is opening the
+ // menu (tao drains its event queue in kCFRunLoopCommonModes, which includes
+ // the menu's NSEventTrackingRunLoopMode), so set_menu would land mid-present
+ // and AppKit would dismiss the just-opened menu — the "first click flashes
+ // then closes" bug. The default-mode CFRunLoopObserver installed in
+ // setup_tray (menu_refresh_observer) does the swap while the menu is closed.
// Windows: left-click opens the app (like macOS dock click), right-click shows menu
#[cfg(target_os = "windows")]