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

release-app fix #901 again, use Window thread-safe

Louis Beaumontdc859fb5fe11
diff --git a/Cargo.toml b/Cargo.toml
index 6dc76e638..f6a93f068 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ resolver = "2"
[workspace.package]
-version = "0.2.45"
+version = "0.2.46"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index f5669579e..693a6c82c 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.33.6"
+version = "0.33.7"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-audio/tests/realtime_test.rs b/screenpipe-audio/tests/realtime_test.rs
index f9a673603..7706a1976 100644
--- a/screenpipe-audio/tests/realtime_test.rs
+++ b/screenpipe-audio/tests/realtime_test.rs
@@ -1,5 +1,8 @@
-use screenpipe_audio::deepgram::start_deepgram_stream;
-use screenpipe_audio::{pcm_decode, AudioDevice, DeviceType};
+use futures::StreamExt;
+use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
+use screenpipe_audio::{deepgram::start_deepgram_stream, AudioDevice};
+use screenpipe_audio::{pcm_decode, DeviceType};
+use screenpipe_events::subscribe_to_event;
use std::{
sync::{atomic::AtomicBool, Arc},
time::Duration,
@@ -13,7 +16,9 @@ use tokio::sync::broadcast;
#[tokio::test]
#[ignore]
async fn test_realtime_transcription() {
- let (samples, sample_rate) = pcm_decode("test_data/accuracy1.wav").unwrap();
+ let (samples, sample_rate) = pcm_decode("test_data/accuracy1.wav").unwrap_or_else(|e| {
+ panic!("Failed to decode audio: {}", e);
+ });
let (stream_tx, stream_rx) = broadcast::channel(sample_rate as usize * 3);
let device = AudioDevice::new("test".to_string(), DeviceType::Output);
@@ -21,9 +26,6 @@ async fn test_realtime_transcription() {
let deepgram_api_key = std::env::var("CUSTOM_DEEPGRAM_API_KEY").unwrap();
- let (realtime_transcription_sender, realtime_transcription_receiver) =
- broadcast::channel(10000);
-
let is_running_clone = is_running.clone();
tokio::spawn(async move {
@@ -31,9 +33,7 @@ async fn test_realtime_transcription() {
stream_rx,
Arc::new(device),
sample_rate,
- Arc::new(realtime_transcription_sender),
is_running_clone,
- vec![],
Some(deepgram_api_key),
)
.await;
@@ -42,17 +42,17 @@ async fn test_realtime_transcription() {
});
let transcription_receiver_handle = tokio::spawn(async move {
- let mut receiver = realtime_transcription_receiver;
+ let mut receiver = subscribe_to_event::<RealtimeTranscriptionEvent>("transcription");
loop {
tokio::select! {
- event = receiver.recv() => {
- if let Ok(event) = event {
- println!("Received event: {:?}", event.transcription);
+ event = receiver.next() => {
+ if let Some(event) = event {
+ println!("Received event: {:?}", event.data.transcription);
} else {
println!("Receiver closed");
}
},
- _ = tokio::time::sleep(Duration::from_secs(10)) => {
+ _ = tokio::time::sleep(Duration::from_secs(15)) => {
println!("Timeout");
return;
}
@@ -60,13 +60,15 @@ async fn test_realtime_transcription() {
}
});
- tokio::time::sleep(Duration::from_secs(5)).await;
+ tokio::time::sleep(Duration::from_secs(10)).await;
let tx = stream_tx.clone();
let samples = samples.clone();
for sample in samples.chunks(sample_rate as usize * 5) {
- tx.send(sample.to_vec()).unwrap();
+ tx.send(sample.to_vec()).unwrap_or_else(|e| {
+ panic!("Failed to send sample: {}", e);
+ });
tokio::time::sleep(Duration::from_millis(10)).await;
}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index d28963499..a75075d73 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -156,7 +156,7 @@ path = "src/bin/screenpipe-server.rs"
[package.metadata.cargo-machete]
-ignored = ["url"]
+ignored = ["url", "console-subscriber"]
[target.'cfg(unix)'.dependencies]
nix = { version = "0.29", features = ["signal"] }
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 312863760..123f10ea7 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -952,16 +952,6 @@ impl DatabaseManager {
speaker_ids: Option<Vec<i64>>,
frame_name: Option<&str>,
) -> Result<usize, sqlx::Error> {
- // binding order:
- // ?1 = query
- // ?2 = start_time
- // ?3 = end_time
- // ?4 = app_name
- // ?5 = window_name
- // ?6 = frame_name (for OCR only)
- // ?7 = min_length (for text/transcription length)
- // ?8 = max_length (for text/transcription length)
- // ?9 = json array for speaker_ids (for audio only)
let json_array = if let Some(ids) = speaker_ids {
if !ids.is_empty() {
serde_json::to_string(&ids).unwrap_or_default()
@@ -1008,9 +998,9 @@ impl DatabaseManager {
WHERE {match_condition}
AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)
AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)
- AND (?6 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?6)
- AND (?7 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?7)
- AND (json_array_length(?8) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?8)))
+ AND (?4 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?4)
+ AND (?5 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?5)
+ AND (json_array_length(?6) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?6)))
"#,
table = if query.is_empty() {
"audio_transcriptions"
@@ -1065,7 +1055,6 @@ impl DatabaseManager {
AND (?6 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) >= ?6)
AND (?7 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) <= ?7)
AND (?8 IS NULL OR frames.name LIKE '%' || ?8 || '%' COLLATE NOCASE)
- AND ocr_text.text != 'No text found'
UNION ALL
-- Audio part
SELECT DISTINCT audio_transcriptions.id
@@ -1125,19 +1114,35 @@ impl DatabaseManager {
_ => return Ok(0),
};
- let count: (i64,) = sqlx::query_as(&sql)
- .bind(query) // ?1
- .bind(start_time) // ?2
- .bind(end_time) // ?3
- .bind(app_name) // ?4
- .bind(window_name) // ?5
- .bind(frame_name) // ?6
- .bind(min_length.map(|l| l as i64)) // ?7
- .bind(max_length.map(|l| l as i64)) // ?8
- .bind(json_array) // ?9
- .fetch_one(&self.pool)
- .await?;
- Ok(count.0 as usize)
+ let count: i64 = match content_type {
+ ContentType::Audio => {
+ sqlx::query_scalar(&sql)
+ .bind(query)
+ .bind(start_time)
+ .bind(end_time)
+ .bind(min_length.map(|l| l as i64))
+ .bind(max_length.map(|l| l as i64))
+ .bind(json_array)
+ .fetch_one(&self.pool)
+ .await?
+ }
+ _ => {
+ sqlx::query_scalar(&sql)
+ .bind(query)
+ .bind(start_time)
+ .bind(end_time)
+ .bind(app_name)
+ .bind(window_name)
+ .bind(frame_name)
+ .bind(min_length.map(|l| l as i64))
+ .bind(max_length.map(|l| l as i64))
+ .bind(json_array)
+ .fetch_one(&self.pool)
+ .await?
+ }
+ };
+
+ Ok(count as usize)
}
pub async fn get_latest_timestamps(
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 63f064e91..48cd8eb9c 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -6,6 +6,7 @@ mod tests {
use axum::Router;
use chrono::DateTime;
use chrono::{Duration, Utc};
+ use lru::LruCache;
use screenpipe_audio::{AudioDevice, DeviceType};
use screenpipe_server::db_types::ContentType;
use screenpipe_server::db_types::SearchResult;
@@ -16,10 +17,10 @@ mod tests {
};
use screenpipe_vision::OcrEngine; // Adjust this import based on your actual module structure
use serde::Deserialize;
- use std::collections::HashMap;
+ use std::num::NonZeroUsize;
use std::path::PathBuf;
- use std::sync::atomic::AtomicBool;
use std::sync::Arc;
+ use tokio::sync::Mutex;
use tower::ServiceExt; // for `oneshot` and `ready`
// Before the test function, add:
@@ -32,9 +33,6 @@ mod tests {
let app_state = Arc::new(AppState {
db: db.clone(),
- vision_control: Arc::new(AtomicBool::new(false)),
- audio_devices_tx: Arc::new(tokio::sync::broadcast::channel(1000).0),
- devices_status: HashMap::new(),
app_start_time: Utc::now(),
screenpipe_dir: PathBuf::from(""),
pipe_manager: Arc::new(PipeManager::new(PathBuf::from(""))),
@@ -44,9 +42,9 @@ mod tests {
FrameCache::new(PathBuf::from(""), db).await.unwrap(),
)),
ui_monitoring_enabled: false,
- realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
- realtime_transcription_enabled: false,
- realtime_vision_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
+ frame_image_cache: Some(Arc::new(Mutex::new(LruCache::new(
+ NonZeroUsize::new(100).unwrap(),
+ )))),
});
let router = create_router();
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index 57bca9a7b..5e2accbc2 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -4,12 +4,12 @@ use axum::{
Router,
};
use chrono::Utc;
+use lru::LruCache;
use screenpipe_audio::{AudioDevice, DeviceType};
use screenpipe_vision::OcrEngine;
use serde_json::json;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-use std::{collections::HashMap, path::PathBuf};
+use std::{num::NonZeroUsize, path::PathBuf, sync::Arc};
+use tokio::sync::Mutex;
use tower::ServiceExt;
use screenpipe_server::{
@@ -29,9 +29,6 @@ async fn setup_test_app() -> (Router, Arc<AppState>) {
db: db.clone(),
vision_disabled: false,
audio_disabled: false,
- vision_control: Arc::new(AtomicBool::new(false)),
- audio_devices_tx: Arc::new(tokio::sync::broadcast::channel(1000).0),
- devices_status: HashMap::new(),
app_start_time: Utc::now(),
screenpipe_dir: PathBuf::from(""),
pipe_manager: Arc::new(PipeManager::new(PathBuf::from(""))),
@@ -39,9 +36,9 @@ async fn setup_test_app() -> (Router, Arc<AppState>) {
FrameCache::new(PathBuf::from(""), db).await.unwrap(),
)),
ui_monitoring_enabled: false,
- realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
- realtime_transcription_enabled: false,
- realtime_vision_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
+ frame_image_cache: Some(Arc::new(Mutex::new(LruCache::new(
+ NonZeroUsize::new(100).unwrap(),
+ )))),
});
let app = create_router().with_state(app_state.clone());
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index a700b2a18..1ee957ebd 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -46,7 +46,6 @@ serde = "1.0.200"
xcap = { package = "xcap", git = "https://github.com/nashaofu/xcap", rev = "214cb44" }
once_cell = { workspace = true }
-chrono = { version = "0.4.39", features = ["serde"] }
base64 = "0.22.1"
reqwest = { workspace = true }
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index 266165172..183f0f0b8 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -4,8 +4,6 @@ use once_cell::sync::Lazy;
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
-use std::time::Duration;
-use tokio::time;
use xcap::{Window, XCapError};
@@ -197,31 +195,27 @@ pub async fn capture_all_visible_windows(
) -> Result<Vec<CapturedWindow>, Box<dyn Error>> {
let mut all_captured_images = Vec::new();
- let windows = retry_with_backoff(
- || {
- let windows = Window::all()?;
- if windows.is_empty() {
- Err(CaptureError::NoWindows)
- } else {
- Ok(windows)
- }
- },
- 3,
- Duration::from_millis(500),
- )
- .await?;
+ // Execute the window capture on the current thread
+ let windows = tokio::task::spawn_blocking(Window::all).await??;
+
+ if windows.is_empty() {
+ return Err(Box::new(CaptureError::NoWindows));
+ }
- for window in &windows {
- let is_valid = is_valid_window(window, monitor, window_filters, capture_unfocused_windows);
+ for window in windows {
+ let is_valid = is_valid_window(&window, monitor, window_filters, capture_unfocused_windows);
if !is_valid {
continue;
}
- let app_name = window.app_name();
- let window_name = window.title();
+ // Store these before moving window
+ let app_name = window.app_name().to_string();
+ let window_name = window.title().to_string();
+ let is_focused = window.is_focused();
- match window.capture_image() {
+ // Now we can move window
+ match tokio::task::spawn_blocking(move || window.capture_image()).await? {
Ok(buffer) => {
let image = DynamicImage::ImageRgba8(
image::ImageBuffer::from_raw(
@@ -234,9 +228,9 @@ pub async fn capture_all_visible_windows(
all_captured_images.push(CapturedWindow {
image,
- app_name: app_name.to_string(),
- window_name: window_name.to_string(),
- is_focused: window.is_focused(),
+ app_name,
+ window_name,
+ is_focused,
});
}
Err(e) => error!(
@@ -275,34 +269,3 @@ pub fn is_valid_window(
filters.is_valid(app_name, title)
}
-
-async fn retry_with_backoff<F, T, E>(
- mut f: F,
- max_retries: u32,
- initial_delay: Duration,
-) -> Result<T, E>
-where
- F: FnMut() -> Result<T, E>,
- E: Error + 'static,
-{
- let mut delay = initial_delay;
- for attempt in 1..=max_retries {
- // info!("Attempt {} to execute function", attempt);
- match f() {
- Ok(result) => {
- // info!("Function executed successfully on attempt {}", attempt);
- return Ok(result);
- }
- Err(e) => {
- if attempt == max_retries {
- error!("All {} attempts failed. Last error: {}", max_retries, e);
- return Err(e);
- }
- // warn!("Attempt {} failed: {}. Retrying in {:?}", attempt, e, delay);
- time::sleep(delay).await;
- delay *= 2;
- }
- }
- }
- unreachable!()
-}