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(macos): wrap all ObjC operations in scoped autorelease pools to prevent SIGSEGV crash

Louis Beaumont4cb9850f76fc
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 68e12ea12..c8dc4c9ea 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9173,7 +9173,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.2.105"
+version = "2.2.106"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 2d9349399..0aaafdb33 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.2.106"
+version = "2.2.107"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/health.rs b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
index 1de8fd858..edde13b3a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/health.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
@@ -322,13 +322,15 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
// (NSStatusBar operations crash if called from a tokio thread)
let app_clone = app.clone();
let _ = app.run_on_main_thread(move || {
- if let Some(main_tray) = app_clone.tray_by_id("screenpipe_main") {
- if let Err(e) =
- crate::safe_icon::safe_set_icon_as_template(&main_tray, image)
- {
- error!("failed to set tray icon: {}", e);
+ crate::window_api::with_autorelease_pool(|| {
+ if let Some(main_tray) = app_clone.tray_by_id("screenpipe_main") {
+ if let Err(e) =
+ crate::safe_icon::safe_set_icon_as_template(&main_tray, image)
+ {
+ error!("failed to set tray icon: {}", e);
+ }
}
- }
+ });
});
}
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs b/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs
index d671c5764..6ab8481c2 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs
@@ -40,7 +40,7 @@ static ANALYZE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::Ato
pub async fn livetext_is_available() -> Result<bool, String> {
#[cfg(target_os = "macos")]
{
- let result = unsafe { livetext_ffi::lt_is_available() };
+ let result = crate::window_api::with_autorelease_pool(|| unsafe { livetext_ffi::lt_is_available() });
info!(
"livetext_is_available: lt_is_available() returned {}",
result
@@ -119,7 +119,9 @@ pub async fn livetext_analyze(
// if called from a tokio worker thread)
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
- let result = (|| -> Result<String, String> {
+ // Wrap in autorelease pool — Swift FFI may create autoreleased
+ // ObjC objects internally, and this thread has no default pool.
+ let result = crate::window_api::with_autorelease_pool(|| -> Result<String, String> {
// Check if a newer request has already been issued
if ANALYZE_GENERATION.load(std::sync::atomic::Ordering::SeqCst) != gen {
return Err("skipped: newer analyze request pending".to_string());
@@ -154,7 +156,7 @@ pub async fn livetext_analyze(
extract_and_free(out_error);
Ok(text)
}
- })();
+ });
let _ = tx.send(result);
});
@@ -173,7 +175,9 @@ pub async fn livetext_analyze(
pub async fn livetext_update_position(x: f64, y: f64, w: f64, h: f64) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
- let status = unsafe { livetext_ffi::lt_update_position(x, y, w, h) };
+ let status = crate::window_api::with_autorelease_pool(|| unsafe {
+ livetext_ffi::lt_update_position(x, y, w, h)
+ });
if status != 0 {
return Err(format!("lt_update_position error: {}", status));
}
@@ -192,7 +196,9 @@ pub async fn livetext_highlight(terms: Vec<String>) -> Result<i32, String> {
{
let json = serde_json::to_string(&terms).map_err(|e| format!("json error: {}", e))?;
let json_c = CString::new(json).map_err(|e| format!("invalid json: {}", e))?;
- let count = unsafe { livetext_ffi::lt_highlight_ranges(json_c.as_ptr()) };
+ let count = crate::window_api::with_autorelease_pool(|| unsafe {
+ livetext_ffi::lt_highlight_ranges(json_c.as_ptr())
+ });
return Ok(count);
}
#[cfg(not(target_os = "macos"))]
@@ -206,7 +212,7 @@ pub async fn livetext_highlight(terms: Vec<String>) -> Result<i32, String> {
pub async fn livetext_clear_highlights() -> Result<(), String> {
#[cfg(target_os = "macos")]
{
- unsafe { livetext_ffi::lt_clear_highlights() };
+ crate::window_api::with_autorelease_pool(|| unsafe { livetext_ffi::lt_clear_highlights() });
return Ok(());
}
#[cfg(not(target_os = "macos"))]
@@ -217,7 +223,7 @@ pub async fn livetext_clear_highlights() -> Result<(), String> {
pub async fn livetext_hide() -> Result<(), String> {
#[cfg(target_os = "macos")]
{
- unsafe { livetext_ffi::lt_hide() };
+ crate::window_api::with_autorelease_pool(|| unsafe { livetext_ffi::lt_hide() });
return Ok(());
}
#[cfg(not(target_os = "macos"))]
@@ -239,7 +245,9 @@ pub async fn livetext_set_guard_rect(
#[cfg(target_os = "macos")]
{
let key_c = CString::new(key).map_err(|e| format!("invalid key: {}", e))?;
- let status = unsafe { livetext_ffi::lt_set_guard_rect(key_c.as_ptr(), x, y, w, h) };
+ let status = crate::window_api::with_autorelease_pool(|| unsafe {
+ livetext_ffi::lt_set_guard_rect(key_c.as_ptr(), x, y, w, h)
+ });
if status != 0 {
return Err(format!("lt_set_guard_rect error: {}", status));
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
index 9a86ed490..c0e943d3a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
@@ -105,16 +105,18 @@ pub async fn request_permission(permission: OSPermission) {
#[cfg(target_os = "macos")]
fn request_av_permission(media_type: nokhwa_bindings_macos::AVMediaType) {
- use objc::{runtime::*, *};
- use tauri_nspanel::block::ConcreteBlock;
-
- let callback = move |_: BOOL| {};
- let cls = class!(AVCaptureDevice);
- let objc_fn_block: ConcreteBlock<(BOOL,), (), _> = ConcreteBlock::new(callback);
- let objc_fn_pass = objc_fn_block.copy();
- unsafe {
- let _: () = msg_send![cls, requestAccessForMediaType:media_type.into_ns_str() completionHandler:objc_fn_pass];
- };
+ crate::window_api::with_autorelease_pool(|| {
+ use objc::{runtime::*, *};
+ use tauri_nspanel::block::ConcreteBlock;
+
+ let callback = move |_: BOOL| {};
+ let cls = class!(AVCaptureDevice);
+ let objc_fn_block: ConcreteBlock<(BOOL,), (), _> = ConcreteBlock::new(callback);
+ let objc_fn_pass = objc_fn_block.copy();
+ unsafe {
+ let _: () = msg_send![cls, requestAccessForMediaType:media_type.into_ns_str() completionHandler:objc_fn_pass];
+ };
+ });
}
// Accessibility permission APIs using ApplicationServices framework
@@ -206,15 +208,17 @@ pub fn check_microphone_permission() -> OSPermissionStatus {
use nokhwa_bindings_macos::AVMediaType;
use objc::*;
- let cls = objc::class!(AVCaptureDevice);
- let status: AVAuthorizationStatus = unsafe {
- msg_send![cls, authorizationStatusForMediaType:AVMediaType::Audio.into_ns_str()]
- };
- match status {
- AVAuthorizationStatus::NotDetermined => OSPermissionStatus::Empty,
- AVAuthorizationStatus::Authorized => OSPermissionStatus::Granted,
- _ => OSPermissionStatus::Denied,
- }
+ crate::window_api::with_autorelease_pool(|| {
+ let cls = objc::class!(AVCaptureDevice);
+ let status: AVAuthorizationStatus = unsafe {
+ msg_send![cls, authorizationStatusForMediaType:AVMediaType::Audio.into_ns_str()]
+ };
+ match status {
+ AVAuthorizationStatus::NotDetermined => OSPermissionStatus::Empty,
+ AVAuthorizationStatus::Authorized => OSPermissionStatus::Granted,
+ _ => OSPermissionStatus::Denied,
+ }
+ })
}
#[cfg(not(target_os = "macos"))]
@@ -352,17 +356,19 @@ pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {
use nokhwa_bindings_macos::AVMediaType;
fn check_av_permission(media_type: AVMediaType) -> OSPermissionStatus {
- use nokhwa_bindings_macos::AVAuthorizationStatus;
- use objc::*;
+ crate::window_api::with_autorelease_pool(|| {
+ use nokhwa_bindings_macos::AVAuthorizationStatus;
+ use objc::*;
- let cls = objc::class!(AVCaptureDevice);
- let status: AVAuthorizationStatus =
- unsafe { msg_send![cls, authorizationStatusForMediaType:media_type.into_ns_str()] };
- match status {
- AVAuthorizationStatus::NotDetermined => OSPermissionStatus::Empty,
- AVAuthorizationStatus::Authorized => OSPermissionStatus::Granted,
- _ => OSPermissionStatus::Denied,
- }
+ let cls = objc::class!(AVCaptureDevice);
+ let status: AVAuthorizationStatus =
+ unsafe { msg_send![cls, authorizationStatusForMediaType:media_type.into_ns_str()] };
+ match status {
+ AVAuthorizationStatus::NotDetermined => OSPermissionStatus::Empty,
+ AVAuthorizationStatus::Authorized => OSPermissionStatus::Granted,
+ _ => OSPermissionStatus::Denied,
+ }
+ })
}
OSPermissionsCheck {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/space_monitor.rs b/apps/screenpipe-app-tauri/src-tauri/src/space_monitor.rs
index 16ae2addb..767448f2a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/space_monitor.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/space_monitor.rs
@@ -83,8 +83,10 @@ pub fn setup_space_listener(app: AppHandle) {
let app = app_for_block.clone();
let app_inner = app.clone();
let _ = app.run_on_main_thread(move || {
- crate::window_api::clear_frontmost_app();
- hide_main_window(&app_inner);
+ crate::window_api::with_autorelease_pool(|| {
+ crate::window_api::clear_frontmost_app();
+ hide_main_window(&app_inner);
+ });
});
});
let block = block.copy();
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
index 1ed9cd8bf..233057cc7 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
@@ -129,6 +129,7 @@ pub fn recreate_tray(app: &AppHandle) {
// across the FFI boundary (nounwind → abort). catch_unwind prevents this.
let _ = app.run_on_main_thread(move || {
if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ crate::window_api::with_autorelease_pool(|| {
let app = app_for_thread;
let update_item = match UPDATE_MENU_ITEM.lock() {
Ok(guard) => guard.clone(),
@@ -198,6 +199,7 @@ pub fn recreate_tray(app: &AppHandle) {
error!("failed to recreate tray icon: {}", e);
}
}
+ }); // with_autorelease_pool
})) {
// The panic hook already sent the panic message + backtrace to Sentry
// (as a Fatal-level capture_message). Log here for local diagnostics.
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
index 65bc5a067..82d404613 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
@@ -279,11 +279,13 @@ impl UpdatesManager {
// TrayIcon must be accessed/dropped on the main thread
let app_clone = self.app.clone();
let _ = self.app.run_on_main_thread(move || {
- if let Some(tray) = app_clone.tray_by_id("screenpipe_main") {
- if let Err(e) = crate::safe_icon::safe_set_icon_as_template(&tray, image) {
- error!("failed to set tray update icon: {}", e);
+ crate::window_api::with_autorelease_pool(|| {
+ if let Some(tray) = app_clone.tray_by_id("screenpipe_main") {
+ if let Err(e) = crate::safe_icon::safe_set_icon_as_template(&tray, image) {
+ error!("failed to set tray update icon: {}", e);
+ }
}
- }
+ });
});
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs b/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs
index 848d1074d..0b3f00800 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs
@@ -47,7 +47,7 @@ pub fn init_magnify_handler(app: tauri::AppHandle) {
let superclass = Class::get("NSObject").unwrap();
let mut decl = ClassDecl::new("ScreenpipeMagnifyHandler", superclass).unwrap();
extern "C" fn handle_magnify(_this: &Object, _sel: Sel, recognizer: *mut Object) {
- unsafe {
+ with_autorelease_pool(|| unsafe {
use objc::{msg_send, sel, sel_impl};
let magnification: f64 = msg_send![recognizer, magnification];
// Reset so next callback gives delta, not cumulative
@@ -55,7 +55,7 @@ pub fn init_magnify_handler(app: tauri::AppHandle) {
if let Some(app) = MAGNIFY_APP_HANDLE.get() {
let _ = app.emit("native-magnify", magnification);
}
- }
+ });
}
unsafe {
use objc::{sel, sel_impl};
@@ -81,7 +81,7 @@ pub fn init_magnify_handler(app: tauri::AppHandle) {
> = std::sync::OnceLock::new();
extern "C" fn swizzled_scroll_wheel(this: &Object, sel: Sel, event: *mut Object) {
- unsafe {
+ with_autorelease_pool(|| unsafe {
use objc::{msg_send, sel, sel_impl};
// Emit Tauri event with scroll data
if let Some(app) = MAGNIFY_APP_HANDLE.get() {
@@ -108,7 +108,7 @@ pub fn init_magnify_handler(app: tauri::AppHandle) {
if let Some(original) = ORIGINAL_SCROLL_WHEEL.get() {
original(this, sel, event);
}
- }
+ });
}
// Swizzle WKWebView scrollWheel:
@@ -151,59 +151,83 @@ pub fn init_magnify_handler(_app: tauri::AppHandle) {}
/// Safe to call multiple times — skips if already attached.
#[cfg(target_os = "macos")]
unsafe fn attach_magnify_gesture_to_view(view: tauri_nspanel::cocoa::base::id) {
- use objc::{class, msg_send, sel, sel_impl};
- use tauri_nspanel::cocoa::base::{id, nil};
- use tauri_nspanel::cocoa::foundation::NSArray;
+ with_autorelease_pool(|| {
+ use objc::{class, msg_send, sel, sel_impl};
+ use tauri_nspanel::cocoa::base::{id, nil};
+ use tauri_nspanel::cocoa::foundation::NSArray;
- if view == nil {
- return;
- }
+ if view == nil {
+ return;
+ }
- // Check if we already added our recognizer (look for ScreenpipeMagnifyHandler target)
- let recognizers: id = msg_send![view, gestureRecognizers];
- if recognizers != nil {
- let count: u64 = NSArray::count(recognizers);
- let handler_class = class!(ScreenpipeMagnifyHandler);
- for i in 0..count {
- let r: id = NSArray::objectAtIndex(recognizers, i);
- let target: id = msg_send![r, target];
- if target != nil {
- let is_ours: bool = msg_send![target, isKindOfClass: handler_class];
- if is_ours {
- return; // already attached
+ // Check if we already added our recognizer (look for ScreenpipeMagnifyHandler target)
+ let recognizers: id = msg_send![view, gestureRecognizers];
+ if recognizers != nil {
+ let count: u64 = NSArray::count(recognizers);
+ let handler_class = class!(ScreenpipeMagnifyHandler);
+ for i in 0..count {
+ let r: id = NSArray::objectAtIndex(recognizers, i);
+ let target: id = msg_send![r, target];
+ if target != nil {
+ let is_ours: bool = msg_send![target, isKindOfClass: handler_class];
+ if is_ours {
+ return; // already attached
+ }
}
}
}
- }
-
- // Create handler instance
- let handler_class = class!(ScreenpipeMagnifyHandler);
- let handler: id = msg_send![handler_class, new];
-
- // Create NSMagnificationGestureRecognizer
- let recognizer: id = msg_send![class!(NSMagnificationGestureRecognizer), alloc];
- let recognizer: id = msg_send![
- recognizer,
- initWithTarget: handler
- action: sel!(handleMagnify:)
- ];
- // Add to view
- let _: () = msg_send![view, addGestureRecognizer: recognizer];
+ // Create handler instance
+ let handler_class = class!(ScreenpipeMagnifyHandler);
+ let handler: id = msg_send![handler_class, new];
+
+ // Create NSMagnificationGestureRecognizer
+ let recognizer: id = msg_send![class!(NSMagnificationGestureRecognizer), alloc];
+ let recognizer: id = msg_send![
+ recognizer,
+ initWithTarget: handler
+ action: sel!(handleMagnify:)
+ ];
+
+ // Add to view
+ let _: () = msg_send![view, addGestureRecognizer: recognizer];
+ });
}
/// Run a closure on the main thread, catching any panics so they don't abort
/// the process (Rust panics inside `run_on_main_thread` cross the Obj-C FFI
/// boundary in `tao::send_event`, which is `nounwind` → calls `abort()`).
+///
+/// The closure is wrapped in its own `NSAutoreleasePool` so that any
+/// autoreleased ObjC objects created inside are drained immediately,
+/// rather than accumulating in the main event-loop pool (where a
+/// use-after-free causes `objc_autoreleasePoolPop` to SIGSEGV).
#[cfg(target_os = "macos")]
pub fn run_on_main_thread_safe<F: FnOnce() + Send + 'static>(app: &AppHandle, f: F) {
let _ = app.run_on_main_thread(move || {
- if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
+ if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ with_autorelease_pool(f);
+ })) {
error!("panic caught in run_on_main_thread: {:?}", e);
}
});
}
+/// Execute `f` inside a fresh `NSAutoreleasePool`.
+/// This scopes any autoreleased ObjC objects so they are drained
+/// immediately rather than leaking into the caller's pool.
+#[cfg(target_os = "macos")]
+pub fn with_autorelease_pool<R, F: FnOnce() -> R>(f: F) -> R {
+ use objc::{class, msg_send, sel, sel_impl};
+ use tauri_nspanel::cocoa::base::id;
+ unsafe {
+ let pool: id = msg_send![class!(NSAutoreleasePool), new];
+ let result = f();
+ let _: () = msg_send![pool, drain];
+ result
+ }
+}
+
use crate::{
store::{OnboardingStore, SettingsStore},
ServerState,
@@ -219,47 +243,51 @@ static PREVIOUS_FRONTMOST_APP: Lazy<Mutex<usize>> = Lazy::new(|| Mutex::new(0));
/// Save the current frontmost app before activating our overlay.
#[cfg(target_os = "macos")]
fn save_frontmost_app() {
- use objc::{class, msg_send, sel, sel_impl};
- use tauri_nspanel::cocoa::base::{id, nil};
- unsafe {
- let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
- let frontmost: id = msg_send![workspace, frontmostApplication];
- if frontmost != nil {
- let _: () = msg_send![frontmost, retain];
- let mut prev = PREVIOUS_FRONTMOST_APP
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- if *prev != 0 {
- let old = *prev as id;
- let _: () = msg_send![old, release];
+ with_autorelease_pool(|| {
+ use objc::{class, msg_send, sel, sel_impl};
+ use tauri_nspanel::cocoa::base::{id, nil};
+ unsafe {
+ let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
+ let frontmost: id = msg_send![workspace, frontmostApplication];
+ if frontmost != nil {
+ let _: () = msg_send![frontmost, retain];
+ let mut prev = PREVIOUS_FRONTMOST_APP
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ if *prev != 0 {
+ let old = *prev as id;
+ let _: () = msg_send![old, release];
+ }
+ *prev = frontmost as usize;
}
- *prev = frontmost as usize;
}
- }
+ });
}
/// Re-activate the previously frontmost app (saved on show).
/// This keeps macOS in the same Space instead of switching.
#[cfg(target_os = "macos")]
pub fn restore_frontmost_app() {
- use objc::{msg_send, sel, sel_impl};
- let ptr = {
- let mut prev = PREVIOUS_FRONTMOST_APP
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let p = *prev;
- *prev = 0;
- p
- };
- if ptr != 0 {
- use tauri_nspanel::cocoa::base::id;
- unsafe {
- let app: id = ptr as id;
- // NSApplicationActivateIgnoringOtherApps = 1 << 1 = 2
- let _: bool = msg_send![app, activateWithOptions: 2u64];
- let _: () = msg_send![app, release];
+ with_autorelease_pool(|| {
+ use objc::{msg_send, sel, sel_impl};
+ let ptr = {
+ let mut prev = PREVIOUS_FRONTMOST_APP
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let p = *prev;
+ *prev = 0;
+ p
+ };
+ if ptr != 0 {
+ use tauri_nspanel::cocoa::base::id;
+ unsafe {
+ let app: id = ptr as id;
+ // NSApplicationActivateIgnoringOtherApps = 1 << 1 = 2
+ let _: bool = msg_send![app, activateWithOptions: 2u64];
+ let _: () = msg_send![app, release];
+ }
}
- }
+ });
}
/// Clear the saved frontmost app without re-activating it.
@@ -267,22 +295,24 @@ pub fn restore_frontmost_app() {
/// pull them back by re-activating the previous app.
#[cfg(target_os = "macos")]
pub fn clear_frontmost_app() {
- use objc::{msg_send, sel, sel_impl};
- let ptr = {
- let mut prev = PREVIOUS_FRONTMOST_APP
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let p = *prev;
- *prev = 0;
- p
- };
- if ptr != 0 {
- use tauri_nspanel::cocoa::base::id;
- unsafe {
- let app: id = ptr as id;
- let _: () = msg_send![app, release];
+ with_autorelease_pool(|| {
+ use objc::{msg_send, sel, sel_impl};
+ let ptr = {
+ let mut prev = PREVIOUS_FRONTMOST_APP
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let p = *prev;
+ *prev = 0;
+ p
+ };
+ if ptr != 0 {
+ use tauri_nspanel::cocoa::base::id;
+ unsafe {
+ let app: id = ptr as id;
+ let _: () = msg_send![app, release];
+ }
}
- }
+ });
}
/// Check if our own app (screenpipe) is still the active macOS application.
@@ -292,13 +322,15 @@ pub fn clear_frontmost_app() {
/// frontmost app or just clear it.
#[cfg(target_os = "macos")]
fn is_own_app_still_active() -> bool {
- use objc::{msg_send, sel, sel_impl};
- use tauri_nspanel::cocoa::base::id;
- unsafe {
- let ns_app: id = msg_send![objc::class!(NSApplication), sharedApplication];
- let active: bool = msg_send![ns_app, isActive];
- active
- }
+ with_autorelease_pool(|| {
+ use objc::{msg_send, sel, sel_impl};
+ use tauri_nspanel::cocoa::base::id;
+ unsafe {
+ let ns_app: id = msg_send![objc::class!(NSApplication), sharedApplication];
+ let active: bool = msg_send![ns_app, isActive];
+ active
+ }
+ })
}
/// Conditionally restore or clear the saved frontmost app.
@@ -347,6 +379,7 @@ fn restore_frontmost_app_if_external_with_app(app: Option<&AppHandle>) {
/// when re-showing an existing window.
#[cfg(target_os = "macos")]
pub unsafe fn make_nswindow_webview_first_responder(ns_win: tauri_nspanel::cocoa::base::id) {
+ with_autorelease_pool(|| {
use objc::{class, msg_send, sel, sel_impl};
use tauri_nspanel::cocoa::base::{id, nil};
use tauri_nspanel::cocoa::foundation::NSArray;
@@ -410,12 +443,12 @@ pub unsafe fn make_nswindow_webview_first_responder(ns_win: tauri_nspanel::cocoa
wk_id: usize,
}
extern "C" fn set_responder(ctx: *mut std::ffi::c_void) {
- unsafe {
+ with_autorelease_pool(|| unsafe {
let ctx = Box::from_raw(ctx as *mut Ctx);
let window: id = ctx.win_id as id;
let wk: id = ctx.wk_id as id;
let _: () = msg_send![window, makeFirstResponder: wk];
- }
+ });
}
let ctx = Box::into_raw(Box::new(Ctx { win_id, wk_id }));
dispatch_async_f(
@@ -424,6 +457,7 @@ pub unsafe fn make_nswindow_webview_first_responder(ns_win: tauri_nspanel::cocoa
set_responder,
);
}
+ }); // with_autorelease_pool
}
/// Find the WKWebView inside an NSPanel's content view and make it first responder.
@@ -436,6 +470,7 @@ pub unsafe fn make_nswindow_webview_first_responder(ns_win: tauri_nspanel::cocoa
/// own responder-chain update to the end of the current event, overwriting our call.
#[cfg(target_os = "macos")]
pub unsafe fn make_webview_first_responder(panel: &tauri_nspanel::raw_nspanel::RawNSPanel) {
+ with_autorelease_pool(|| {
use objc::{class, msg_send, sel, sel_impl};
use tauri_nspanel::cocoa::base::{id, nil};
use tauri_nspanel::cocoa::foundation::NSArray;
@@ -497,12 +532,12 @@ pub unsafe fn make_webview_first_responder(panel: &tauri_nspanel::raw_nspanel::R
wk_id: usize,
}
extern "C" fn set_responder(ctx: *mut std::ffi::c_void) {
- unsafe {
+ with_autorelease_pool(|| unsafe {
let ctx = Box::from_raw(ctx as *mut Ctx);
let window: id = ctx.panel_id as id;
let wk: id = ctx.wk_id as id;
let _: () = msg_send![window, makeFirstResponder: wk];
- }
+ });
}
let ctx = Box::into_raw(Box::new(Ctx { panel_id, wk_id }));
dispatch_async_f(
@@ -510,6 +545,7 @@ pub unsafe fn make_webview_first_responder(panel: &tauri_nspanel::raw_nspanel::R
ctx as *mut std::ffi::c_void,
set_responder,
);
+ }); // with_autorelease_pool
}
/// Shared panel visibility sequence — the single source of truth for making an
@@ -527,24 +563,26 @@ unsafe fn show_panel_visible(
app: &AppHandle,
activate_app: bool,
) {
- use objc::{msg_send, sel, sel_impl};
- use tauri_nspanel::cocoa::base::id;
+ with_autorelease_pool(|| {
+ use objc::{msg_send, sel, sel_impl};
+ use tauri_nspanel::cocoa::base::id;
- save_frontmost_app();
+ save_frontmost_app();
- let _: () = msg_send![&*panel, setAlphaValue: 1.0f64];
+ let _: () = msg_send![&*panel, setAlphaValue: 1.0f64];
- if activate_app {
- let ns_app: id = msg_send![objc::class!(NSApplication), sharedApplication];
- let _: () = msg_send![ns_app, activateIgnoringOtherApps: true];
- }
+ if activate_app {
+ let ns_app: id = msg_send![objc::class!(NSApplication), sharedApplication];
+ let _: () = msg_send![ns_app, activateIgnoringOtherApps: true];
+ }
- panel.order_front_regardless();
- panel.make_key_window();
- make_webview_first_responder(panel);
+ panel.order_front_regardless();
+ panel.make_key_window();
+ make_webview_first_responder(panel);
- MAIN_PANEL_SHOWN.store(true, std::sync::atomic::Ordering::SeqCst);
- let _ = app.emit("window-focused", true);
+ MAIN_PANEL_SHOWN.store(true, std::sync::atomic::Ordering::SeqCst);
+ let _ = app.emit("window-focused", true);
+ });
}
/// Logical visibility of the main panel. `true` means the panel is (or should
@@ -1409,16 +1447,18 @@ impl ShowRewindWindow {
{
let app2 = app.clone();
let _ = app.run_on_main_thread(move || {
- // Conditional restore: if focus moved to another
- // screenpipe window (Settings, Chat), just clear.
- // Only activate previous external app if our app
- // is no longer active.
- restore_frontmost_app_if_external_with_app(Some(&app2));
- // order_out removes the invisible panel from
- // the screen so it can't receive stray clicks.
- if let Ok(panel) = app2.get_webview_panel("main-window") {
- panel.order_out(None);
- }
+ with_autorelease_pool(|| {
+ // Conditional restore: if focus moved to another
+ // screenpipe window (Settings, Chat), just clear.
+ // Only activate previous external app if our app
+ // is no longer active.
+ restore_frontmost_app_if_external_with_app(Some(&app2));
+ // order_out removes the invisible panel from
+ // the screen so it can't receive stray clicks.
+ if let Ok(panel) = app2.get_webview_panel("main-window") {
+ panel.order_out(None);
+ }
+ });
});
}
// Unregister window shortcuts on focus loss (#2219)
@@ -1755,15 +1795,17 @@ impl ShowRewindWindow {
main_label_for_mode(&mode).to_string()
};
let _ = app.run_on_main_thread(move || {
- // Conditional restore: if focus moved to another
- // screenpipe window, just clear. Only activate
- // previous external app if ours is inactive.
- restore_frontmost_app_if_external_with_app(Some(&app2));
- // order_out removes the invisible panel so it
- // can't receive stray clicks at alpha=0.
- if let Ok(panel) = app2.get_webview_panel(&lbl) {
- panel.order_out(None);
- }
+ with_autorelease_pool(|| {
+ // Conditional restore: if focus moved to another
+ // screenpipe window, just clear. Only activate
+ // previous external app if ours is inactive.
+ restore_frontmost_app_if_external_with_app(Some(&app2));
+ // order_out removes the invisible panel so it
+ // can't receive stray clicks at alpha=0.
+ if let Ok(panel) = app2.get_webview_panel(&lbl) {
+ panel.order_out(None);
+ }
+ });
});
}
// Unregister window-specific shortcuts (arrows, Escape)
@@ -2141,12 +2183,12 @@ impl ShowRewindWindow {
MAIN_PANEL_SHOWN.store(false, std::sync::atomic::Ordering::SeqCst);
let app_clone = app.clone();
run_on_main_thread_safe(app, move || {
- use objc::{msg_send, sel, sel_impl};
for label in &["main", "main-window"] {
if let Ok(panel) = app_clone.get_webview_panel(label) {
if panel.is_visible() {
// Alpha=0 first for instant visual hide
unsafe {
+ use objc::{msg_send, sel, sel_impl};
let _: () = msg_send![&*panel, setAlphaValue: 0.0f64];
}
panel.order_out(None);