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: cargo fmt + remove unused deps (dirs, tracing, keyring, async-stream)

Louis Beaumont6aa868ac50bb
diff --git a/Cargo.lock b/Cargo.lock
index cdfb4d5f7..3a968c00a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3601,16 +3601,6 @@ dependencies = [
"wasm-bindgen",
]
-[[package]]
-name = "keyring"
-version = "3.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
-dependencies = [
- "log",
- "zeroize",
-]
-
[[package]]
name = "khronos-egl"
version = "6.0.0"
@@ -6588,7 +6578,6 @@ dependencies = [
"specta",
"tempfile",
"toml 0.8.23",
- "tracing",
]
[[package]]
@@ -6667,7 +6656,6 @@ dependencies = [
"anyhow",
"chrono",
"criterion",
- "dirs 5.0.1",
"futures",
"image",
"libsqlite3-sys",
@@ -6817,7 +6805,6 @@ version = "0.3.202"
dependencies = [
"argon2",
"chacha20poly1305",
- "keyring",
"rand 0.8.5",
"serde",
"serde_json",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 18752c337..621950c76 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -95,7 +95,6 @@ raw-window-handle = "0.6"
notify = "8.0.0"
futures = "0.3.30"
-async-stream = "0.3"
chrono = "0.4.39"
chrono-tz = "0.10"
diff --git a/crates/screenpipe-a11y/src/platform/windows.rs b/crates/screenpipe-a11y/src/platform/windows.rs
index 630a6ebad..a725ae84a 100644
--- a/crates/screenpipe-a11y/src/platform/windows.rs
+++ b/crates/screenpipe-a11y/src/platform/windows.rs
@@ -20,6 +20,8 @@ use super::windows_uia::{self, ClickElementRequest};
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::System::Threading::GetCurrentThreadId;
+use windows::Win32::UI::Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK};
use windows::Win32::UI::Input::KeyboardAndMouse::{
GetKeyState, VK_CAPITAL, VK_CONTROL, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU,
VK_RCONTROL, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SHIFT,
@@ -28,15 +30,10 @@ use windows::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, DispatchMessageW, GetForegroundWindow, GetMessageW, GetWindowTextW,
GetWindowThreadProcessId, PostThreadMessageW, SetTimer, SetWindowsHookExW, TranslateMessage,
UnhookWindowsHookEx, EVENT_SYSTEM_FOREGROUND, HC_ACTION, HHOOK, KBDLLHOOKSTRUCT, MSG,
- MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, WINEVENT_OUTOFCONTEXT,
- WINEVENT_SKIPOWNPROCESS, WM_KEYDOWN, WM_KEYUP, WM_LBUTTONDOWN, WM_MBUTTONDOWN,
- WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_QUIT, WM_RBUTTONDOWN, WM_SYSKEYDOWN, WM_SYSKEYUP,
- WM_TIMER, WM_XBUTTONDOWN,
-};
-use windows::Win32::UI::Accessibility::{
- SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK,
+ MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS,
+ WM_KEYDOWN, WM_KEYUP, WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_QUIT,
+ WM_RBUTTONDOWN, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TIMER, WM_XBUTTONDOWN,
};
-use windows::Win32::System::Threading::GetCurrentThreadId;
/// Permission status for UI capture
#[derive(Debug, Clone)]
@@ -1308,7 +1305,9 @@ fn run_app_observer(
}
/// Cached PID→process name mapping with TTL to avoid CreateToolhelp32Snapshot on every lookup.
-static PROCESS_NAME_CACHE: std::sync::OnceLock<Mutex<std::collections::HashMap<u32, (String, Instant)>>> = std::sync::OnceLock::new();
+static PROCESS_NAME_CACHE: std::sync::OnceLock<
+ Mutex<std::collections::HashMap<u32, (String, Instant)>>,
+> = std::sync::OnceLock::new();
fn process_name_cache() -> &'static Mutex<std::collections::HashMap<u32, (String, Instant)>> {
PROCESS_NAME_CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
diff --git a/crates/screenpipe-a11y/src/platform/windows_uia.rs b/crates/screenpipe-a11y/src/platform/windows_uia.rs
index a49a6fb53..01a5ed647 100644
--- a/crates/screenpipe-a11y/src/platform/windows_uia.rs
+++ b/crates/screenpipe-a11y/src/platform/windows_uia.rs
@@ -37,7 +37,7 @@ use windows::Win32::UI::Accessibility::{
};
use windows::Win32::UI::WindowsAndMessaging::{
DispatchMessageW, GetForegroundWindow, GetWindowTextW, GetWindowThreadProcessId,
- MsgWaitForMultipleObjects, PeekMessageW, QS_ALLINPUT, TranslateMessage, MSG, PM_REMOVE,
+ MsgWaitForMultipleObjects, PeekMessageW, TranslateMessage, MSG, PM_REMOVE, QS_ALLINPUT,
};
/// Shared state for pending focus changes (set by COM handler, read by UIA thread)
@@ -702,14 +702,15 @@ pub fn run_uia_thread(
// Block until a Windows message arrives or a computed timeout elapses.
// This replaces the old 50ms sleep-poll: the thread stays asleep until
// something actually needs to happen (COM event, debounce, or re-capture).
- let wait_ms = compute_next_timeout(&pending_focus, debounce_dur, &last_capture_time, interval_dur, &config);
+ let wait_ms = compute_next_timeout(
+ &pending_focus,
+ debounce_dur,
+ &last_capture_time,
+ interval_dur,
+ &config,
+ );
unsafe {
- MsgWaitForMultipleObjects(
- None,
- false,
- wait_ms as u32,
- QS_ALLINPUT,
- );
+ MsgWaitForMultipleObjects(None, false, wait_ms as u32, QS_ALLINPUT);
}
}
diff --git a/crates/screenpipe-a11y/src/tree/mod.rs b/crates/screenpipe-a11y/src/tree/mod.rs
index ad9a3069e..a7e465c79 100644
--- a/crates/screenpipe-a11y/src/tree/mod.rs
+++ b/crates/screenpipe-a11y/src/tree/mod.rs
@@ -46,7 +46,6 @@ pub struct AccessibilityTreeNode {
pub bounds: Option<NodeBounds>,
// --- Automation properties (all Optional, filled per-platform) ---
-
/// Stable unique identifier for targeting elements.
/// Windows: UIA AutomationId. macOS: AXIdentifier. Linux: AT-SPI object path.
#[serde(skip_serializing_if = "Option::is_none")]
diff --git a/crates/screenpipe-a11y/src/tree/windows.rs b/crates/screenpipe-a11y/src/tree/windows.rs
index 69b78bb12..8420d9af2 100644
--- a/crates/screenpipe-a11y/src/tree/windows.rs
+++ b/crates/screenpipe-a11y/src/tree/windows.rs
@@ -423,7 +423,13 @@ fn extract_text_from_tree(
if let Some(ref val) = node.value {
if !val.trim().is_empty() {
append_text(buffer, val);
- nodes.push(make_tree_node(node, ct, val.trim(), depth, norm_bounds.clone()));
+ nodes.push(make_tree_node(
+ node,
+ ct,
+ val.trim(),
+ depth,
+ norm_bounds.clone(),
+ ));
// Don't recurse into text controls — their children are sub-elements of the same text
return;
}
@@ -446,7 +452,13 @@ fn extract_text_from_tree(
} else {
// Non-URL value — treat as text content
append_text(buffer, trimmed);
- nodes.push(make_tree_node(node, ct, trimmed, depth, norm_bounds.clone()));
+ nodes.push(make_tree_node(
+ node,
+ ct,
+ trimmed,
+ depth,
+ norm_bounds.clone(),
+ ));
}
}
}
@@ -456,7 +468,13 @@ fn extract_text_from_tree(
if let Some(ref name) = node.name {
if !name.trim().is_empty() {
append_text(buffer, name);
- nodes.push(make_tree_node(node, ct, name.trim(), depth, norm_bounds.clone()));
+ nodes.push(make_tree_node(
+ node,
+ ct,
+ name.trim(),
+ depth,
+ norm_bounds.clone(),
+ ));
}
}
}
@@ -469,7 +487,13 @@ fn extract_text_from_tree(
if let Some(ref val) = node.value {
if !val.trim().is_empty() {
append_text(buffer, val);
- nodes.push(make_tree_node(node, ct, val.trim(), depth, norm_bounds.clone()));
+ nodes.push(make_tree_node(
+ node,
+ ct,
+ val.trim(),
+ depth,
+ norm_bounds.clone(),
+ ));
}
} else if ct.eq_ignore_ascii_case("Custom") {
// Custom elements in Electron apps often have names
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index 1a8b017e0..d154cd53e 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -948,10 +948,7 @@ impl AudioManager {
/// Seed the embedding manager with named speakers from the DB.
/// This allows returning voices to be recognized immediately instead of
/// starting anonymous for the first 30+ seconds.
-async fn seed_speakers_from_db(
- db: &Arc<DatabaseManager>,
- seg_mgr: &Arc<SegmentationManager>,
-) {
+async fn seed_speakers_from_db(db: &Arc<DatabaseManager>, seg_mgr: &Arc<SegmentationManager>) {
match db.get_named_speakers_with_centroids().await {
Ok(speakers) if !speakers.is_empty() => {
for (_db_id, name, centroid) in &speakers {
@@ -992,8 +989,7 @@ async fn run_meeting_speaker_constraint_loop(
let mut meeting_sub =
screenpipe_events::subscribe_to_event::<MeetingEventData>("meeting_started");
- let mut ended_sub =
- screenpipe_events::subscribe_to_event::<MeetingEventData>("meeting_ended");
+ let mut ended_sub = screenpipe_events::subscribe_to_event::<MeetingEventData>("meeting_ended");
info!("calendar-assisted speaker diarization: listening for meeting events");
diff --git a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
index 15431f7df..23694dfb3 100644
--- a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
+++ b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
@@ -204,7 +204,10 @@ pub async fn reconcile_untranscribed(
// Batch-delete orphan chunks (missing audio files)
if !orphan_chunk_ids.is_empty() {
- if let Err(e) = db.delete_audio_chunks_batch_queued(orphan_chunk_ids.clone()).await {
+ if let Err(e) = db
+ .delete_audio_chunks_batch_queued(orphan_chunk_ids.clone())
+ .await
+ {
warn!(
"reconciliation: failed to batch-delete {} orphan chunks: {}",
orphan_chunk_ids.len(),
@@ -309,7 +312,10 @@ pub async fn reconcile_untranscribed(
old_chunks.len()
);
let old_chunk_ids: Vec<i64> = old_chunks.iter().map(|c| c.id).collect();
- if let Err(e) = db.delete_audio_chunks_batch_queued(old_chunk_ids.clone()).await {
+ if let Err(e) = db
+ .delete_audio_chunks_batch_queued(old_chunk_ids.clone())
+ .await
+ {
warn!(
"reconciliation: failed to batch-delete {} silent chunks: {}",
old_chunks.len(),
diff --git a/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs b/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs
index 69e8e766e..d3e777a9a 100644
--- a/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs
+++ b/crates/screenpipe-audio/src/core/run_record_and_transcribe.rs
@@ -14,11 +14,7 @@ use anyhow::{anyhow, Result};
use tokio::sync::broadcast;
use tracing::{debug, error, info, warn};
-use crate::{
- core::update_device_capture_time,
- metrics::AudioPipelineMetrics,
- AudioInput,
-};
+use crate::{core::update_device_capture_time, metrics::AudioPipelineMetrics, AudioInput};
use super::AudioStream;
@@ -65,7 +61,15 @@ pub async fn run_record_and_transcribe(
&& !audio_stream.is_disconnected.load(Ordering::Relaxed)
{
while collected_audio.len() < max_samples && is_running.load(Ordering::Relaxed) {
- match recv_audio_chunk(&mut receiver, &audio_stream, &device_name, &metrics, &stream_start).await? {
+ match recv_audio_chunk(
+ &mut receiver,
+ &audio_stream,
+ &device_name,
+ &metrics,
+ &stream_start,
+ )
+ .await?
+ {
Some(chunk) => collected_audio.extend(chunk),
None => continue,
}
@@ -140,7 +144,9 @@ async fn recv_audio_chunk(
Err(_timeout) => {
// During startup grace period, tolerate timeouts while the OS
// stream initializes (ScreenCaptureKit may take a moment).
- if stream_start.elapsed().as_secs() < STREAM_STARTUP_GRACE_SECS + AUDIO_RECEIVE_TIMEOUT_SECS {
+ if stream_start.elapsed().as_secs()
+ < STREAM_STARTUP_GRACE_SECS + AUDIO_RECEIVE_TIMEOUT_SECS
+ {
debug!(
"no audio from {} for {}s during startup grace, continuing",
device_name, AUDIO_RECEIVE_TIMEOUT_SECS
diff --git a/crates/screenpipe-config/Cargo.toml b/crates/screenpipe-config/Cargo.toml
index c1144b76d..1cb531ed6 100644
--- a/crates/screenpipe-config/Cargo.toml
+++ b/crates/screenpipe-config/Cargo.toml
@@ -11,7 +11,6 @@ edition.workspace = true
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"
-tracing = { workspace = true }
dirs = "6"
specta = { version = "=2.0.0-rc.20", features = ["derive"], optional = true }
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index ed6f9fb87..1197eb6f4 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -214,9 +214,7 @@ impl PipePermissionsConfig {
}
/// Deserialize `permissions` field: accepts a string preset or a structured block.
-fn deserialize_permissions_field<'de, D>(
- deserializer: D,
-) -> Result<PipePermissionsConfig, D::Error>
+fn deserialize_permissions_field<'de, D>(deserializer: D) -> Result<PipePermissionsConfig, D::Error>
where
D: serde::Deserializer<'de>,
{
@@ -921,18 +919,16 @@ impl PipeManager {
.to_string_lossy()
.to_string();
match std::fs::read_to_string(&pipe_md) {
- Ok(content) => {
- match parse_frontmatter(&content) {
- Ok((mut config, body)) => {
- config.name = dir_name.clone();
- info!("loaded pipe: {}", dir_name);
- pipes.insert(dir_name, (config, body, content));
- }
- Err(e) => {
- warn!("pipe '{}': failed to parse pipe.md: {}", dir_name, e);
- }
+ Ok(content) => match parse_frontmatter(&content) {
+ Ok((mut config, body)) => {
+ config.name = dir_name.clone();
+ info!("loaded pipe: {}", dir_name);
+ pipes.insert(dir_name, (config, body, content));
}
- }
+ Err(e) => {
+ warn!("pipe '{}': failed to parse pipe.md: {}", dir_name, e);
+ }
+ },
Err(e) => warn!("pipe '{}': failed to read pipe.md: {}", dir_name, e),
}
}
@@ -1521,10 +1517,7 @@ impl PipeManager {
"",
None,
Some("timeout"),
- Some(&format!(
- "execution timed out after {}s",
- pipe_timeout
- )),
+ Some(&format!("execution timed out after {}s", pipe_timeout)),
)
.await;
}
@@ -1603,397 +1596,403 @@ impl PipeManager {
}
/// Inner implementation with retry depth tracking for preset fallback.
- fn run_pipe_with_trigger_inner<'a>(&'a self, name: &'a str, trigger: &'a str, retry_depth: usize) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<PipeRunLog>> + Send + 'a>> {
+ fn run_pipe_with_trigger_inner<'a>(
+ &'a self,
+ name: &'a str,
+ trigger: &'a str,
+ retry_depth: usize,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<PipeRunLog>> + Send + 'a>> {
Box::pin(async move {
- let (config, body, _raw) = {
- let pipes = self.pipes.lock().await;
- match pipes.get(name).cloned() {
- Some(v) => v,
- None => return Err(self.pipe_not_found_error(name)),
- }
- };
+ let (config, body, _raw) = {
+ let pipes = self.pipes.lock().await;
+ match pipes.get(name).cloned() {
+ Some(v) => v,
+ None => return Err(self.pipe_not_found_error(name)),
+ }
+ };
- let executor = self
- .executors
- .get(&config.agent)
- .ok_or_else(|| anyhow!("agent '{}' not available", config.agent))?
- .clone();
+ let executor = self
+ .executors
+ .get(&config.agent)
+ .ok_or_else(|| anyhow!("agent '{}' not available", config.agent))?
+ .clone();
- // Check agent is available
- if !executor.is_available() {
- return Err(anyhow!(
- "agent '{}' is not installed — run ensure_installed first",
- config.agent
- ));
- }
+ // Check agent is available
+ if !executor.is_available() {
+ return Err(anyhow!(
+ "agent '{}' is not installed — run ensure_installed first",
+ config.agent
+ ));
+ }
- // Mark as running
- {
- let mut running = self.running.lock().await;
- if running.contains_key(name) {
- return Err(anyhow!("pipe '{}' is already running", name));
+ // Mark as running
+ {
+ let mut running = self.running.lock().await;
+ if running.contains_key(name) {
+ return Err(anyhow!("pipe '{}' is already running", name));
+ }
+ // Placeholder handle; real PID comes via pid_tx channel
+ running.insert(name.to_string(), ExecutionHandle { pid: 0 });
}
- // Placeholder handle; real PID comes via pid_tx channel
- running.insert(name.to_string(), ExecutionHandle { pid: 0 });
- }
- let started_at = Utc::now();
- let pipe_dir = self.pipes_dir.join(name);
+ let started_at = Utc::now();
+ let pipe_dir = self.pipes_dir.join(name);
+
+ // Resolve preset → model/provider overrides (with fallback support)
+ let (
+ run_model,
+ run_provider,
+ run_provider_url,
+ run_api_key,
+ preset_prompt,
+ active_preset_id,
+ ) = if !config.preset.is_empty() {
+ // Pick the best available preset using circuit breaker
+ let (preset_id, _idx) = self
+ .fallback_registry
+ .pick_preset(&config.preset)
+ .ok_or_else(|| anyhow!("pipe '{}': no presets configured", name))?;
- // Resolve preset → model/provider overrides (with fallback support)
- let (
- run_model,
- run_provider,
- run_provider_url,
- run_api_key,
- preset_prompt,
- active_preset_id,
- ) = if !config.preset.is_empty() {
- // Pick the best available preset using circuit breaker
- let (preset_id, _idx) = self
- .fallback_registry
- .pick_preset(&config.preset)
- .ok_or_else(|| anyhow!("pipe '{}': no presets configured", name))?;
-
- match resolve_preset(&self.pipes_dir, preset_id) {
- Some(resolved) => {
- info!(
- "pipe '{}': using preset '{}' → model={}, provider={:?}{}",
- name,
- preset_id,
- resolved.model,
- resolved.provider,
- if _idx > 0 {
- format!(" (fallback #{})", _idx)
- } else {
- String::new()
- }
- );
- (
- resolved.model,
- resolved.provider,
- resolved.url,
- resolved.api_key,
- resolved.prompt,
- Some(preset_id.to_string()),
- )
- }
- None => {
- return Err(anyhow!(
- "pipe '{}': preset '{}' not found in settings — \
+ match resolve_preset(&self.pipes_dir, preset_id) {
+ Some(resolved) => {
+ info!(
+ "pipe '{}': using preset '{}' → model={}, provider={:?}{}",
+ name,
+ preset_id,
+ resolved.model,
+ resolved.provider,
+ if _idx > 0 {
+ format!(" (fallback #{})", _idx)
+ } else {
+ String::new()
+ }
+ );
+ (
+ resolved.model,
+ resolved.provider,
+ resolved.url,
+ resolved.api_key,
+ resolved.prompt,
+ Some(preset_id.to_string()),
+ )
+ }
+ None => {
+ return Err(anyhow!(
+ "pipe '{}': preset '{}' not found in settings — \
create the preset in Settings → AI or remove the \
'preset: {}' line from the pipe config",
- name,
- preset_id,
- preset_id
- ));
+ name,
+ preset_id,
+ preset_id
+ ));
+ }
}
- }
- } else {
- (
- config.model.clone(),
- config.provider.clone(),
- None,
- None,
- None,
- None,
- )
- };
+ } else {
+ (
+ config.model.clone(),
+ config.provider.clone(),
+ None,
+ None,
+ None,
+ None,
+ )
+ };
- // Create DB execution row
- let exec_id = if let Some(ref store) = self.store {
- match store
- .create_execution(name, trigger, &run_model, run_provider.as_deref())
- .await
- {
- Ok(id) => {
- // Track execution ID for stop API
- let mut exec_ids = self.running_execution_ids.lock().await;
- exec_ids.insert(name.to_string(), id);
- Some(id)
- }
- Err(e) => {
- warn!("failed to create execution row: {}", e);
- None
+ // Create DB execution row
+ let exec_id = if let Some(ref store) = self.store {
+ match store
+ .create_execution(name, trigger, &run_model, run_provider.as_deref())
+ .await
+ {
+ Ok(id) => {
+ // Track execution ID for stop API
+ let mut exec_ids = self.running_execution_ids.lock().await;
+ exec_ids.insert(name.to_string(), id);
+ Some(id)
+ }
+ Err(e) => {
+ warn!("failed to create execution row: {}", e);
+ None
+ }
}
- }
- } else {
- None
- };
+ } else {
+ None
+ };
- // Check if history/session continuation is enabled for this pipe
- let history_enabled = config
- .config
- .get("history")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ // Check if history/session continuation is enabled for this pipe
+ let history_enabled = config
+ .config
+ .get("history")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
- // Build prompt with context header
- let prompt = self.render_prompt(&config, &body, preset_prompt.as_deref());
+ // Build prompt with context header
+ let prompt = self.render_prompt(&config, &body, preset_prompt.as_deref());
- // Create a channel so the executor can report PID immediately
- let (pid_tx, pid_rx) = tokio::sync::oneshot::channel::<u32>();
+ // Create a channel so the executor can report PID immediately
+ let (pid_tx, pid_rx) = tokio::sync::oneshot::channel::<u32>();
- // Mark as running in DB
- if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
- let _ = store.set_execution_running(id, None).await;
- }
+ // Mark as running in DB
+ if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
+ let _ = store.set_execution_running(id, None).await;
+ }
- // Spawn PID watcher: when PID arrives, update running map + DB
- let running_ref = self.running.clone();
- let store_for_pid = self.store.clone();
- let name_for_pid = name.to_string();
- let exec_id_for_pid = exec_id;
- tokio::spawn(async move {
- if let Ok(pid) = pid_rx.await {
- // Update in-memory running map with real PID
- {
- let mut r = running_ref.lock().await;
- if let Some(handle) = r.get_mut(&name_for_pid) {
- handle.pid = pid;
+ // Spawn PID watcher: when PID arrives, update running map + DB
+ let running_ref = self.running.clone();
+ let store_for_pid = self.store.clone();
+ let name_for_pid = name.to_string();
+ let exec_id_for_pid = exec_id;
+ tokio::spawn(async move {
+ if let Ok(pid) = pid_rx.await {
+ // Update in-memory running map with real PID
+ {
+ let mut r = running_ref.lock().await;
+ if let Some(handle) = r.get_mut(&name_for_pid) {
+ handle.pid = pid;
+ }
+ }
+ // Update DB row with PID
+ if let (Some(ref store), Some(id)) = (&store_for_pid, exec_id_for_pid) {
+ let _ = store.set_execution_running(id, Some(pid)).await;
}
}
- // Update DB row with PID
- if let (Some(ref store), Some(id)) = (&store_for_pid, exec_id_for_pid) {
- let _ = store.set_execution_running(id, Some(pid)).await;
+ });
+
+ // Pre-configure pi with the pipe's provider so models.json has the
+ // right entry before the agent subprocess starts.
+ let mut pipe_token: Option<String> = None;
+ if config.agent == "pi" {
+ if let Err(e) = PiExecutor::ensure_pi_config(
+ None,
+ SCREENPIPE_API_URL,
+ run_provider.as_deref(),
+ Some(&run_model),
+ run_provider_url.as_deref(),
+ ) {
+ warn!("failed to pre-configure pi provider: {}", e);
}
- }
- });
- // Pre-configure pi with the pipe's provider so models.json has the
- // right entry before the agent subprocess starts.
- let mut pipe_token: Option<String> = None;
- if config.agent == "pi" {
- if let Err(e) = PiExecutor::ensure_pi_config(
- None,
- SCREENPIPE_API_URL,
- run_provider.as_deref(),
- Some(&run_model),
- run_provider_url.as_deref(),
- ) {
- warn!("failed to pre-configure pi provider: {}", e);
+ pipe_token = setup_pipe_permissions(
+ &self.pipes_dir.join(name),
+ &config,
+ self.token_registry.as_ref(),
+ )
+ .await;
}
- pipe_token = setup_pipe_permissions(
- &self.pipes_dir.join(name),
- &config,
- self.token_registry.as_ref(),
- )
- .await;
- }
-
- // Run with timeout + streaming
- let pipe_timeout = config.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS);
- let timeout_duration = std::time::Duration::from_secs(pipe_timeout);
+ // Run with timeout + streaming
+ let pipe_timeout = config.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS);
+ let timeout_duration = std::time::Duration::from_secs(pipe_timeout);
- let (line_tx, mut line_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
- let drain_pipe_name = name.to_string();
- let drain_exec_id = exec_id.unwrap_or(0);
- let drain_on_output = self.on_output_line.clone();
- tokio::spawn(async move {
- while let Some(line) = line_rx.recv().await {
+ let (line_tx, mut line_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
+ let drain_pipe_name = name.to_string();
+ let drain_exec_id = exec_id.unwrap_or(0);
+ let drain_on_output = self.on_output_line.clone();
+ tokio::spawn(async move {
+ while let Some(line) = line_rx.recv().await {
+ if let Some(ref cb) = drain_on_output {
+ cb(&drain_pipe_name, drain_exec_id, &line);
+ }
+ }
+ // Channel closed — pipe process exited. Emit a done sentinel.
if let Some(ref cb) = drain_on_output {
- cb(&drain_pipe_name, drain_exec_id, &line);
+ cb(&drain_pipe_name, drain_exec_id, r#"{"type":"pipe_done"}"#);
}
- }
- // Channel closed — pipe process exited. Emit a done sentinel.
- if let Some(ref cb) = drain_on_output {
- cb(&drain_pipe_name, drain_exec_id, r#"{"type":"pipe_done"}"#);
- }
- });
+ });
- let run_result = tokio::time::timeout(
- timeout_duration,
- executor.run_streaming(
- &prompt,
- &run_model,
- &pipe_dir,
- run_provider.as_deref(),
- run_provider_url.as_deref(),
- run_api_key.as_deref(),
- Some(pid_tx),
- line_tx,
- history_enabled,
- None, // manual run — gateway-side caching still applies
- ),
- )
- .await;
+ let run_result = tokio::time::timeout(
+ timeout_duration,
+ executor.run_streaming(
+ &prompt,
+ &run_model,
+ &pipe_dir,
+ run_provider.as_deref(),
+ run_provider_url.as_deref(),
+ run_api_key.as_deref(),
+ Some(pid_tx),
+ line_tx,
+ history_enabled,
+ None, // manual run — gateway-side caching still applies
+ ),
+ )
+ .await;
- // Remove from running
- let removed_handle = {
- let mut running = self.running.lock().await;
- running.remove(name)
- };
- {
- let mut exec_ids = self.running_execution_ids.lock().await;
- exec_ids.remove(name);
- }
+ // Remove from running
+ let removed_handle = {
+ let mut running = self.running.lock().await;
+ running.remove(name)
+ };
+ {
+ let mut exec_ids = self.running_execution_ids.lock().await;
+ exec_ids.remove(name);
+ }
- let finished_at = Utc::now();
- let _duration_ms = (finished_at - started_at).num_milliseconds();
+ let finished_at = Utc::now();
+ let _duration_ms = (finished_at - started_at).num_milliseconds();
- let log = match run_result {
- Ok(Ok(output)) => {
- // Normal completion
- let filtered_stdout = filter_ndjson_stdout(&output.stdout);
- let (error_type, error_message) = if !output.success {
- parse_error_type_from_output(&output.stderr, &filtered_stdout)
- } else {
- (None, None)
- };
+ let log = match run_result {
+ Ok(Ok(output)) => {
+ // Normal completion
+ let filtered_stdout = filter_ndjson_stdout(&output.stdout);
+ let (error_type, error_message) = if !output.success {
+ parse_error_type_from_output(&output.stderr, &filtered_stdout)
+ } else {
+ (None, None)
+ };
- let status = if output.success {
- "completed"
- } else {
- "failed"
- };
- if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
- let _ = store
- .finish_execution(
- id,
- status,
- &truncate_string(&filtered_stdout, 50_000),
- &truncate_string(&output.stderr, 10_000),
- None,
- error_type.as_deref(),
- error_message.as_deref(),
- )
- .await;
- }
- if let Some(ref store) = self.store {
- let _ = store.upsert_scheduler_state(name, output.success).await;
- }
+ let status = if output.success {
+ "completed"
+ } else {
+ "failed"
+ };
+ if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
+ let _ = store
+ .finish_execution(
+ id,
+ status,
+ &truncate_string(&filtered_stdout, 50_000),
+ &truncate_string(&output.stderr, 10_000),
+ None,
+ error_type.as_deref(),
+ error_message.as_deref(),
+ )
+ .await;
+ }
+ if let Some(ref store) = self.store {
+ let _ = store.upsert_scheduler_state(name, output.success).await;
+ }
- // Update circuit breaker state
- if let Some(ref pid) = active_preset_id {
- if output.success {
- self.fallback_registry.record_success(pid);
- } else if config.preset.len() > 1 {
- // Only record failure for fallback if multiple presets configured
- self.fallback_registry.record_failure_from_output(
- pid,
- &output.stderr,
- &filtered_stdout,
- );
+ // Update circuit breaker state
+ if let Some(ref pid) = active_preset_id {
+ if output.success {
+ self.fallback_registry.record_success(pid);
+ } else if config.preset.len() > 1 {
+ // Only record failure for fallback if multiple presets configured
+ self.fallback_registry.record_failure_from_output(
+ pid,
+ &output.stderr,
+ &filtered_stdout,
+ );
+ }
}
- }
- PipeRunLog {
- pipe_name: name.to_string(),
- started_at,
- finished_at,
- success: output.success,
- stdout: truncate_string(&filtered_stdout, 10_000),
- stderr: truncate_string(&output.stderr, 5_000),
- }
- }
- Ok(Err(e)) => {
- // Executor error (not timeout)
- if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
- let _ = store
- .finish_execution(
- id,
- "failed",
- "",
- &e.to_string(),
- None,
- Some("crash"),
- Some(&e.to_string()),
- )
- .await;
- }
- if let Some(ref store) = self.store {
- let _ = store.upsert_scheduler_state(name, false).await;
+ PipeRunLog {
+ pipe_name: name.to_string(),
+ started_at,
+ finished_at,
+ success: output.success,
+ stdout: truncate_string(&filtered_stdout, 10_000),
+ stderr: truncate_string(&output.stderr, 5_000),
+ }
}
+ Ok(Err(e)) => {
+ // Executor error (not timeout)
+ if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
+ let _ = store
+ .finish_execution(
+ id,
+ "failed",
+ "",
+ &e.to_string(),
+ None,
+ Some("crash"),
+ Some(&e.to_string()),
+ )
+ .await;
+ }
+ if let Some(ref store) = self.store {
+ let _ = store.upsert_scheduler_state(name, false).await;
+ }
- PipeRunLog {
- pipe_name: name.to_string(),
- started_at,
- finished_at,
- success: false,
- stdout: String::new(),
- stderr: e.to_string(),
+ PipeRunLog {
+ pipe_name: name.to_string(),
+ started_at,
+ finished_at,
+ success: false,
+ stdout: String::new(),
+ stderr: e.to_string(),
+ }
}
- }
- Err(_elapsed) => {
- // Timeout — kill the process
- warn!(
- "pipe '{}' timed out after {}s, killing process",
- name, pipe_timeout
- );
- if let Some(handle) = removed_handle {
- if handle.pid != 0 {
- if let Some(executor) = self.executors.get(&config.agent) {
- let _ = executor.kill(&handle);
+ Err(_elapsed) => {
+ // Timeout — kill the process
+ warn!(
+ "pipe '{}' timed out after {}s, killing process",
+ name, pipe_timeout
+ );
+ if let Some(handle) = removed_handle {
+ if handle.pid != 0 {
+ if let Some(executor) = self.executors.get(&config.agent) {
+ let _ = executor.kill(&handle);
+ }
}
}
- }
- if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
- let _ = store
- .finish_execution(
- id,
- "timed_out",
- "",
- "",
- None,
- Some("timeout"),
- Some(&format!(
- "execution timed out after {}s",
- pipe_timeout
- )),
- )
- .await;
- }
- if let Some(ref store) = self.store {
- let _ = store.upsert_scheduler_state(name, false).await;
- }
+ if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
+ let _ = store
+ .finish_execution(
+ id,
+ "timed_out",
+ "",
+ "",
+ None,
+ Some("timeout"),
+ Some(&format!("execution timed out after {}s", pipe_timeout)),
+ )
+ .await;
+ }
+ if let Some(ref store) = self.store {
+ let _ = store.upsert_scheduler_state(name, false).await;
+ }
- PipeRunLog {
- pipe_name: name.to_string(),
- started_at,
- finished_at,
- success: false,
- stdout: String::new(),
- stderr: format!("execution timed out after {}s", pipe_timeout),
+ PipeRunLog {
+ pipe_name: name.to_string(),
+ started_at,
+ finished_at,
+ success: false,
+ stdout: String::new(),
+ stderr: format!("execution timed out after {}s", pipe_timeout),
+ }
}
- }
- };
+ };
- // Clean up pipe token from server registry
- if let Some(ref token) = pipe_token {
- cleanup_pipe_token(token, self.token_registry.as_ref());
- }
+ // Clean up pipe token from server registry
+ if let Some(ref token) = pipe_token {
+ cleanup_pipe_token(token, self.token_registry.as_ref());
+ }
- // Immediate fallback retry: if the pipe failed with a retryable error
- // and there are fallback presets available, retry now instead of waiting
- // for the next scheduled run.
- if !log.success && config.preset.len() > 1 && retry_depth < config.preset.len() - 1 {
- // Check if the circuit breaker picked a different preset for retry
- if let Some((next_preset_id, _)) = self.fallback_registry.pick_preset(&config.preset) {
- let should_retry = match &active_preset_id {
- Some(current_id) => next_preset_id != current_id.as_str(),
- None => false,
- };
- if should_retry {
- info!(
+ // Immediate fallback retry: if the pipe failed with a retryable error
+ // and there are fallback presets available, retry now instead of waiting
+ // for the next scheduled run.
+ if !log.success && config.preset.len() > 1 && retry_depth < config.preset.len() - 1 {
+ // Check if the circuit breaker picked a different preset for retry
+ if let Some((next_preset_id, _)) =
+ self.fallback_registry.pick_preset(&config.preset)
+ {
+ let should_retry = match &active_preset_id {
+ Some(current_id) => next_preset_id != current_id.as_str(),
+ None => false,
+ };
+ if should_retry {
+ info!(
"pipe '{}': primary preset failed, immediately retrying with fallback '{}'",
name, next_preset_id
);
- // Save log of the failed attempt
- self.append_log(name, &log).await;
- let _ = self.write_log_to_disk(name, &log);
- // Retry with next preset
- return self.run_pipe_with_trigger_inner(name, trigger, retry_depth + 1).await;
+ // Save log of the failed attempt
+ self.append_log(name, &log).await;
+ let _ = self.write_log_to_disk(name, &log);
+ // Retry with next preset
+ return self
+ .run_pipe_with_trigger_inner(name, trigger, retry_depth + 1)
+ .await;
+ }
}
}
- }
- // Save log (in-memory + disk)
- self.append_log(name, &log).await;
- let _ = self.write_log_to_disk(name, &log);
+ // Save log (in-memory + disk)
+ self.append_log(name, &log).await;
+ let _ = self.write_log_to_disk(name, &log);
- Ok(log)
+ Ok(log)
}) // end Box::pin(async move { ... })
}
@@ -2128,7 +2127,9 @@ impl PipeManager {
if source_path.exists() {
// Canonicalize source for reliable same-path detection
- let source_canonical = source_path.canonicalize().unwrap_or_else(|_| source_path.to_path_buf());
+ let source_canonical = source_path
+ .canonicalize()
+ .unwrap_or_else(|_| source_path.to_path_buf());
// Local file or directory
if source_path.is_file() && source_path.extension().is_some_and(|e| e == "md") {
@@ -2151,7 +2152,9 @@ impl PipeManager {
let dest_dir = self.pipes_dir.join(&name);
let dest_file = dest_dir.join("pipe.md");
- let dest_canonical = dest_file.canonicalize().unwrap_or_else(|_| dest_file.clone());
+ let dest_canonical = dest_file
+ .canonicalize()
+ .unwrap_or_else(|_| dest_file.clone());
// Skip copy if source and destination are the same file — copying
// a file onto itself can truncate it to 0 bytes on some platforms.
@@ -2537,11 +2540,8 @@ impl PipeManager {
let pipe_dir = pipes_dir.join(name);
- let pipe_system_prompt = render_pipe_system_prompt(
- body,
- api_port,
- preset_prompt.as_deref(),
- );
+ let pipe_system_prompt =
+ render_pipe_system_prompt(body, api_port, preset_prompt.as_deref());
let prompt = render_prompt_with_port(
config,
body,
@@ -2750,10 +2750,7 @@ impl PipeManager {
)
}
Err(_elapsed) => {
- warn!(
- "pipe '{}' timed out after {}s",
- pipe_name, pipe_timeout
- );
+ warn!("pipe '{}' timed out after {}s", pipe_name, pipe_timeout);
if let Some(handle) = removed_handle {
if handle.pid != 0 {
let _ = crate::agents::pi::kill_process_group(handle.pid);
@@ -3049,11 +3046,7 @@ pub fn serialize_pipe(config: &PipeConfig, body: &str) -> Result<String> {
/// Contains the pipe body (instructions from pipe.md) and the preset system prompt.
/// These are identical across runs and across turns within a run, making them
/// ideal for Anthropic prompt caching (90% input cost reduction on cache hits).
-fn render_pipe_system_prompt(
- body: &str,
- api_port: u16,
- system_prompt: Option<&str>,
-) -> String {
+fn render_pipe_system_prompt(body: &str, api_port: u16, system_prompt: Option<&str>) -> String {
let os = std::env::consts::OS;
let mut sys = String::new();
diff --git a/crates/screenpipe-core/src/pipes/permissions.rs b/crates/screenpipe-core/src/pipes/permissions.rs
index 19074d523..178dd6c75 100644
--- a/crates/screenpipe-core/src/pipes/permissions.rs
+++ b/crates/screenpipe-core/src/pipes/permissions.rs
@@ -82,17 +82,23 @@ pub fn parse_rules(s: &str) -> Vec<PermissionRule> {
"api" => parse_bare_api(inner).into_iter().collect(),
"app" => inner
.split(',')
- .map(|s| PermissionRule::App { value: s.trim().to_lowercase() })
+ .map(|s| PermissionRule::App {
+ value: s.trim().to_lowercase(),
+ })
.filter(|r| !matches!(r, PermissionRule::App { value: s } if s.is_empty()))
.collect(),
"window" => inner
.split(',')
- .map(|s| PermissionRule::Window { value: s.trim().to_string() })
+ .map(|s| PermissionRule::Window {
+ value: s.trim().to_string(),
+ })
.filter(|r| !matches!(r, PermissionRule::Window { value: s } if s.is_empty()))
.collect(),
"content" => inner
.split(',')
- .map(|s| PermissionRule::Content { value: s.trim().to_lowercase() })
+ .map(|s| PermissionRule::Content {
+ value: s.trim().to_lowercase(),
+ })
.filter(|r| !matches!(r, PermissionRule::Content { value: s } if s.is_empty()))
.collect(),
_ => vec![], // Unknown type, ignore
@@ -192,8 +198,14 @@ impl PipePermissions {
/// Check if an HTTP request (method + path) is allowed.
pub fn is_endpoint_allowed(&self, method: &str, path: &str) -> bool {
// No endpoint restrictions → full access
- let has_api_rules = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::Api { .. }))
- || self.deny_rules.iter().any(|r| matches!(r, PermissionRule::Api { .. }))
+ let has_api_rules = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Api { .. }))
+ || self
+ .deny_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Api { .. }))
|| self.use_default_allowlist;
if !has_api_rules {
return true;
@@ -203,7 +215,11 @@ impl PipePermissions {
// Deny wins
for rule in &self.deny_rules {
- if let PermissionRule::Api { method: rm, path: rp } = rule {
+ if let PermissionRule::Api {
+ method: rm,
+ path: rp,
+ } = rule
+ {
if (rm == "*" || rm == &m) && glob_match(rp, path) {
return false;
}
@@ -212,7 +228,11 @@ impl PipePermissions {
// Explicit allow
for rule in &self.allow_rules {
- if let PermissionRule::Api { method: rm, path: rp } = rule {
+ if let PermissionRule::Api {
+ method: rm,
+ path: rp,
+ } = rule
+ {
if (rm == "*" || rm == &m) && glob_match(rp, path) {
return true;
}
@@ -223,7 +243,11 @@ impl PipePermissions {
if self.use_default_allowlist {
for pattern in DEFAULT_ALLOWED_ENDPOINTS {
if let Some(rule) = parse_bare_api(pattern) {
- if let PermissionRule::Api { method: rm, path: rp } = &rule {
+ if let PermissionRule::Api {
+ method: rm,
+ path: rp,
+ } = &rule
+ {
if (rm == "*" || rm == &m) && glob_match(rp, path) {
return true;
}
@@ -237,8 +261,14 @@ impl PipePermissions {
/// Check if an app name is allowed.
pub fn is_app_allowed(&self, app_name: &str) -> bool {
- let has_app_rules = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::App { .. }))
- || self.deny_rules.iter().any(|r| matches!(r, PermissionRule::App { .. }));
+ let has_app_rules = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::App { .. }))
+ || self
+ .deny_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::App { .. }));
if !has_app_rules {
return true;
}
@@ -255,7 +285,10 @@ impl PipePermissions {
}
// Explicit allow
- let has_allows = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::App { .. }));
+ let has_allows = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::App { .. }));
if !has_allows {
return true; // No allow rules = allow all (only deny rules active)
}
@@ -271,8 +304,14 @@ impl PipePermissions {
/// Check if a window title is allowed (glob matching).
pub fn is_window_allowed(&self, window_title: &str) -> bool {
- let has_window_rules = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::Window { .. }))
- || self.deny_rules.iter().any(|r| matches!(r, PermissionRule::Window { .. }));
+ let has_window_rules = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Window { .. }))
+ || self
+ .deny_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Window { .. }));
if !has_window_rules {
return true;
}
@@ -289,7 +328,10 @@ impl PipePermissions {
}
// Explicit allow
- let has_allows = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::Window { .. }));
+ let has_allows = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Window { .. }));
if !has_allows {
return true;
}
@@ -305,8 +347,14 @@ impl PipePermissions {
/// Check if a content type is allowed.
pub fn is_content_type_allowed(&self, content_type: &str) -> bool {
- let has_content_rules = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::Content { .. }))
- || self.deny_rules.iter().any(|r| matches!(r, PermissionRule::Content { .. }));
+ let has_content_rules = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Content { .. }))
+ || self
+ .deny_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Content { .. }));
if !has_content_rules {
return true;
}
@@ -321,7 +369,10 @@ impl PipePermissions {
}
// Explicit allow
- let has_allows = self.allow_rules.iter().any(|r| matches!(r, PermissionRule::Content { .. }));
+ let has_allows = self
+ .allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Content { .. }));
if !has_allows {
return true;
}
@@ -398,7 +449,13 @@ impl PipePermissions {
fn resolve_rules(
config: &PipePermissionsConfig,
-) -> (Vec<PermissionRule>, Vec<PermissionRule>, bool, Option<String>, Option<String>) {
+) -> (
+ Vec<PermissionRule>,
+ Vec<PermissionRule>,
+ bool,
+ Option<String>,
+ Option<String>,
+) {
match config {
PipePermissionsConfig::Preset(preset) => {
match preset.to_lowercase().as_str() {
@@ -431,17 +488,30 @@ fn resolve_rules(
_ => (vec![], vec![], false, None, None),
}
}
- PipePermissionsConfig::Rules { allow, deny, time, days } => {
+ PipePermissionsConfig::Rules {
+ allow,
+ deny,
+ time,
+ days,
+ } => {
let allow_rules: Vec<PermissionRule> =
allow.iter().flat_map(|s| parse_rules(s)).collect();
let deny_rules: Vec<PermissionRule> =
deny.iter().flat_map(|s| parse_rules(s)).collect();
// If explicit allow has Api rules, don't layer on defaults
- let has_api_allows = allow_rules.iter().any(|r| matches!(r, PermissionRule::Api { .. }));
+ let has_api_allows = allow_rules
+ .iter()
+ .any(|r| matches!(r, PermissionRule::Api { .. }));
let use_defaults = !has_api_allows;
- (allow_rules, deny_rules, use_defaults, time.clone(), days.clone())
+ (
+ allow_rules,
+ deny_rules,
+ use_defaults,
+ time.clone(),
+ days.clone(),
+ )
}
}
}
@@ -549,7 +619,9 @@ mod tests {
fn parse_api_rule() {
let rules = parse_rules("Api(GET /search)");
assert_eq!(rules.len(), 1);
- assert!(matches!(&rules[0], PermissionRule::Api { method, path } if method == "GET" && path == "/search"));
+ assert!(
+ matches!(&rules[0], PermissionRule::Api { method, path } if method == "GET" && path == "/search")
+ );
}
#[test]
@@ -587,7 +659,9 @@ mod tests {
fn parse_bare_api_pattern() {
let rules = parse_rules("GET /meetings/*");
assert_eq!(rules.len(), 1);
- assert!(matches!(&rules[0], PermissionRule::Api { method, path } if method == "GET" && path == "/meetings/*"));
+ assert!(
+ matches!(&rules[0], PermissionRule::Api { method, path } if method == "GET" && path == "/meetings/*")
+ );
}
#[test]
@@ -640,8 +714,12 @@ mod tests {
fn app_allow_restricts() {
let mut p = make_perms();
p.allow_rules = vec![
- PermissionRule::App { value: "slack".to_string() },
- PermissionRule::App { value: "chrome".to_string() },
+ PermissionRule::App {
+ value: "slack".to_string(),
+ },
+ PermissionRule::App {
+ value: "chrome".to_string(),
+ },
];
assert!(p.is_app_allowed("Slack"));
assert!(p.is_app_allowed("Chrome"));
@@ -651,15 +729,21 @@ mod tests {
#[test]
fn app_deny_wins() {
let mut p = make_perms();
- p.allow_rules = vec![PermissionRule::App { value: "slack".to_string() }];
- p.deny_rules = vec![PermissionRule::App { value: "slack".to_string() }];
+ p.allow_rules = vec![PermissionRule::App {
+ value: "slack".to_string(),
+ }];
+ p.deny_rules = vec![PermissionRule::App {
+ value: "slack".to_string(),
+ }];
assert!(!p.is_app_allowed("Slack"));
}
#[test]
fn app_deny_only_allows_others() {
let mut p = make_perms();
- p.deny_rules = vec![PermissionRule::App { value: "1password".to_string() }];
+ p.deny_rules = vec![PermissionRule::App {
+ value: "1password".to_string(),
+ }];
assert!(p.is_app_allowed("Slack"));
assert!(!p.is_app_allowed("1Password"));
}
@@ -670,8 +754,12 @@ mod tests {
fn window_deny_glob() {
let mut p = make_perms();
p.deny_rules = vec![
- PermissionRule::Window { value: "*incognito*".to_string() },
- PermissionRule::Window { value: "*bank*".to_string() },
+ PermissionRule::Window {
+ value: "*incognito*".to_string(),
+ },
+ PermissionRule::Window {
+ value: "*bank*".to_string(),
+ },
];
assert!(p.is_window_allowed("Slack - General"));
assert!(!p.is_window_allowed("Chrome - Incognito"));
@@ -681,7 +769,9 @@ mod tests {
#[test]
fn window_allow_restricts() {
let mut p = make_perms();
- p.allow_rules = vec![PermissionRule::Window { value: "*meeting*".to_string() }];
+ p.allow_rules = vec![PermissionRule::Window {
+ value: "*meeting*".to_string(),
+ }];
assert!(p.is_window_allowed("Zoom Meeting"));
assert!(!p.is_window_allowed("Slack - General"));
}
@@ -692,8 +782,12 @@ mod tests {
fn content_allow_restricts() {
let mut p = make_perms();
p.allow_rules = vec![
- PermissionRule::Content { value: "ocr".to_string() },
- PermissionRule::Content { value: "audio".to_string() },
+ PermissionRule::Content {
+ value: "ocr".to_string(),
+ },
+ PermissionRule::Content {
+ value: "audio".to_string(),
+ },
];
assert!(p.is_content_type_allowed("ocr"));
assert!(p.is_content_type_allowed("audio"));
@@ -704,10 +798,16 @@ mod tests {
fn content_deny_wins() {
let mut p = make_perms();
p.allow_rules = vec![
- PermissionRule::Content { value: "ocr".to_string() },
- PermissionRule::Content { value: "input".to_string() },
+ PermissionRule::Content {
+ value: "ocr".to_string(),
+ },
+ PermissionRule::Content {
+ value: "input".to_string(),
+ },
];
- p.deny_rules = vec![PermissionRule::Content { value: "input".to_string() }];
+ p.deny_rules = vec![PermissionRule::Content {
+ value: "input".to_string(),
+ }];
assert!(p.is_content_type_allowed("ocr"));
assert!(!p.is_content_type_allowed("input"));
}
diff --git a/crates/screenpipe-db/Cargo.toml b/crates/screenpipe-db/Cargo.toml
index b1d6c1030..39c63805d 100644
--- a/crates/screenpipe-db/Cargo.toml
+++ b/crates/screenpipe-db/Cargo.toml
@@ -34,7 +34,6 @@ oasgen = { workspace = true }
tracing-subscriber = { workspace = true }
regex = "1.11"
once_cell = "1.19"
-dirs = "5"
[[bench]]
name = "db_benchmarks"
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 8af66b244..6e76f4c6a 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -523,16 +523,20 @@ impl DatabaseManager {
device_name: &str,
) -> Result<i64, sqlx::Error> {
use crate::write_queue::{WriteOp, WriteResult};
- match self.write_queue.submit(WriteOp::SyncInsertFrame {
- sync_id: sync_id.to_string(),
- machine_id: machine_id.to_string(),
- timestamp: timestamp.to_string(),
- offset_index,
- app_name: app_name.map(|s| s.to_string()),
- window_name: window_name.map(|s| s.to_string()),
- browser_url: browser_url.map(|s| s.to_string()),
- device_name: device_name.to_string(),
- }).await? {
+ match self
+ .write_queue
+ .submit(WriteOp::SyncInsertFrame {
+ sync_id: sync_id.to_string(),
+ machine_id: machine_id.to_string(),
+ timestamp: timestamp.to_string(),
+ offset_index,
+ app_name: app_name.map(|s| s.to_string()),
+ window_name: window_name.map(|s| s.to_string()),
+ browser_url: browser_url.map(|s| s.to_string()),
+ device_name: device_name.to_string(),
+ })
+ .await?
+ {
WriteResult::Id(id) => Ok(id),
_ => Ok(0),
}
@@ -549,14 +553,16 @@ impl DatabaseManager {
sync_id: &str,
) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
- self.write_queue.submit(WriteOp::SyncInsertOcr {
- frame_id,
- text: text.to_string(),
- focused,
- app_name: app_name.to_string(),
- window_name: window_name.map(|s| s.to_string()),
- sync_id: sync_id.to_string(),
- }).await?;
+ self.write_queue
+ .submit(WriteOp::SyncInsertOcr {
+ frame_id,
+ text: text.to_string(),
+ focused,
+ app_name: app_name.to_string(),
+ window_name: window_name.map(|s| s.to_string()),
+ sync_id: sync_id.to_string(),
+ })
+ .await?;
Ok(())
}
@@ -572,15 +578,19 @@ impl DatabaseManager {
speaker_id: Option<i64>,
) -> Result<i64, sqlx::Error> {
use crate::write_queue::{WriteOp, WriteResult};
- match self.write_queue.submit(WriteOp::SyncInsertTranscription {
- sync_id: sync_id.to_string(),
- machine_id: machine_id.to_string(),
- timestamp: timestamp.to_string(),
- transcription: transcription.to_string(),
- device: device.to_string(),
- is_input_device,
- speaker_id,
- }).await? {
+ match self
+ .write_queue
+ .submit(WriteOp::SyncInsertTranscription {
+ sync_id: sync_id.to_string(),
+ machine_id: machine_id.to_string(),
+ timestamp: timestamp.to_string(),
+ transcription: transcription.to_string(),
+ device: device.to_string(),
+ is_input_device,
+ speaker_id,
+ })
+ .await?
+ {
WriteResult::Id(id) => Ok(id),
_ => Ok(0),
}
@@ -598,15 +608,17 @@ impl DatabaseManager {
text_content: &str,
) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
- self.write_queue.submit(WriteOp::SyncInsertAccessibility {
- sync_id: sync_id.to_string(),
- machine_id: machine_id.to_string(),
- timestamp: timestamp.to_string(),
- app_name: app_name.to_string(),
- window_name: window_name.to_string(),
- browser_url: browser_url.map(|s| s.to_string()),
- text_content: text_content.to_string(),
- }).await?;
+ self.write_queue
+ .submit(WriteOp::SyncInsertAccessibility {
+ sync_id: sync_id.to_string(),
+ machine_id: machine_id.to_string(),
+ timestamp: timestamp.to_string(),
+ app_name: app_name.to_string(),
+ window_name: window_name.to_string(),
+ browser_url: browser_url.map(|s| s.to_string()),
+ text_content: text_content.to_string(),
+ })
+ .await?;
Ok(())
}
@@ -643,49 +655,62 @@ impl DatabaseManager {
frame_id: Option<i64>,
) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
- self.write_queue.submit(WriteOp::SyncInsertUiEvent {
- sync_id: sync_id.to_string(),
- machine_id: machine_id.to_string(),
- timestamp: timestamp.to_string(),
- event_type: event_type.to_string(),
- app_name: app_name.map(|s| s.to_string()),
- window_title: window_title.map(|s| s.to_string()),
- browser_url: browser_url.map(|s| s.to_string()),
- text_content: text_content.map(|s| s.to_string()),
- x,
- y,
- key_code,
- modifiers,
- element_role: element_role.map(|s| s.to_string()),
- element_name: element_name.map(|s| s.to_string()),
- session_id: session_id.map(|s| s.to_string()),
- relative_ms,
- delta_x,
- delta_y,
- button,
- click_count,
- text_length,
- app_pid,
- element_value: element_value.map(|s| s.to_string()),
- element_description: element_description.map(|s| s.to_string()),
- element_automation_id: element_automation_id.map(|s| s.to_string()),
- element_bounds: element_bounds.map(|s| s.to_string()),
- frame_id,
- }).await?;
+ self.write_queue
+ .submit(WriteOp::SyncInsertUiEvent {
+ sync_id: sync_id.to_string(),
+ machine_id: machine_id.to_string(),
+ timestamp: timestamp.to_string(),
+ event_type: event_type.to_string(),
+ app_name: app_name.map(|s| s.to_string()),
+ window_title: window_title.map(|s| s.to_string()),
+ browser_url: browser_url.map(|s| s.to_string()),
+ text_content: text_content.map(|s| s.to_string()),
+ x,
+ y,
+ key_code,
+ modifiers,
+ element_role: element_role.map(|s| s.to_string()),
+ element_name: element_name.map(|s| s.to_string()),
+ session_id: session_id.map(|s| s.to_string()),
+ relative_ms,
+ delta_x,
+ delta_y,
+ button,
+ click_count,
+ text_length,
+ app_pid,
+ element_value: element_value.map(|s| s.to_string()),
+ element_description: element_description.map(|s| s.to_string()),
+ element_automation_id: element_automation_id.map(|s| s.to_string()),
+ element_bounds: element_bounds.map(|s| s.to_string()),
+ frame_id,
+ })
+ .await?;
Ok(())
}
/// Compact snapshots via the write coalescing queue.
- pub async fn compact_snapshots_queued(&self, chunk_id: i64, batch: Vec<(i64, u32)>) -> Result<(), sqlx::Error> {
+ pub async fn compact_snapshots_queued(
+ &self,
+ chunk_id: i64,
+ batch: Vec<(i64, u32)>,
+ ) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
- self.write_queue.submit(WriteOp::CompactSnapshots { chunk_id, batch }).await?;
+ self.write_queue
+ .submit(WriteOp::CompactSnapshots { chunk_id, batch })
+ .await?;
Ok(())
}
/// Clear snapshot_path for frames with missing JPEG files, via write queue.
- pub async fn clear_snapshot_paths_queued(&self, frame_ids: Vec<i64>) -> Result<(), sqlx::Error> {
+ pub async fn clear_snapshot_paths_queued(
+ &self,
+ frame_ids: Vec<i64>,
+ ) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
- self.write_queue.submit(WriteOp::ClearSnapshotPaths { frame_ids }).await?;
+ self.write_queue
+ .submit(WriteOp::ClearSnapshotPaths { frame_ids })
+ .await?;
Ok(())
}
@@ -732,7 +757,10 @@ impl DatabaseManager {
}
/// Delete old pipe executions via the write queue.
- pub async fn pipe_delete_old_executions_queued(&self, keep_per_pipe: i32) -> Result<(), sqlx::Error> {
+ pub async fn pipe_delete_old_executions_queued(
+ &self,
+ keep_per_pipe: i32,
+ ) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
self.write_queue
.submit(WriteOp::PipeDeleteOldExecutions { keep_per_pipe })
@@ -741,9 +769,14 @@ impl DatabaseManager {
}
/// Delete audio chunks in batch via the write coalescing queue.
- pub async fn delete_audio_chunks_batch_queued(&self, chunk_ids: Vec<i64>) -> Result<(), sqlx::Error> {
+ pub async fn delete_audio_chunks_batch_queued(
+ &self,
+ chunk_ids: Vec<i64>,
+ ) -> Result<(), sqlx::Error> {
use crate::write_queue::WriteOp;
- self.write_queue.submit(WriteOp::DeleteAudioChunksBatch { chunk_ids }).await?;
+ self.write_queue
+ .submit(WriteOp::DeleteAudioChunksBatch { chunk_ids })
+ .await?;
Ok(())
}
@@ -1868,23 +1901,65 @@ impl DatabaseManager {
// Serialize automation properties as JSON (only non-None fields)
let properties = {
let mut props = serde_json::Map::new();
- if let Some(ref v) = node.automation_id { props.insert("automation_id".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.class_name { props.insert("class_name".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.value { props.insert("value".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.help_text { props.insert("help_text".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.url { props.insert("url".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.placeholder { props.insert("placeholder".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.role_description { props.insert("role_description".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.subrole { props.insert("subrole".into(), serde_json::Value::String(v.clone())); }
- if let Some(v) = node.is_enabled { props.insert("is_enabled".into(), serde_json::Value::Bool(v)); }
- if let Some(v) = node.is_focused { props.insert("is_focused".into(), serde_json::Value::Bool(v)); }
- if let Some(v) = node.is_selected { props.insert("is_selected".into(), serde_json::Value::Bool(v)); }
- if let Some(v) = node.is_expanded { props.insert("is_expanded".into(), serde_json::Value::Bool(v)); }
- if let Some(v) = node.is_password { props.insert("is_password".into(), serde_json::Value::Bool(v)); }
- if let Some(v) = node.is_keyboard_focusable { props.insert("is_keyboard_focusable".into(), serde_json::Value::Bool(v)); }
- if let Some(ref v) = node.accelerator_key { props.insert("accelerator_key".into(), serde_json::Value::String(v.clone())); }
- if let Some(ref v) = node.access_key { props.insert("access_key".into(), serde_json::Value::String(v.clone())); }
- if props.is_empty() { None } else { Some(serde_json::Value::Object(props).to_string()) }
+ if let Some(ref v) = node.automation_id {
+ props.insert("automation_id".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(ref v) = node.class_name {
+ props.insert("class_name".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(ref v) = node.value {
+ props.insert("value".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(ref v) = node.help_text {
+ props.insert("help_text".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(ref v) = node.url {
+ props.insert("url".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(ref v) = node.placeholder {
+ props.insert("placeholder".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(ref v) = node.role_description {
+ props.insert(
+ "role_description".into(),
+ serde_json::Value::String(v.clone()),
+ );
+ }
+ if let Some(ref v) = node.subrole {
+ props.insert("subrole".into(), serde_json::Value::String(v.clone()));
+ }
+ if let Some(v) = node.is_enabled {
+ props.insert("is_enabled".into(), serde_json::Value::Bool(v));
+ }
+ if let Some(v) = node.is_focused {
+ props.insert("is_focused".into(), serde_json::Value::Bool(v));
+ }
+ if let Some(v) = node.is_selected {
+ props.insert("is_selected".into(), serde_json::Value::Bool(v));
+ }
+ if let Some(v) = node.is_expanded {
+ props.insert("is_expanded".into(), serde_json::Value::Bool(v));
+ }
+ if let Some(v) = node.is_password {
+ props.insert("is_password".into(), serde_json::Value::Bool(v));
+ }
+ if let Some(v) = node.is_keyboard_focusable {
+ props.insert("is_keyboard_focusable".into(), serde_json::Value::Bool(v));
+ }
+ if let Some(ref v) = node.accelerator_key {
+ props.insert(
+ "accelerator_key".into(),
+ serde_json::Value::String(v.clone()),
+ );
+ }
+ if let Some(ref v) = node.access_key {
+ props.insert("access_key".into(), serde_json::Value::String(v.clone()));
+ }
+ if props.is_empty() {
+ None
+ } else {
+ Some(serde_json::Value::Object(props).to_string())
+ }
};
let result = sqlx::query_scalar::<_, i64>(
@@ -2010,8 +2085,12 @@ impl DatabaseManager {
// Submit element inserts as a separate write op so they don't hold
// the write lock during the frame transaction. Elements are supplementary
// data — the frame is usable for search immediately after the first commit.
- let has_elements = ocr_json_for_elements.as_ref().is_some_and(|j| !j.is_empty())
- || a11y_json_for_elements.as_ref().is_some_and(|j| !j.is_empty());
+ let has_elements = ocr_json_for_elements
+ .as_ref()
+ .is_some_and(|j| !j.is_empty())
+ || a11y_json_for_elements
+ .as_ref()
+ .is_some_and(|j| !j.is_empty());
if has_elements {
// Fire-and-forget: spawn so we don't block the capture loop waiting
// for element insertion. Errors are logged inside insert_*_elements.
@@ -4301,12 +4380,10 @@ impl DatabaseManager {
.execute(&mut **tx.conn())
.await?;
// Clear ref on the new anchor (it now owns the elements)
- sqlx::query(
- "UPDATE frames SET elements_ref_frame_id = NULL WHERE id = ?1",
- )
- .bind(new_id)
- .execute(&mut **tx.conn())
- .await?;
+ sqlx::query("UPDATE frames SET elements_ref_frame_id = NULL WHERE id = ?1")
+ .bind(new_id)
+ .execute(&mut **tx.conn())
+ .await?;
}
}
@@ -5793,32 +5870,36 @@ LIMIT ? OFFSET ?
pub async fn insert_ui_event(&self, event: &InsertUiEvent) -> Result<i64, sqlx::Error> {
use crate::write_queue::{WriteOp, WriteResult};
let text_length = event.text_content.as_ref().map(|s| s.len() as i32);
- let result = self.write_queue.submit(WriteOp::InsertUiEvent {
- timestamp: event.timestamp.to_string(),
- session_id: event.session_id.clone(),
- relative_ms: event.relative_ms,
- event_type: event.event_type.to_string(),
- x: event.x, y: event.y,
- delta_x: event.delta_x.map(|v| v as i32),
- delta_y: event.delta_y.map(|v| v as i32),
- button: event.button.map(|v| v as i32),
- click_count: event.click_count.map(|v| v as i32),
- key_code: event.key_code.map(|v| v as i32),
- modifiers: event.modifiers.map(|v| v as i32),
- text_content: event.text_content.clone(),
- text_length,
- app_name: event.app_name.clone(),
- app_pid: event.app_pid,
- window_title: event.window_title.clone(),
- browser_url: event.browser_url.clone(),
- element_role: event.element_role.clone(),
- element_name: event.element_name.clone(),
- element_value: event.element_value.clone(),
- element_description: event.element_description.clone(),
- element_automation_id: event.element_automation_id.clone(),
- element_bounds: event.element_bounds.clone(),
- frame_id: event.frame_id,
- }).await?;
+ let result = self
+ .write_queue
+ .submit(WriteOp::InsertUiEvent {
+ timestamp: event.timestamp.to_string(),
+ session_id: event.session_id.clone(),
+ relative_ms: event.relative_ms,
+ event_type: event.event_type.to_string(),
+ x: event.x,
+ y: event.y,
+ delta_x: event.delta_x.map(|v| v as i32),
+ delta_y: event.delta_y.map(|v| v as i32),
+ button: event.button.map(|v| v as i32),
+ click_count: event.click_count.map(|v| v as i32),
+ key_code: event.key_code.map(|v| v as i32),
+ modifiers: event.modifiers.map(|v| v as i32),
+ text_content: event.text_content.clone(),
+ text_length,
+ app_name: event.app_name.clone(),
+ app_pid: event.app_pid,
+ window_title: event.window_title.clone(),
+ browser_url: event.browser_url.clone(),
+ element_role: event.element_role.clone(),
+ element_name: event.element_name.clone(),
+ element_value: event.element_value.clone(),
+ element_description: event.element_description.clone(),
+ element_automation_id: event.element_automation_id.clone(),
+ element_bounds: event.element_bounds.clone(),
+ frame_id: event.frame_id,
+ })
+ .await?;
match result {
WriteResult::Id(id) => Ok(id),
_ => unreachable!(),
@@ -5826,8 +5907,13 @@ LIMIT ? OFFSET ?
}
/// Insert multiple UI events via the write coalescing queue.
- pub async fn insert_ui_events_batch(&self, events: &[InsertUiEvent]) -> Result<usize, sqlx::Error> {
- if events.is_empty() { return Ok(0); }
+ pub async fn insert_ui_events_batch(
+ &self,
+ events: &[InsertUiEvent],
+ ) -> Result<usize, sqlx::Error> {
+ if events.is_empty() {
+ return Ok(0);
+ }
let mut count = 0;
for event in events {
self.insert_ui_event(event).await?;
@@ -6019,11 +6105,9 @@ LIMIT ? OFFSET ?
}
pub async fn has_active_meeting(&self) -> Result<bool, SqlxError> {
- let row: (i64,) = sqlx::query_as(
- "SELECT COUNT(*) FROM meetings WHERE meeting_end IS NULL",
- )
- .fetch_one(&self.pool)
- .await?;
+ let row: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM meetings WHERE meeting_end IS NULL")
+ .fetch_one(&self.pool)
+ .await?;
Ok(row.0 > 0)
}
diff --git a/crates/screenpipe-db/src/types.rs b/crates/screenpipe-db/src/types.rs
index 7ac3ce0a0..a5bb51db1 100644
--- a/crates/screenpipe-db/src/types.rs
+++ b/crates/screenpipe-db/src/types.rs
@@ -784,4 +784,3 @@ mod tests {
);
}
}
-
diff --git a/crates/screenpipe-db/src/write_queue.rs b/crates/screenpipe-db/src/write_queue.rs
index 5723bd929..bb668378c 100644
--- a/crates/screenpipe-db/src/write_queue.rs
+++ b/crates/screenpipe-db/src/write_queue.rs
@@ -728,13 +728,16 @@ async fn execute_single_write(
} => {
if let Some(ref text_json) = ocr_text_json {
if !text_json.is_empty() {
- crate::db::DatabaseManager::insert_ocr_elements(conn, *frame_id, text_json).await;
+ crate::db::DatabaseManager::insert_ocr_elements(conn, *frame_id, text_json)
+ .await;
}
}
if let Some(ref tree_json) = accessibility_tree_json {
if !tree_json.is_empty() {
- crate::db::DatabaseManager::insert_accessibility_elements(conn, *frame_id, tree_json)
- .await;
+ crate::db::DatabaseManager::insert_accessibility_elements(
+ conn, *frame_id, tree_json,
+ )
+ .await;
}
}
Ok(WriteResult::Unit)
@@ -787,11 +790,31 @@ async fn execute_single_write(
}
WriteOp::InsertUiEvent {
- timestamp, session_id, relative_ms, event_type,
- x, y, delta_x, delta_y, button, click_count, key_code, modifiers,
- text_content, text_length, app_name, app_pid, window_title, browser_url,
- element_role, element_name, element_value, element_description,
- element_automation_id, element_bounds, frame_id,
+ timestamp,
+ session_id,
+ relative_ms,
+ event_type,
+ x,
+ y,
+ delta_x,
+ delta_y,
+ button,
+ click_count,
+ key_code,
+ modifiers,
+ text_content,
+ text_length,
+ app_name,
+ app_pid,
+ window_title,
+ browser_url,
+ element_role,
+ element_name,
+ element_value,
+ element_description,
+ element_automation_id,
+ element_bounds,
+ frame_id,
} => {
let result = sqlx::query(
"INSERT INTO ui_events (timestamp, session_id, relative_ms, event_type, x, y, delta_x, delta_y, button, click_count, key_code, modifiers, text_content, text_length, app_name, app_pid, window_title, browser_url, element_role, element_name, element_value, element_description, element_automation_id, element_bounds, frame_id) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25)",
@@ -811,16 +834,26 @@ async fn execute_single_write(
WriteOp::DeleteAudioChunksBatch { chunk_ids } => {
for id in chunk_ids {
sqlx::query("DELETE FROM audio_transcriptions WHERE audio_chunk_id = ?1")
- .bind(id).execute(&mut **conn).await?;
+ .bind(id)
+ .execute(&mut **conn)
+ .await?;
sqlx::query("DELETE FROM audio_chunks WHERE id = ?1")
- .bind(id).execute(&mut **conn).await?;
+ .bind(id)
+ .execute(&mut **conn)
+ .await?;
}
Ok(WriteResult::Unit)
}
WriteOp::SyncInsertFrame {
- sync_id, machine_id, timestamp, offset_index,
- app_name, window_name, browser_url, device_name,
+ sync_id,
+ machine_id,
+ timestamp,
+ offset_index,
+ app_name,
+ window_name,
+ browser_url,
+ device_name,
} => {
// Create a virtual video_chunk for this synced frame
let video_chunk_id: Option<i64> = sqlx::query_scalar(
@@ -863,7 +896,12 @@ async fn execute_single_write(
}
WriteOp::SyncInsertOcr {
- frame_id, text, focused, app_name, window_name, sync_id,
+ frame_id,
+ text,
+ focused,
+ app_name,
+ window_name,
+ sync_id,
} => {
let now = Utc::now().to_rfc3339();
sqlx::query(
@@ -883,8 +921,13 @@ async fn execute_single_write(
}
WriteOp::SyncInsertTranscription {
- sync_id, machine_id, timestamp, transcription, device,
- is_input_device, speaker_id,
+ sync_id,
+ machine_id,
+ timestamp,
+ transcription,
+ device,
+ is_input_device,
+ speaker_id,
} => {
let now = Utc::now().to_rfc3339();
// Create audio chunk for synced transcription
@@ -917,8 +960,13 @@ async fn execute_single_write(
}
WriteOp::SyncInsertAccessibility {
- sync_id, machine_id, timestamp, app_name, window_name,
- browser_url, text_content,
+ sync_id,
+ machine_id,
+ timestamp,
+ app_name,
+ window_name,
+ browser_url,
+ text_content,
} => {
let now = Utc::now().to_rfc3339();
let id = sqlx::query(
@@ -940,12 +988,33 @@ async fn execute_single_write(
}
WriteOp::SyncInsertUiEvent {
- sync_id, machine_id, timestamp, event_type,
- app_name, window_title, browser_url, text_content,
- x, y, key_code, modifiers, element_role, element_name,
- session_id, relative_ms, delta_x, delta_y, button, click_count,
- text_length, app_pid, element_value, element_description,
- element_automation_id, element_bounds, frame_id,
+ sync_id,
+ machine_id,
+ timestamp,
+ event_type,
+ app_name,
+ window_title,
+ browser_url,
+ text_content,
+ x,
+ y,
+ key_code,
+ modifiers,
+ element_role,
+ element_name,
+ session_id,
+ relative_ms,
+ delta_x,
+ delta_y,
+ button,
+ click_count,
+ text_length,
+ app_pid,
+ element_value,
+ element_description,
+ element_automation_id,
+ element_bounds,
+ frame_id,
} => {
let now = Utc::now().to_rfc3339();
let id = sqlx::query(
@@ -1040,7 +1109,12 @@ async fn execute_single_write(
// Dual-write: insert OCR elements into unified elements table
if !window.text_json.is_empty() {
- crate::db::DatabaseManager::insert_ocr_elements(conn, frame_id, &window.text_json).await;
+ crate::db::DatabaseManager::insert_ocr_elements(
+ conn,
+ frame_id,
+ &window.text_json,
+ )
+ .await;
}
results.push((frame_id, idx));
@@ -1049,34 +1123,50 @@ async fn execute_single_write(
}
WriteOp::CompactSnapshots { chunk_id, batch } => {
- if batch.is_empty() { return Ok(WriteResult::Unit); }
+ if batch.is_empty() {
+ return Ok(WriteResult::Unit);
+ }
let placeholders: Vec<String> = batch.iter().map(|_| "?".to_string()).collect();
- let case_clauses: Vec<String> = batch.iter()
- .map(|(id, pos)| format!("WHEN {} THEN {}", id, pos)).collect();
+ let case_clauses: Vec<String> = batch
+ .iter()
+ .map(|(id, pos)| format!("WHEN {} THEN {}", id, pos))
+ .collect();
let sql = format!(
"UPDATE frames SET video_chunk_id = ?1, offset_index = CASE id {} ELSE offset_index END, snapshot_path = NULL WHERE id IN ({}) AND snapshot_path IS NOT NULL",
case_clauses.join(" "), placeholders.join(",")
);
let mut query = sqlx::query(&sql).bind(chunk_id);
- for (id, _) in batch { query = query.bind(id); }
+ for (id, _) in batch {
+ query = query.bind(id);
+ }
query.execute(&mut **conn).await?;
Ok(WriteResult::Unit)
}
WriteOp::ClearSnapshotPaths { frame_ids } => {
- if frame_ids.is_empty() { return Ok(WriteResult::Unit); }
+ if frame_ids.is_empty() {
+ return Ok(WriteResult::Unit);
+ }
let placeholders: Vec<&str> = frame_ids.iter().map(|_| "?").collect();
let sql = format!(
"UPDATE frames SET snapshot_path = NULL WHERE id IN ({})",
placeholders.join(",")
);
let mut query = sqlx::query(&sql);
- for id in frame_ids { query = query.bind(id); }
+ for id in frame_ids {
+ query = query.bind(id);
+ }
query.execute(&mut **conn).await?;
Ok(WriteResult::Unit)
}
- WriteOp::PipeCreateExecution { pipe_name, trigger_type, model, provider, started_at } => {
+ WriteOp::PipeCreateExecution {
+ pipe_name,
+ trigger_type,
+ model,
+ provider,
+ started_at,
+ } => {
let row = sqlx::query_scalar::<_, i64>(
r#"INSERT INTO pipe_executions (pipe_name, status, trigger_type, model, provider, started_at)
VALUES (?, 'queued', ?, ?, ?, ?)
@@ -1096,12 +1186,24 @@ async fn execute_single_write(
let mut query = sqlx::query(&sql);
for bind in binds {
match bind {
- PipeBindValue::Text(v) => { query = query.bind(v); }
- PipeBindValue::OptText(v) => { query = query.bind(v); }
- PipeBindValue::Int(v) => { query = query.bind(v); }
- PipeBindValue::OptInt(v) => { query = query.bind(v); }
- PipeBindValue::Int32(v) => { query = query.bind(v); }
- PipeBindValue::OptInt32(v) => { query = query.bind(v); }
+ PipeBindValue::Text(v) => {
+ query = query.bind(v);
+ }
+ PipeBindValue::OptText(v) => {
+ query = query.bind(v);
+ }
+ PipeBindValue::Int(v) => {
+ query = query.bind(v);
+ }
+ PipeBindValue::OptInt(v) => {
+ query = query.bind(v);
+ }
+ PipeBindValue::Int32(v) => {
+ query = query.bind(v);
+ }
+ PipeBindValue::OptInt32(v) => {
+ query = query.bind(v);
+ }
}
}
query.execute(&mut **conn).await?;
diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
index 660d6ffa2..5623924f8 100644
--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
@@ -27,8 +27,8 @@ use screenpipe_engine::{
Cli, CliAudioTranscriptionEngine, Command,
},
hot_frame_cache::HotFrameCache,
- start_meeting_watcher, start_power_manager, start_sleep_monitor,
- start_speaker_identification, start_ui_recording,
+ start_meeting_watcher, start_power_manager, start_sleep_monitor, start_speaker_identification,
+ start_ui_recording,
vision_manager::{start_monitor_watcher, stop_monitor_watcher, VisionManager},
watch_pid, ResourceMonitor, SCServer,
};
diff --git a/crates/screenpipe-engine/src/calendar_speaker_id.rs b/crates/screenpipe-engine/src/calendar_speaker_id.rs
index 35e2a68a1..b07403a0f 100644
--- a/crates/screenpipe-engine/src/calendar_speaker_id.rs
+++ b/crates/screenpipe-engine/src/calendar_speaker_id.rs
@@ -1020,9 +1020,9 @@ mod tests {
None,
);
let observations = vec![
- speaker(1, "", true, 5), // unnamed input → Rule 1 names as Alice
- speaker(2, "Bob Jones", false, 10), // already named
- speaker(3, "", false, 5), // unnamed output
+ speaker(1, "", true, 5), // unnamed input → Rule 1 names as Alice
+ speaker(2, "Bob Jones", false, 10), // already named
+ speaker(3, "", false, 5), // unnamed output
];
let decisions = decide_speaker_names(&context, &observations);
diff --git a/crates/screenpipe-engine/src/cli/login.rs b/crates/screenpipe-engine/src/cli/login.rs
index 84ee40225..4a88cc3d1 100644
--- a/crates/screenpipe-engine/src/cli/login.rs
+++ b/crates/screenpipe-engine/src/cli/login.rs
@@ -48,10 +48,7 @@ pub async fn handle_login_command() -> anyhow::Result<()> {
// The redirect param is no longer used for localhost callback,
// but we keep it so the website knows this is a CLI login flow
- let login_url = format!(
- "{}/login?code={}&redirect=cli",
- base, code
- );
+ let login_url = format!("{}/login?code={}&redirect=cli", base, code);
println!();
println!(" opening browser to log in...");
diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rs
index 74a062ec8..86ab92401 100644
--- a/crates/screenpipe-engine/src/connections_api.rs
+++ b/crates/screenpipe-engine/src/connections_api.rs
@@ -72,10 +72,9 @@ async fn list_connections(State(state): State<ConnectionsState>) -> Json<Value>
let mut data = serde_json::to_value(&list).unwrap_or(json!([]));
if let Some(arr) = data.as_array_mut() {
// Native calendar (macOS / Windows)
- let cal_available =
- tokio::task::spawn_blocking(is_native_calendar_available)
- .await
- .unwrap_or(false);
+ let cal_available = tokio::task::spawn_blocking(is_native_calendar_available)
+ .await
+ .unwrap_or(false);
arr.push(json!({
"id": "calendar",
"name": "Calendar",
@@ -215,9 +214,7 @@ pub struct CalendarEventsQuery {
}
/// GET /connections/calendar/events — fetch native OS calendar events.
-async fn calendar_events(
- Query(params): Query<CalendarEventsQuery>,
-) -> (StatusCode, Json<Value>) {
+async fn calendar_events(Query(params): Query<CalendarEventsQuery>) -> (StatusCode, Json<Value>) {
let hours_back = params.hours_back.unwrap_or(1);
let hours_ahead = params.hours_ahead.unwrap_or(8);
@@ -238,10 +235,9 @@ async fn calendar_events(
/// GET /connections/calendar/status — check native calendar access.
async fn calendar_status() -> Json<Value> {
- let available =
- tokio::task::spawn_blocking(is_native_calendar_available)
- .await
- .unwrap_or(false);
+ let available = tokio::task::spawn_blocking(is_native_calendar_available)
+ .await
+ .unwrap_or(false);
Json(json!({ "available": available, "platform": std::env::consts::OS }))
}
@@ -249,7 +245,9 @@ async fn calendar_status() -> Json<Value> {
fn get_native_calendar_events(hours_back: i64, hours_ahead: i64) -> Result<Vec<Value>, String> {
use screenpipe_connect::calendar::ScreenpipeCalendar;
let cal = ScreenpipeCalendar::new();
- let events = cal.get_events(hours_back, hours_ahead).map_err(|e| format!("{:?}", e))?;
+ let events = cal
+ .get_events(hours_back, hours_ahead)
+ .map_err(|e| format!("{:?}", e))?;
Ok(events
.into_iter()
.map(|e| {
diff --git a/crates/screenpipe-engine/src/event_driven_capture.rs b/crates/screenpipe-engine/src/event_driven_capture.rs
index 0d10bf961..c34b99ee5 100644
--- a/crates/screenpipe-engine/src/event_driven_capture.rs
+++ b/crates/screenpipe-engine/src/event_driven_capture.rs
@@ -412,7 +412,8 @@ pub async fn event_driven_capture_loop(
// for this device, reference that frame's elements instead of
// inserting duplicate element rows.
let elements_ref = if let Some(hash) = last_content_hash {
- if let Some(&(prev_frame_id, prev_hash)) = last_elements_cache.get(&device_name) {
+ if let Some(&(prev_frame_id, prev_hash)) = last_elements_cache.get(&device_name)
+ {
if hash == prev_hash && hash != 0 {
Some(prev_frame_id)
} else {
@@ -476,10 +477,8 @@ pub async fn event_driven_capture_loop(
// (not when we referenced another frame's elements)
if !output.elements_deduped {
if let Some(hash) = result.content_hash {
- last_elements_cache.insert(
- device_name.clone(),
- (result.frame_id, hash),
- );
+ last_elements_cache
+ .insert(device_name.clone(), (result.frame_id, hash));
}
}
@@ -544,8 +543,7 @@ pub async fn event_driven_capture_loop(
// protocol, permission denied, etc.) while still
// recovering quickly from transient errors.
if consecutive_capture_errors >= 3 {
- let backoff_secs = (consecutive_capture_errors as u64 / 3)
- .min(30); // cap at 30s
+ let backoff_secs = (consecutive_capture_errors as u64 / 3).min(30); // cap at 30s
tokio::time::sleep(Duration::from_secs(backoff_secs)).await;
}
}
diff --git a/crates/screenpipe-engine/src/meeting_detector.rs b/crates/screenpipe-engine/src/meeting_detector.rs
index 7d4b1a55d..80662db72 100644
--- a/crates/screenpipe-engine/src/meeting_detector.rs
+++ b/crates/screenpipe-engine/src/meeting_detector.rs
@@ -67,9 +67,7 @@ pub enum CallSignal {
/// Match a menu bar item by exact title (case-insensitive).
/// Used for apps like Zoom that expose meeting controls only via
/// AXMenuBarItem/AXMenuItem in the menu bar, not as AXButton in windows.
- MenuBarItem {
- title_contains: &'static str,
- },
+ MenuBarItem { title_contains: &'static str },
/// Match an AXMenuItem by its automation ID (AXIdentifier).
/// Zoom exposes identifiers like "onMuteAudio:", "onMuteVideo:" on menu items.
MenuItemId(&'static str),
@@ -496,8 +494,14 @@ impl MeetingUiScanner {
// Walk this window's AX tree looking for signals
walk_for_signals(
- window, &precomputed, 0, max_depth, &start, scan_timeout,
- &mut found, min_required,
+ window,
+ &precomputed,
+ 0,
+ max_depth,
+ &start,
+ scan_timeout,
+ &mut found,
+ min_required,
);
if found.len() >= min_required {
@@ -655,7 +659,8 @@ fn walk_for_signals(
desc_lower.as_deref(),
ident_lower.as_deref(),
) {
- let label = format_signal_match(&ps.signal, &role_str, title.as_deref(), desc.as_deref());
+ let label =
+ format_signal_match(&ps.signal, &role_str, title.as_deref(), desc.as_deref());
if !found.contains(&label) {
found.push(label);
}
@@ -686,7 +691,14 @@ fn walk_for_signals(
}
let child = &children[i];
walk_for_signals(
- child, signals, depth + 1, max_depth, start, timeout, found, min_required,
+ child,
+ signals,
+ depth + 1,
+ max_depth,
+ start,
+ timeout,
+ found,
+ min_required,
);
}
}
@@ -736,7 +748,9 @@ fn check_signal_match(
identifier: Option<&str>,
) -> bool {
match signal {
- CallSignal::AutomationId(id) => identifier.map_or(false, |ident| ident.eq_ignore_ascii_case(id)),
+ CallSignal::AutomationId(id) => {
+ identifier.map_or(false, |ident| ident.eq_ignore_ascii_case(id))
+ }
CallSignal::AutomationIdContains(substr) => identifier.map_or(false, |ident| {
ident.to_lowercase().contains(&substr.to_lowercase())
}),
@@ -945,7 +959,11 @@ fn windows_enumerate_processes() -> Vec<WindowsProcessInfo> {
if Process32FirstW(snapshot, &mut entry).is_ok() {
loop {
let name = String::from_utf16_lossy(
- &entry.szExeFile[..entry.szExeFile.iter().position(|&c| c == 0).unwrap_or(entry.szExeFile.len())]
+ &entry.szExeFile[..entry
+ .szExeFile
+ .iter()
+ .position(|&c| c == 0)
+ .unwrap_or(entry.szExeFile.len())],
);
results.push(WindowsProcessInfo {
pid: entry.th32ProcessID,
@@ -976,11 +994,11 @@ fn windows_get_process_name(pid: i32) -> Option<String> {
/// Enumerate visible window titles and their PIDs on Windows.
#[cfg(target_os = "windows")]
fn windows_enumerate_window_titles() -> Vec<(i32, String)> {
+ use std::sync::Mutex;
+ use windows::Win32::Foundation::{BOOL, HWND, LPARAM};
use windows::Win32::UI::WindowsAndMessaging::{
EnumWindows, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible,
};
- use windows::Win32::Foundation::{BOOL, HWND, LPARAM};
- use std::sync::Mutex;
let results: Arc<Mutex<Vec<(i32, String)>>> = Arc::new(Mutex::new(Vec::new()));
let results_clone = results.clone();
@@ -1010,23 +1028,25 @@ fn windows_enumerate_window_titles() -> Vec<(i32, String)> {
);
}
- Arc::try_unwrap(results).unwrap_or_default().into_inner().unwrap_or_default()
+ Arc::try_unwrap(results)
+ .unwrap_or_default()
+ .into_inner()
+ .unwrap_or_default()
}
/// Enumerate visible windows belonging to a specific PID.
#[cfg(target_os = "windows")]
fn enumerate_windows_for_pid(target_pid: u32) -> Vec<windows::Win32::Foundation::HWND> {
+ use std::sync::Mutex;
+ use windows::Win32::Foundation::{BOOL, HWND, LPARAM};
use windows::Win32::UI::WindowsAndMessaging::{
EnumWindows, GetWindowThreadProcessId, IsWindowVisible,
};
- use windows::Win32::Foundation::{BOOL, HWND, LPARAM};
- use std::sync::Mutex;
let param_data = (target_pid, Mutex::new(Vec::<HWND>::new()));
unsafe extern "system" fn enum_for_pid(hwnd: HWND, lparam: LPARAM) -> BOOL {
- let (target_pid, hwnds) =
- &*(lparam.0 as *const (u32, Mutex<Vec<HWND>>));
+ let (target_pid, hwnds) = &*(lparam.0 as *const (u32, Mutex<Vec<HWND>>));
if IsWindowVisible(hwnd).as_bool() {
let mut win_pid: u32 = 0;
@@ -1068,7 +1088,7 @@ fn windows_scan_process_uia(
};
use windows::Win32::UI::Accessibility::{
CUIAutomation, IUIAutomation, IUIAutomationCondition, TreeScope_Descendants,
- UIA_NamePropertyId, UIA_AutomationIdPropertyId,
+ UIA_AutomationIdPropertyId, UIA_NamePropertyId,
};
unsafe {
@@ -1090,7 +1110,11 @@ fn windows_scan_process_uia(
conditions.push(cond);
}
}
- CallSignal::NameContains(name) | CallSignal::RoleWithName { name_contains: name, .. } => {
+ CallSignal::NameContains(name)
+ | CallSignal::RoleWithName {
+ name_contains: name,
+ ..
+ } => {
// UIA PropertyCondition doesn't support substring match,
// so we search for exact name. For "leave"/"hang up" this works
// because the button name IS the keyword.
@@ -1129,9 +1153,7 @@ fn windows_scan_process_uia(
// Build OR condition from all individual conditions
let first: IUIAutomationCondition = conditions[0].clone().into();
let second: IUIAutomationCondition = conditions[1].clone().into();
- let mut combined = automation
- .CreateOrCondition(&first, &second)
- .ok();
+ let mut combined = automation.CreateOrCondition(&first, &second).ok();
for cond in &conditions[2..] {
if let Some(ref prev) = combined {
let prev_cond: IUIAutomationCondition = prev.clone().into();
@@ -1154,18 +1176,26 @@ fn windows_scan_process_uia(
if let Ok(el) = results.GetElement(i) {
let name = el.CurrentName().ok().map(|s| s.to_string());
let auto_id = el.CurrentAutomationId().ok().map(|s| s.to_string());
- let role = el.CurrentLocalizedControlType()
- .ok().map(|s| s.to_string()).unwrap_or_default();
+ let role = el
+ .CurrentLocalizedControlType()
+ .ok()
+ .map(|s| s.to_string())
+ .unwrap_or_default();
// Verify this element actually matches one of our signals
for signal in signals {
if check_signal_match(
- signal, &role,
- name.as_deref(), None,
+ signal,
+ &role,
+ name.as_deref(),
+ None,
auto_id.as_deref(),
) {
let label = format_signal_match(
- signal, &role, name.as_deref(), None,
+ signal,
+ &role,
+ name.as_deref(),
+ None,
);
if !found.contains(&label) {
found.push(label);
@@ -1175,12 +1205,17 @@ fn windows_scan_process_uia(
// Also check with AX prefix for cross-platform compat
let ax_role = format!("AX{}", role);
if check_signal_match(
- signal, &ax_role,
- name.as_deref(), None,
+ signal,
+ &ax_role,
+ name.as_deref(),
+ None,
auto_id.as_deref(),
) {
let label = format_signal_match(
- signal, &role, name.as_deref(), None,
+ signal,
+ &role,
+ name.as_deref(),
+ None,
);
if !found.contains(&label) {
found.push(label);
@@ -1404,7 +1439,8 @@ pub fn advance_state(
} else {
debug!(
"meeting v2: Ending (app={}, id={}, elapsed={:?})",
- app, meeting_id,
+ app,
+ meeting_id,
since.elapsed()
);
(
@@ -1531,10 +1567,7 @@ pub fn find_running_meeting_apps(
if !profile.app_identifiers.browser_url_patterns.is_empty()
&& BROWSER_NAMES.iter().any(|b| name_lower.contains(b))
{
- if has_browser_meeting_url(
- pid,
- &profile.app_identifiers.browser_url_patterns,
- ) {
+ if has_browser_meeting_url(pid, &profile.app_identifiers.browser_url_patterns) {
results.push(RunningMeetingApp {
pid,
app_name: name.clone(),
@@ -1610,14 +1643,12 @@ pub fn find_running_meeting_apps(
profiles: &[MeetingDetectionProfile],
currently_tracking: Option<&ActiveTracking>,
) -> Vec<RunningMeetingApp> {
- use windows::Win32::System::Threading::{
- OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
- };
+ use std::collections::{HashMap, HashSet};
+ use windows::Win32::Foundation::{BOOL, HWND, LPARAM};
+ use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};
use windows::Win32::UI::WindowsAndMessaging::{
EnumWindows, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible,
};
- use windows::Win32::Foundation::{BOOL, HWND, LPARAM};
- use std::collections::{HashMap, HashSet};
let mut results = Vec::new();
let mut seen_pids = HashSet::new();
@@ -1630,7 +1661,8 @@ pub fn find_running_meeting_apps(
if process_map.iter().any(|p| p.pid == tracking.pid as u32) {
results.push(RunningMeetingApp {
pid: tracking.pid,
- app_name: process_map.iter()
+ app_name: process_map
+ .iter()
.find(|p| p.pid == tracking.pid as u32)
.map(|p| p.name.clone())
.unwrap_or_else(|| format!("pid:{}", tracking.pid)),
@@ -1664,14 +1696,13 @@ pub fn find_running_meeting_apps(
// Also add child processes that render UI (Teams uses msedgewebview2.exe).
// Only include known UI-hosting children to avoid scanning 10-15+ GPU/utility
// worker processes that would each block for 2s+ on timeout.
- const UI_CHILD_PROCESS_NAMES: &[&str] = &[
- "msedgewebview2.exe",
- "webview2.exe",
- ];
+ const UI_CHILD_PROCESS_NAMES: &[&str] = &["msedgewebview2.exe", "webview2.exe"];
for child in process_map.iter() {
if child.parent_pid == proc.pid
&& !seen_pids.contains(&(child.pid as i32))
- && UI_CHILD_PROCESS_NAMES.iter().any(|n| child.name.eq_ignore_ascii_case(n))
+ && UI_CHILD_PROCESS_NAMES
+ .iter()
+ .any(|n| child.name.eq_ignore_ascii_case(n))
{
results.push(RunningMeetingApp {
pid: child.pid as i32,
@@ -1690,8 +1721,13 @@ pub fn find_running_meeting_apps(
let window_titles = windows_enumerate_window_titles();
let browser_process_names: &[&str] = &[
- "chrome.exe", "msedge.exe", "firefox.exe", "brave.exe",
- "arc.exe", "opera.exe", "vivaldi.exe",
+ "chrome.exe",
+ "msedge.exe",
+ "firefox.exe",
+ "brave.exe",
+ "arc.exe",
+ "opera.exe",
+ "vivaldi.exe",
];
for (idx, profile) in profiles.iter().enumerate() {
@@ -1705,20 +1741,24 @@ pub fn find_running_meeting_apps(
}
// Check if this is a browser process
- let proc_name = process_map.iter()
+ let proc_name = process_map
+ .iter()
.find(|p| p.pid == *pid as u32)
.map(|p| p.name.to_lowercase());
- let is_browser = proc_name.as_ref().map_or(false, |n| {
- browser_process_names.iter().any(|b| n == *b)
- });
+ let is_browser = proc_name
+ .as_ref()
+ .map_or(false, |n| browser_process_names.iter().any(|b| n == *b));
if !is_browser {
continue;
}
let title_lower = title.to_lowercase();
- if profile.app_identifiers.browser_url_patterns.iter().any(|p| {
- title_lower.contains(&p.to_lowercase())
- }) {
+ if profile
+ .app_identifiers
+ .browser_url_patterns
+ .iter()
+ .any(|p| title_lower.contains(&p.to_lowercase()))
+ {
results.push(RunningMeetingApp {
pid: *pid,
app_name: proc_name.unwrap_or_default(),
@@ -1776,7 +1816,7 @@ async fn db_find_browser_meetings(
let rows: Vec<(String, String)> = sqlx::query_as(
"SELECT DISTINCT app_name, window_name FROM frames \
WHERE timestamp > datetime('now', '-30 seconds') \
- AND app_name IS NOT NULL AND window_name IS NOT NULL"
+ AND app_name IS NOT NULL AND window_name IS NOT NULL",
)
.fetch_all(&db.pool)
.await?;
@@ -1788,7 +1828,10 @@ async fn db_find_browser_meetings(
if profile.app_identifiers.browser_url_patterns.is_empty() {
continue;
}
- let matches = profile.app_identifiers.browser_url_patterns.iter()
+ let matches = profile
+ .app_identifiers
+ .browser_url_patterns
+ .iter()
.any(|p| window_lower.contains(&p.to_lowercase()));
if matches {
#[cfg(target_os = "macos")]
@@ -1808,7 +1851,10 @@ async fn db_find_browser_meetings(
#[cfg(not(target_os = "macos"))]
let pid = -1i32;
if pid > 0 {
- debug!("meeting v2: DB hint — {} window {:?} matches profile {}", app_name, window_name, idx);
+ debug!(
+ "meeting v2: DB hint — {} window {:?} matches profile {}",
+ app_name, window_name, idx
+ );
results.push(RunningMeetingApp {
pid,
app_name: app_name.clone(),
@@ -1925,7 +1971,10 @@ pub async fn run_meeting_detection_loop(
// Merge DB browser hints (avoids missing meetings when AX doesn't expose URLs)
for hint in db_browser_hints {
- if !running_apps.iter().any(|a| a.profile_index == hint.profile_index) {
+ if !running_apps
+ .iter()
+ .any(|a| a.profile_index == hint.profile_index)
+ {
running_apps.push(hint);
}
}
@@ -1934,7 +1983,10 @@ pub async fn run_meeting_detection_loop(
debug!(
"meeting v2: found {} running meeting app(s): {:?}",
running_apps.len(),
- running_apps.iter().map(|a| format!("{}(pid={})", a.app_name, a.pid)).collect::<Vec<_>>()
+ running_apps
+ .iter()
+ .map(|a| format!("{}(pid={})", a.app_name, a.pid))
+ .collect::<Vec<_>>()
);
}
@@ -1943,9 +1995,7 @@ pub async fn run_meeting_detection_loop(
let (new_state, ended_id) = handle_no_apps_running(state);
state = new_state;
if let Some(meeting_id) = ended_id {
- let now = Utc::now()
- .format("%Y-%m-%dT%H:%M:%S%.3fZ")
- .to_string();
+ let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
if let Err(e) = db.end_meeting(meeting_id, &now).await {
error!("meeting v2: failed to end meeting {}: {}", meeting_id, e);
}
@@ -2009,7 +2059,7 @@ pub async fn run_meeting_detection_loop(
idle_scan_count = 0; // reset idle counter when apps are present
current_interval = match &state {
MeetingState::Idle => IDLE_APPS_SCAN_INTERVAL, // apps open but no call
- _ => base_interval, // Confirming/Active/Ending — scan fast
+ _ => base_interval, // Confirming/Active/Ending — scan fast
};
// 4. Handle actions
@@ -2027,19 +2077,13 @@ pub async fn run_meeting_detection_loop(
recent.id
}
Err(e) => {
- warn!(
- "meeting v2: failed to reopen meeting {}: {}",
- recent.id, e
- );
+ warn!("meeting v2: failed to reopen meeting {}: {}", recent.id, e);
insert_new_meeting(&db, &app).await
}
},
Ok(None) => insert_new_meeting(&db, &app).await,
Err(e) => {
- warn!(
- "meeting v2: failed to find recent meeting: {}",
- e
- );
+ warn!("meeting v2: failed to find recent meeting: {}", e);
insert_new_meeting(&db, &app).await
}
};
@@ -2066,18 +2110,13 @@ pub async fn run_meeting_detection_loop(
}
StateAction::EndMeeting { meeting_id } => {
if meeting_id >= 0 {
- let now = Utc::now()
- .format("%Y-%m-%dT%H:%M:%S%.3fZ")
- .to_string();
+ let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
match db.end_meeting(meeting_id, &now).await {
Ok(()) => {
info!("meeting v2: meeting ended (id={})", meeting_id);
}
Err(e) => {
- error!(
- "meeting v2: failed to end meeting {}: {}",
- meeting_id, e
- );
+ error!("meeting v2: failed to end meeting {}: {}", meeting_id, e);
}
}
}
@@ -2249,9 +2288,7 @@ mod tests {
CallSignal::RoleWithName { name_contains, .. } => {
!name_contains.to_lowercase().contains("mute")
}
- CallSignal::AutomationIdContains(s) => {
- !s.to_lowercase().contains("mute")
- }
+ CallSignal::AutomationIdContains(s) => !s.to_lowercase().contains("mute"),
_ => true,
});
assert!(
@@ -2388,9 +2425,7 @@ mod tests {
let mute_matches: Vec<_> = profile
.call_signals
.iter()
- .filter(|s| {
- check_signal_match(s, "AXButton", Some("Mute"), None, None)
- })
+ .filter(|s| check_signal_match(s, "AXButton", Some("Mute"), None, None))
.collect();
// If mute is a signal, verify that other non-mute signals also exist
// (so a lobby with only Mute won't trigger detection)
@@ -2505,10 +2540,7 @@ mod tests {
assert!(matches!(
new_state,
- MeetingState::Active {
- meeting_id: 42,
- ..
- }
+ MeetingState::Active { meeting_id: 42, .. }
));
assert!(action.is_none());
}
@@ -2526,10 +2558,7 @@ mod tests {
assert!(matches!(
new_state,
- MeetingState::Ending {
- meeting_id: 42,
- ..
- }
+ MeetingState::Ending { meeting_id: 42, .. }
));
assert!(action.is_none());
}
@@ -2575,10 +2604,7 @@ mod tests {
assert!(matches!(
new_state,
- MeetingState::Active {
- meeting_id: 42,
- ..
- }
+ MeetingState::Active { meeting_id: 42, .. }
));
assert!(action.is_none());
}
@@ -2615,10 +2641,7 @@ mod tests {
assert!(matches!(
new_state,
- MeetingState::Ending {
- meeting_id: 42,
- ..
- }
+ MeetingState::Ending { meeting_id: 42, .. }
));
assert!(action.is_none());
}
@@ -2897,7 +2920,10 @@ mod tests {
.expect("Zoom profile not found");
let has_menu_bar = zoom.call_signals.iter().any(|s| {
- matches!(s, CallSignal::MenuBarItem { .. } | CallSignal::MenuItemId(_))
+ matches!(
+ s,
+ CallSignal::MenuBarItem { .. } | CallSignal::MenuItemId(_)
+ )
});
assert!(
has_menu_bar,
@@ -2945,7 +2971,10 @@ mod live_tests {
let apps = find_running_meeting_apps(&profiles, None);
println!("Found {} running meeting app(s)", apps.len());
for app in &apps {
- println!(" {} (pid={}, profile={})", app.app_name, app.pid, app.profile_index);
+ println!(
+ " {} (pid={}, profile={})",
+ app.app_name, app.pid, app.profile_index
+ );
}
if apps.is_empty() {
@@ -2956,7 +2985,10 @@ mod live_tests {
let running = workspace.running_apps();
for i in 0..running.len() {
let app = &running[i];
- let name = app.localized_name().map(|s| s.to_string()).unwrap_or_default();
+ let name = app
+ .localized_name()
+ .map(|s| s.to_string())
+ .unwrap_or_default();
let name_lower = name.to_lowercase();
if BROWSER_NAMES.iter().any(|b| name_lower.contains(b)) {
println!("\nBROWSER: {} (pid={})", name, app.pid());
@@ -2968,15 +3000,24 @@ mod live_tests {
for j in 0..children.len() {
let child = &children[j];
let _ = child.set_messaging_timeout_secs(0.5);
- if let Some(title) = get_ax_string_attr(child, cidre::ax::attr::title()) {
- let has_meet = title.to_lowercase().contains("google meet") || title.to_lowercase().contains("meet.google.com");
+ if let Some(title) =
+ get_ax_string_attr(child, cidre::ax::attr::title())
+ {
+ let has_meet = title.to_lowercase().contains("google meet")
+ || title.to_lowercase().contains("meet.google.com");
if has_meet {
println!(" *** MEET WINDOW [{}]: {:?}", j, title);
} else {
- println!(" window[{}]: {:?}", j, &title[..title.len().min(80)]);
+ println!(
+ " window[{}]: {:?}",
+ j,
+ &title[..title.len().min(80)]
+ );
}
}
- if let Some(doc) = get_ax_string_attr(child, cidre::ax::attr::document()) {
+ if let Some(doc) =
+ get_ax_string_attr(child, cidre::ax::attr::document())
+ {
if doc.to_lowercase().contains("meet.google") {
println!(" *** MEET DOC [{}]: {:?}", j, doc);
}
@@ -2996,8 +3037,10 @@ mod live_tests {
let scanner = MeetingUiScanner::new();
for app in &apps {
let result = scanner.scan_process(app.pid, &profiles[app.profile_index]);
- println!(" {} => in_call={}, signals={}, matched={:?}",
- app.app_name, result.is_in_call, result.signals_found, result.matched_signals);
+ println!(
+ " {} => in_call={}, signals={}, matched={:?}",
+ app.app_name, result.is_in_call, result.signals_found, result.matched_signals
+ );
}
}
}
@@ -3017,40 +3060,62 @@ mod live_tests2 {
let running = workspace.running_apps();
for i in 0..running.len() {
let app = &running[i];
- let name = app.localized_name().map(|s| s.to_string()).unwrap_or_default();
- if name != "Arc" { continue; }
-
+ let name = app
+ .localized_name()
+ .map(|s| s.to_string())
+ .unwrap_or_default();
+ if name != "Arc" {
+ continue;
+ }
+
println!("Arc pid={}", app.pid());
let ax_app = cidre::ax::UiElement::with_app_pid(app.pid());
let _ = ax_app.set_messaging_timeout_secs(2.0);
-
+
let windows = ax_app.children().unwrap();
for j in 0..windows.len() {
let window = &windows[j];
let _ = window.set_messaging_timeout_secs(1.0);
-
- let title = get_ax_string_attr(window, cidre::ax::attr::title()).unwrap_or_default();
- let doc = get_ax_string_attr(window, cidre::ax::attr::document()).unwrap_or_default();
+
+ let title =
+ get_ax_string_attr(window, cidre::ax::attr::title()).unwrap_or_default();
+ let doc =
+ get_ax_string_attr(window, cidre::ax::attr::document()).unwrap_or_default();
println!("\nwindow[{}] title={:?} doc={:?}", j, title, doc);
-
+
// Check role
- let role = get_ax_string_attr(window, cidre::ax::attr::role()).unwrap_or_default();
+ let role =
+ get_ax_string_attr(window, cidre::ax::attr::role()).unwrap_or_default();
println!(" role={:?}", role);
-
+
// Walk 2 levels deep looking for URL or "Google Meet"
if let Ok(children) = window.children() {
println!(" children: {}", children.len());
for k in 0..children.len().min(20) {
let child = &children[k];
let _ = child.set_messaging_timeout_secs(0.3);
- let crole = get_ax_string_attr(child, cidre::ax::attr::role()).unwrap_or_default();
- let ctitle = get_ax_string_attr(child, cidre::ax::attr::title()).unwrap_or_default();
- let cdoc = get_ax_string_attr(child, cidre::ax::attr::document()).unwrap_or_default();
- let cval = get_ax_string_attr(child, cidre::ax::attr::value()).unwrap_or_default();
-
- if !ctitle.is_empty() || !cdoc.is_empty() || cval.contains("meet") || cval.contains("google") {
- println!(" child[{}] role={:?} title={:?} doc={:?} val={:?}",
- k, crole, &ctitle[..ctitle.len().min(60)], &cdoc[..cdoc.len().min(60)], &cval[..cval.len().min(80)]);
+ let crole = get_ax_string_attr(child, cidre::ax::attr::role())
+ .unwrap_or_default();
+ let ctitle = get_ax_string_attr(child, cidre::ax::attr::title())
+ .unwrap_or_default();
+ let cdoc = get_ax_string_attr(child, cidre::ax::attr::document())
+ .unwrap_or_default();
+ let cval = get_ax_string_attr(child, cidre::ax::attr::value())
+ .unwrap_or_default();
+
+ if !ctitle.is_empty()
+ || !cdoc.is_empty()
+ || cval.contains("meet")
+ || cval.contains("google")
+ {
+ println!(
+ " child[{}] role={:?} title={:?} doc={:?} val={:?}",
+ k,
+ crole,
+ &ctitle[..ctitle.len().min(60)],
+ &cdoc[..cdoc.len().min(60)],
+ &cval[..cval.len().min(80)]
+ );
}
}
}
diff --git a/crates/screenpipe-engine/src/paired_capture.rs b/crates/screenpipe-engine/src/paired_capture.rs
index 8375a6973..c4d244614 100644
--- a/crates/screenpipe-engine/src/paired_capture.rs
+++ b/crates/screenpipe-engine/src/paired_capture.rs
@@ -814,7 +814,12 @@ mod tests {
#[test]
fn test_thin_known_canvas_app_figma() {
let snap = make_snap(vec![]);
- assert!(a11y_content_is_thin(&snap, Some("My Design - Figma"), None, None));
+ assert!(a11y_content_is_thin(
+ &snap,
+ Some("My Design - Figma"),
+ None,
+ None
+ ));
}
#[test]
@@ -825,7 +830,12 @@ mod tests {
AccessibilityTreeNode { role: "AXStaticText".into(), text: "This is a long article about dogs. Dogs are domesticated descendants of wolves. They were the first species to be domesticated over 14,000 years ago.".into(), depth: 1, bounds: None, ..Default::default() },
AccessibilityTreeNode { role: "AXLink".into(), text: "Read more about canine history".into(), depth: 1, bounds: None, ..Default::default() },
]);
- assert!(!a11y_content_is_thin(&snap, Some("Dog - Wikipedia"), None, None));
+ assert!(!a11y_content_is_thin(
+ &snap,
+ Some("Dog - Wikipedia"),
+ None,
+ None
+ ));
}
#[test]
@@ -939,7 +949,12 @@ mod tests {
},
]);
// >70% chrome text
- assert!(a11y_content_is_thin(&snap, Some("Untitled document"), None, None));
+ assert!(a11y_content_is_thin(
+ &snap,
+ Some("Untitled document"),
+ None,
+ None
+ ));
}
#[test]
diff --git a/crates/screenpipe-engine/src/pipe_store.rs b/crates/screenpipe-engine/src/pipe_store.rs
index fc5e8ca98..684edbdb5 100644
--- a/crates/screenpipe-engine/src/pipe_store.rs
+++ b/crates/screenpipe-engine/src/pipe_store.rs
@@ -33,23 +33,28 @@ impl PipeStore for SqlitePipeStore {
model: &str,
provider: Option<&str>,
) -> Result<i64> {
- Ok(self.db.pipe_create_execution_queued(pipe_name, trigger_type, model, provider).await?)
+ Ok(self
+ .db
+ .pipe_create_execution_queued(pipe_name, trigger_type, model, provider)
+ .await?)
}
async fn set_execution_running(&self, id: i64, pid: Option<u32>) -> Result<()> {
use screenpipe_db::write_queue::PipeBindValue;
let now = Utc::now().to_rfc3339();
- self.db.pipe_execute_write_queued(
- id,
- r#"UPDATE pipe_executions
+ self.db
+ .pipe_execute_write_queued(
+ id,
+ r#"UPDATE pipe_executions
SET status = 'running', pid = COALESCE(?, pid), started_at = COALESCE(started_at, ?)
WHERE id = ?"#,
- vec![
- PipeBindValue::OptInt(pid.map(|p| p as i64)),
- PipeBindValue::Text(now),
- PipeBindValue::Int(id),
- ],
- ).await?;
+ vec![
+ PipeBindValue::OptInt(pid.map(|p| p as i64)),
+ PipeBindValue::Text(now),
+ PipeBindValue::Int(id),
+ ],
+ )
+ .await?;
Ok(())
}
@@ -65,9 +70,10 @@ impl PipeStore for SqlitePipeStore {
) -> Result<()> {
use screenpipe_db::write_queue::PipeBindValue;
let now = Utc::now().to_rfc3339();
- self.db.pipe_execute_write_queued(
- id,
- r#"UPDATE pipe_executions
+ self.db
+ .pipe_execute_write_queued(
+ id,
+ r#"UPDATE pipe_executions
SET status = ?,
finished_at = ?,
stdout = ?,
@@ -80,19 +86,20 @@ impl PipeStore for SqlitePipeStore {
AS INTEGER
)
WHERE id = ?"#,
- vec![
- PipeBindValue::Text(status.to_string()),
- PipeBindValue::Text(now.clone()),
- PipeBindValue::Text(stdout.to_string()),
- PipeBindValue::Text(stderr.to_string()),
- PipeBindValue::OptInt32(exit_code),
- PipeBindValue::OptText(error_type.map(|s| s.to_string())),
- PipeBindValue::OptText(error_message.map(|s| s.to_string())),
- PipeBindValue::Text(now.clone()),
- PipeBindValue::Text(now),
- PipeBindValue::Int(id),
- ],
- ).await?;
+ vec![
+ PipeBindValue::Text(status.to_string()),
+ PipeBindValue::Text(now.clone()),
+ PipeBindValue::Text(stdout.to_string()),
+ PipeBindValue::Text(stderr.to_string()),
+ PipeBindValue::OptInt32(exit_code),
+ PipeBindValue::OptText(error_type.map(|s| s.to_string())),
+ PipeBindValue::OptText(error_message.map(|s| s.to_string())),
+ PipeBindValue::Text(now.clone()),
+ PipeBindValue::Text(now),
+ PipeBindValue::Int(id),
+ ],
+ )
+ .await?;
Ok(())
}
@@ -117,16 +124,18 @@ impl PipeStore for SqlitePipeStore {
async fn mark_orphaned_running(&self) -> Result<u32> {
use screenpipe_db::write_queue::PipeBindValue;
let now = Utc::now().to_rfc3339();
- self.db.pipe_execute_write_queued(
- 0,
- r#"UPDATE pipe_executions
+ self.db
+ .pipe_execute_write_queued(
+ 0,
+ r#"UPDATE pipe_executions
SET status = 'failed',
finished_at = ?,
error_type = 'interrupted',
error_message = 'interrupted by system restart'
WHERE status IN ('running', 'queued')"#,
- vec![PipeBindValue::Text(now)],
- ).await?;
+ vec![PipeBindValue::Text(now)],
+ )
+ .await?;
// We can't easily get rows_affected through the write queue, return 0
Ok(0)
}
@@ -181,7 +190,9 @@ impl PipeStore for SqlitePipeStore {
}
async fn cleanup_old_executions(&self, keep_per_pipe: i32) -> Result<u32> {
- self.db.pipe_delete_old_executions_queued(keep_per_pipe).await?;
+ self.db
+ .pipe_delete_old_executions_queued(keep_per_pipe)
+ .await?;
// Can't easily get rows_affected through write queue, return 0
Ok(0)
}
diff --git a/crates/screenpipe-engine/src/routes/frames.rs b/crates/screenpipe-engine/src/routes/frames.rs
index 3dee5752c..319f5514a 100644
--- a/crates/screenpipe-engine/src/routes/frames.rs
+++ b/crates/screenpipe-engine/src/routes/frames.rs
@@ -565,10 +565,22 @@ pub async fn get_frame_context(
let properties = {
let mut props = serde_json::Map::new();
for key in &[
- "automation_id", "class_name", "value", "help_text",
- "url", "placeholder", "role_description", "subrole",
- "is_enabled", "is_focused", "is_selected", "is_expanded",
- "is_password", "is_keyboard_focusable", "accelerator_key", "access_key",
+ "automation_id",
+ "class_name",
+ "value",
+ "help_text",
+ "url",
+ "placeholder",
+ "role_description",
+ "subrole",
+ "is_enabled",
+ "is_focused",
+ "is_selected",
+ "is_expanded",
+ "is_password",
+ "is_keyboard_focusable",
+ "accelerator_key",
+ "access_key",
] {
if let Some(v) = node_val.get(*key) {
if !v.is_null() {
@@ -576,7 +588,11 @@ pub async fn get_frame_context(
}
}
}
- if props.is_empty() { None } else { Some(serde_json::Value::Object(props)) }
+ if props.is_empty() {
+ None
+ } else {
+ Some(serde_json::Value::Object(props))
+ }
};
nodes.push(AccessibilityNode {
diff --git a/crates/screenpipe-engine/src/routes/pipe_store.rs b/crates/screenpipe-engine/src/routes/pipe_store.rs
index 819b64481..5e3a0255e 100644
--- a/crates/screenpipe-engine/src/routes/pipe_store.rs
+++ b/crates/screenpipe-engine/src/routes/pipe_store.rs
@@ -238,14 +238,18 @@ pub async fn pipe_store_install(
};
// Extract version from registry response
- let version = detail.get("version")
+ let version = detail
+ .get("version")
.or_else(|| detail.get("data").and_then(|d| d.get("version")))
.and_then(|v| v.as_i64())
.unwrap_or(1);
// 2. Install locally with store tracking
let mgr = pm.lock().await;
- let name = match mgr.install_pipe_from_store(&source_md, &body.slug, version).await {
+ let name = match mgr
+ .install_pipe_from_store(&source_md, &body.slug, version)
+ .await
+ {
Ok(name) => name,
Err(e) => return Json(json!({ "error": format!("failed to install pipe: {}", e) })),
};
@@ -272,24 +276,36 @@ pub async fn pipe_store_update(
let detail = match client.get(&detail_url).send().await {
Ok(resp) => match resp.json::<Value>().await {
Ok(body) => body,
- Err(e) => return Json(json!({ "error": format!("failed to parse registry response: {}", e) })),
+ Err(e) => {
+ return Json(
+ json!({ "error": format!("failed to parse registry response: {}", e) }),
+ )
+ }
},
Err(e) => return Json(json!({ "error": format!("failed to reach registry: {}", e) })),
};
- let source_md = match detail.get("source_md").or_else(|| detail.get("data").and_then(|d| d.get("source_md"))).and_then(|v| v.as_str()) {
+ let source_md = match detail
+ .get("source_md")
+ .or_else(|| detail.get("data").and_then(|d| d.get("source_md")))
+ .and_then(|v| v.as_str())
+ {
Some(md) => md.to_string(),
None => return Json(json!({ "error": "pipe not found or missing source_md" })),
};
- let version = detail.get("version")
+ let version = detail
+ .get("version")
.or_else(|| detail.get("data").and_then(|d| d.get("version")))
.and_then(|v| v.as_i64())
.unwrap_or(1);
// 2. Update locally
let mgr = pm.lock().await;
- match mgr.update_pipe_from_store(&body.slug, &source_md, &body.slug, version).await {
+ match mgr
+ .update_pipe_from_store(&body.slug, &source_md, &body.slug, version)
+ .await
+ {
Ok(()) => Json(json!({ "success": true, "slug": body.slug, "version": version })),
Err(e) => Json(json!({ "error": format!("failed to update pipe: {}", e) })),
}
@@ -299,9 +315,7 @@ pub async fn pipe_store_update(
///
/// Check for available updates for all store-installed pipes.
/// Returns a map of slug -> latest_version for pipes that have updates.
-pub async fn pipe_store_check_updates(
- State(pm): State<SharedPipeManager>,
-) -> Json<Value> {
+pub async fn pipe_store_check_updates(State(pm): State<SharedPipeManager>) -> Json<Value> {
let mgr = pm.lock().await;
let pipes = mgr.list_pipes().await;
drop(mgr);
diff --git a/crates/screenpipe-engine/src/routes/streaming.rs b/crates/screenpipe-engine/src/routes/streaming.rs
index e46045ace..d397ae905 100644
--- a/crates/screenpipe-engine/src/routes/streaming.rs
+++ b/crates/screenpipe-engine/src/routes/streaming.rs
@@ -369,18 +369,22 @@ async fn handle_stream_frames_socket(
// frames (the only channel consumer).
let frames_to_send: Vec<_> = {
let mut sent = sent_ids_backfill.lock().await;
- chunks.frames.into_iter().filter_map(|chunk| {
- if sent.contains(&chunk.frame_id) {
- return None;
- }
- sent.insert(chunk.frame_id);
- let frame = create_time_series_frame(chunk);
- if frame.frame_data.is_empty() {
- None
- } else {
- Some(frame)
- }
- }).collect()
+ chunks
+ .frames
+ .into_iter()
+ .filter_map(|chunk| {
+ if sent.contains(&chunk.frame_id) {
+ return None;
+ }
+ sent.insert(chunk.frame_id);
+ let frame = create_time_series_frame(chunk);
+ if frame.frame_data.is_empty() {
+ None
+ } else {
+ Some(frame)
+ }
+ })
+ .collect()
}; // lock dropped
for frame in frames_to_send {
@@ -650,16 +654,20 @@ async fn fetch_and_process_frames_with_tracking(
// live-frame path which also needs this lock.
let frames_to_send: Vec<_> = {
let mut sent = sent_frame_ids.lock().await;
- chunks.frames.into_iter().filter_map(|chunk| {
- sent.insert(chunk.frame_id);
- let ts = chunk.timestamp;
- let frame = create_time_series_frame(chunk);
- if frame.frame_data.is_empty() {
- None
- } else {
- Some((ts, frame))
- }
- }).collect()
+ chunks
+ .frames
+ .into_iter()
+ .filter_map(|chunk| {
+ sent.insert(chunk.frame_id);
+ let ts = chunk.timestamp;
+ let frame = create_time_series_frame(chunk);
+ if frame.frame_data.is_empty() {
+ None
+ } else {
+ Some((ts, frame))
+ }
+ })
+ .collect()
}; // lock dropped
for (ts, frame) in frames_to_send {
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 16d183c7a..3f40f81b9 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -664,7 +664,6 @@ impl SCServer {
router
};
-
// Connections routes (pipe-facing integrations: Telegram, Slack, etc.)
let cm: crate::connections_api::SharedConnectionManager = Arc::new(Mutex::new(
screenpipe_connect::connections::ConnectionManager::new(self.screenpipe_dir.clone()),
diff --git a/crates/screenpipe-engine/src/sleep_monitor.rs b/crates/screenpipe-engine/src/sleep_monitor.rs
index b138fb5a4..c1f774caf 100644
--- a/crates/screenpipe-engine/src/sleep_monitor.rs
+++ b/crates/screenpipe-engine/src/sleep_monitor.rs
@@ -246,18 +246,16 @@ pub fn start_sleep_monitor() {
// Thread 2: Safety-net CGSession poller. The CFNotificationCenter above is
// event-driven but notifications can be lost during sleep/wake transitions or
// if the CFRunLoop thread stalls. This poll catches any missed unlock within 5s.
- std::thread::spawn(|| {
- loop {
- std::thread::sleep(std::time::Duration::from_secs(5));
+ std::thread::spawn(|| loop {
+ std::thread::sleep(std::time::Duration::from_secs(5));
- let locked = check_screen_locked_cgsession();
- let was_locked = SCREEN_IS_LOCKED.swap(locked, Ordering::SeqCst);
- if locked != was_locked {
- if locked {
- info!("Screen locked (CGSession safety-net poll)");
- } else {
- info!("Screen unlocked (CGSession safety-net poll)");
- }
+ let locked = check_screen_locked_cgsession();
+ let was_locked = SCREEN_IS_LOCKED.swap(locked, Ordering::SeqCst);
+ if locked != was_locked {
+ if locked {
+ info!("Screen locked (CGSession safety-net poll)");
+ } else {
+ info!("Screen unlocked (CGSession safety-net poll)");
}
}
});
diff --git a/crates/screenpipe-engine/src/sync_provider.rs b/crates/screenpipe-engine/src/sync_provider.rs
index fbe462f29..ac24589f6 100644
--- a/crates/screenpipe-engine/src/sync_provider.rs
+++ b/crates/screenpipe-engine/src/sync_provider.rs
@@ -572,7 +572,14 @@ impl ScreenpipeSyncProvider {
.or_else(|| frame_rec.and_then(|f| f.window_name.as_deref()));
self.db
- .sync_insert_ocr(frame_id, &ocr.text, ocr.focused, app_name, window_name, &ocr.sync_id)
+ .sync_insert_ocr(
+ frame_id,
+ &ocr.text,
+ ocr.focused,
+ app_name,
+ window_name,
+ &ocr.sync_id,
+ )
.await
.map_err(|e| SyncError::Database(format!("failed to insert OCR: {}", e)))?;
@@ -611,7 +618,9 @@ impl ScreenpipeSyncProvider {
trans.speaker_id,
)
.await
- .map_err(|e| SyncError::Database(format!("failed to insert transcription: {}", e)))?;
+ .map_err(|e| {
+ SyncError::Database(format!("failed to insert transcription: {}", e))
+ })?;
imported_transcriptions += 1;
tokio::task::yield_now().await;
diff --git a/crates/screenpipe-vault/Cargo.toml b/crates/screenpipe-vault/Cargo.toml
index 16d1e1aba..4894deba5 100644
--- a/crates/screenpipe-vault/Cargo.toml
+++ b/crates/screenpipe-vault/Cargo.toml
@@ -30,12 +30,8 @@ tracing = { workspace = true }
# File walking
walkdir = "2"
-# OS keychain
-keyring = { version = "3", optional = true }
-
[dev-dependencies]
tempfile = "3"
[features]
default = []
-keychain = ["dep:keyring"]