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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: single worker thread for livetext analysis, prevents GCD thread exhaustion freeze, bump app to v2.2.152
Louis Beaumonta3e29d42ab99
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex b74ea1774..bca250c7d 100644--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -9329,7 +9329,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.2.150"+version = "2.2.151"dependencies = ["anyhow","arboard",diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex bec35767a..a7da4c022 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.151"+version = "2.2.152"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs b/apps/screenpipe-app-tauri/src-tauri/src/livetext.rsindex cec7a4178..87a4f977a 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs@@ -29,11 +29,102 @@ unsafe fn extract_and_free(ptr: *mut std::os::raw::c_char) -> Option<String> {}/// Generation counter — incremented on every analyze call.-/// The spawned thread checks this before doing expensive work;+/// The worker thread checks this before doing expensive work;/// if a newer request has arrived, it bails out early.#[cfg(target_os = "macos")]static ANALYZE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+/// Single worker thread for livetext analysis. Prevents thread pile-up when+/// VisionKit is slow — only the latest request is processed, older ones are+/// dropped. Without this, each analyze call spawns a thread that blocks on+/// VisionKit's DispatchSemaphore, hitting GCD's 80-thread limit and freezing.+#[cfg(target_os = "macos")]+static ANALYZE_WORKER: std::sync::OnceLock<std::sync::mpsc::SyncSender<AnalyzeRequest>> =+ std::sync::OnceLock::new();++#[cfg(target_os = "macos")]+struct AnalyzeRequest {+ image_path: String,+ frame_id: String,+ x: f64,+ y: f64,+ w: f64,+ h: f64,+ gen: u64,+ reply: std::sync::mpsc::Sender<Result<String, String>>,+}++#[cfg(target_os = "macos")]+fn get_analyze_worker() -> &'static std::sync::mpsc::SyncSender<AnalyzeRequest> {+ ANALYZE_WORKER.get_or_init(|| {+ // SyncSender with capacity 0 — new requests replace old ones+ let (tx, rx) = std::sync::mpsc::sync_channel::<AnalyzeRequest>(1);+ std::thread::Builder::new()+ .name("livetext-worker".into())+ .spawn(move || {+ loop {+ // Block waiting for next request+ let req = match rx.recv() {+ Ok(r) => r,+ Err(_) => break, // channel closed+ };++ // Drain any queued requests — only process the latest+ let mut latest = req;+ while let Ok(newer) = rx.try_recv() {+ // Drop older request's reply channel (caller gets RecvError)+ let _ = latest.reply;+ latest = newer;+ }++ // Check generation before expensive work+ if ANALYZE_GENERATION.load(std::sync::atomic::Ordering::SeqCst) != latest.gen {+ let _ = latest.reply.send(Err("skipped: newer analyze request pending".to_string()));+ continue;+ }++ let result = crate::window::with_autorelease_pool(|| -> Result<String, String> {+ let path_c = CString::new(latest.image_path.clone())+ .map_err(|e| format!("invalid path: {}", e))?;+ let frame_id_c = CString::new(latest.frame_id.clone())+ .map_err(|e| format!("invalid frame_id: {}", e))?;++ let mut out_text: *mut std::os::raw::c_char = std::ptr::null_mut();+ let mut out_error: *mut std::os::raw::c_char = std::ptr::null_mut();++ let status = unsafe {+ livetext_ffi::lt_analyze_image(+ path_c.as_ptr(),+ frame_id_c.as_ptr(),+ latest.x,+ latest.y,+ latest.w,+ latest.h,+ &mut out_text,+ &mut out_error,+ )+ };++ unsafe {+ if status != 0 {+ let err = extract_and_free(out_error)+ .unwrap_or_else(|| "unknown error".to_string());+ extract_and_free(out_text);+ return Err(format!("live text analysis failed: {}", err));+ }+ let text = extract_and_free(out_text).unwrap_or_default();+ extract_and_free(out_error);+ Ok(text)+ }+ });+ let _ = latest.reply.send(result);+ }+ })+ .expect("failed to spawn livetext worker thread");+ tx+ })+}+// ---------- Tauri commands ----------#[tauri::command]@@ -112,61 +203,29 @@ pub async fn livetext_analyze() -> Result<String, String> {#[cfg(target_os = "macos")]{- // Bump generation — any in-flight analysis with an older generation will bail out.+ // Bump generation — the worker checks this before doing expensive work.let gen = ANALYZE_GENERATION.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;- // Run on a dedicated thread to avoid blocking tokio runtime- // (the Swift semaphore.wait() inside lt_analyze_image would deadlock- // if called from a tokio worker thread)- let (tx, rx) = std::sync::mpsc::channel();- std::thread::spawn(move || {- // Wrap in autorelease pool — Swift FFI may create autoreleased- // ObjC objects internally, and this thread has no default pool.- let result = crate::window::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());- }+ // Send to single worker thread. This prevents thread pile-up when+ // VisionKit is slow — only one analysis runs at a time, and stale+ // requests are drained from the queue before processing.+ let (reply_tx, reply_rx) = std::sync::mpsc::channel();+ let worker = get_analyze_worker();- let path_c =- CString::new(image_path.clone()).map_err(|e| format!("invalid path: {}", e))?;- let frame_id_c =- CString::new(frame_id.clone()).map_err(|e| format!("invalid frame_id: {}", e))?;-- let mut out_text: *mut std::os::raw::c_char = std::ptr::null_mut();- let mut out_error: *mut std::os::raw::c_char = std::ptr::null_mut();-- let status = unsafe {- livetext_ffi::lt_analyze_image(- path_c.as_ptr(),- frame_id_c.as_ptr(),- x,- y,- w,- h,- &mut out_text,- &mut out_error,- )- };-- unsafe {- if status != 0 {- let err = extract_and_free(out_error)- .unwrap_or_else(|| "unknown error".to_string());- extract_and_free(out_text);- return Err(format!("live text analysis failed: {}", err));- }- let text = extract_and_free(out_text).unwrap_or_default();- extract_and_free(out_error);- Ok(text)- }- });- let _ = tx.send(result);+ // try_send: if the worker's queue is full (capacity=1), the old+ // request is still in the queue. That's fine — the worker drains+ // stale requests before processing.+ let _ = worker.try_send(AnalyzeRequest {+ image_path,+ frame_id,+ x, y, w, h,+ gen,+ reply: reply_tx,});- return rx+ return reply_rx.recv()- .map_err(|_| "analyze thread channel closed".to_string())?;+ .map_err(|_| "skipped: superseded by newer request".to_string())?;}#[cfg(not(target_os = "macos"))]{