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

style: cargo fmt across workspace

Louis Beaumontd7f92b37eea3
diff --git a/crates/screenpipe-audio/src/audio_manager/device_monitor.rs b/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
index e4c4f4686..c6517c798 100644
--- a/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
+++ b/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
@@ -242,7 +242,9 @@ pub async fn start_device_monitor(
"[DEVICE_RECOVERY] initial sync: stopping non-default output: {}",
device_name
);
- let _ = audio_manager.stop_device(device_name).await;
+ let _ = audio_manager
+ .stop_device(device_name)
+ .await;
}
}
}
@@ -273,7 +275,8 @@ pub async fn start_device_monitor(
"[DEVICE_RECOVERY] initial sync: started communications output: {}",
comm_name
);
- default_tracker.last_communications_output = Some(comm_name);
+ default_tracker.last_communications_output =
+ Some(comm_name);
}
Err(e) => {
warn!(
@@ -390,7 +393,9 @@ pub async fn start_device_monitor(
#[cfg(target_os = "windows")]
{
let old_comm = default_tracker.last_communications_output.clone();
- if let Some(new_comm_output) = default_tracker.check_communications_output_changed() {
+ if let Some(new_comm_output) =
+ default_tracker.check_communications_output_changed()
+ {
info!(
"[DEVICE_RECOVERY] communications output changed to: {}",
new_comm_output
@@ -398,7 +403,8 @@ pub async fn start_device_monitor(
// Stop the previous communications device if it's not the multimedia default
if let Some(ref old_name) = old_comm {
- if default_tracker.last_output.as_deref() != Some(old_name.as_str()) {
+ if default_tracker.last_output.as_deref() != Some(old_name.as_str())
+ {
let _ = audio_manager.stop_device(old_name).await;
}
}
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index 2f1e87c83..f683c35dd 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -533,14 +533,21 @@ impl AudioManager {
let mut inserted = false;
for retry in 0..3u32 {
match db.insert_audio_chunk(&path, capture_dt).await {
- Ok(_) => { inserted = true; break; }
+ Ok(_) => {
+ inserted = true;
+ break;
+ }
Err(e) => {
warn!(
"failed to insert audio chunk into db (attempt {}/3): {:?}",
- retry + 1, e
+ retry + 1,
+ e
);
if retry < 2 {
- tokio::time::sleep(std::time::Duration::from_millis(500 * (retry as u64 + 1))).await;
+ tokio::time::sleep(std::time::Duration::from_millis(
+ 500 * (retry as u64 + 1),
+ ))
+ .await;
}
}
}
diff --git a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
index d48ff5d28..56eed414e 100644
--- a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
+++ b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
@@ -207,7 +207,8 @@ pub async fn reconcile_untranscribed(
if let Err(e) = db.delete_audio_chunks_batch(&orphan_chunk_ids).await {
warn!(
"reconciliation: failed to batch-delete {} orphan chunks: {}",
- orphan_chunk_ids.len(), e
+ orphan_chunk_ids.len(),
+ e
);
consecutive_db_errors += 1;
} else {
@@ -282,7 +283,8 @@ pub async fn reconcile_untranscribed(
if let Err(e) = db.delete_audio_chunks_batch(&old_chunk_ids).await {
warn!(
"reconciliation: failed to batch-delete {} silent chunks: {}",
- old_chunks.len(), e
+ old_chunks.len(),
+ e
);
consecutive_db_errors += 1;
} else {
@@ -502,7 +504,8 @@ async fn retry_pending_transcriptions(
// (e.g. by archive cleanup), the INSERT will always fail with a FK
// constraint violation — remove the orphaned pending file instead of
// retrying forever.
- let chunk_exists = db.audio_chunk_exists(pending.audio_chunk_id)
+ let chunk_exists = db
+ .audio_chunk_exists(pending.audio_chunk_id)
.await
.unwrap_or(false);
diff --git a/crates/screenpipe-audio/src/core/device.rs b/crates/screenpipe-audio/src/core/device.rs
index 1ed2e1b63..7334d0bbf 100644
--- a/crates/screenpipe-audio/src/core/device.rs
+++ b/crates/screenpipe-audio/src/core/device.rs
@@ -234,10 +234,7 @@ pub async fn get_cpal_device_and_config(
result
}
Err(e) => {
- tracing::warn!(
- "ScreenCaptureKit unavailable for System Audio: {}",
- e
- );
+ tracing::warn!("ScreenCaptureKit unavailable for System Audio: {}", e);
None
}
};
@@ -293,7 +290,9 @@ pub async fn get_cpal_device_and_config(
})
.ok_or_else(|| anyhow!("No supported output configurations found"))?;
- best_config.clone().with_sample_rate(best_config.max_sample_rate())
+ best_config
+ .clone()
+ .with_sample_rate(best_config.max_sample_rate())
} else {
let configs: Vec<_> = cpal_audio_device.supported_input_configs()?.collect();
let best_config = configs
@@ -306,7 +305,9 @@ pub async fn get_cpal_device_and_config(
})
.ok_or_else(|| anyhow!("No supported input configurations found"))?;
- best_config.clone().with_sample_rate(best_config.max_sample_rate())
+ best_config
+ .clone()
+ .with_sample_rate(best_config.max_sample_rate())
};
Ok((cpal_audio_device, config))
@@ -607,14 +608,13 @@ mod windows_com_audio {
/// Returns the friendly name if it differs from the eConsole default,
/// or None if they are the same device.
pub unsafe fn get_communications_output_name() -> Result<Option<String>> {
+ use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
use windows::Win32::Media::Audio::{
eCommunications, eConsole, eRender, IMMDeviceEnumerator, MMDeviceEnumerator,
};
use windows::Win32::System::Com::{
- CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_MULTITHREADED,
- STGM,
+ CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_MULTITHREADED, STGM,
};
- use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
// COM init (idempotent per thread — returns S_FALSE if already initialized)
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
diff --git a/crates/screenpipe-audio/src/meeting_detector.rs b/crates/screenpipe-audio/src/meeting_detector.rs
index 6ceb3562f..ffc359f3a 100644
--- a/crates/screenpipe-audio/src/meeting_detector.rs
+++ b/crates/screenpipe-audio/src/meeting_detector.rs
@@ -137,27 +137,27 @@ impl MeetingDetector {
"around",
"whereby",
"google meet",
- "tuple", // Pair programming with video
- "pop", // Screen sharing + video
- "tandem", // Virtual office
- "loom", // Loom live recording/calls
- "riverside", // Podcast/interview recording
- "gather", // Virtual office
- "butter", // Workshop/meeting platform
- "cal.com", // Cal.com video meetings
- "daily.co", // Daily.co video SDK app
- "ringcentral", // RingCentral meetings
+ "tuple", // Pair programming with video
+ "pop", // Screen sharing + video
+ "tandem", // Virtual office
+ "loom", // Loom live recording/calls
+ "riverside", // Podcast/interview recording
+ "gather", // Virtual office
+ "butter", // Workshop/meeting platform
+ "cal.com", // Cal.com video meetings
+ "daily.co", // Daily.co video SDK app
+ "ringcentral", // RingCentral meetings
"ringcentral meetings",
- "bluejeans", // BlueJeans video
- "gotomeeting", // GoTo Meeting
+ "bluejeans", // BlueJeans video
+ "gotomeeting", // GoTo Meeting
"goto meeting",
- "dialpad", // Dialpad meetings
- "lifesize", // Lifesize video
- "vonage", // Vonage meetings
+ "dialpad", // Dialpad meetings
+ "lifesize", // Lifesize video
+ "vonage", // Vonage meetings
"8x8 meet",
"8x8 work",
- "jitsi meet", // Jitsi desktop app
- "chime", // Amazon Chime
+ "jitsi meet", // Jitsi desktop app
+ "chime", // Amazon Chime
"amazon chime",
]
.iter()
@@ -192,31 +192,31 @@ impl MeetingDetector {
"teams.live.com".to_string(),
"zoom.us/j".to_string(),
"zoom.us/wc".to_string(),
- "zoom.us/my".to_string(), // Personal meeting rooms
+ "zoom.us/my".to_string(), // Personal meeting rooms
"whereby.com".to_string(),
"app.slack.com/huddle".to_string(),
- "meet.jit.si".to_string(), // Jitsi public instance
- "jitsi".to_string(), // Self-hosted Jitsi (partial match)
- "riverside.fm".to_string(), // Riverside browser
- "gather.town".to_string(), // Gather virtual office
+ "meet.jit.si".to_string(), // Jitsi public instance
+ "jitsi".to_string(), // Self-hosted Jitsi (partial match)
+ "riverside.fm".to_string(), // Riverside browser
+ "gather.town".to_string(), // Gather virtual office
"app.gather.town".to_string(),
- "butter.us".to_string(), // Butter workshops
- "livestorm.co".to_string(), // Livestorm webinars
- "ping.gg".to_string(), // Ping video
- "cal.com".to_string(), // Cal.com video
- "daily.co".to_string(), // Daily.co video
+ "butter.us".to_string(), // Butter workshops
+ "livestorm.co".to_string(), // Livestorm webinars
+ "ping.gg".to_string(), // Ping video
+ "cal.com".to_string(), // Cal.com video
+ "daily.co".to_string(), // Daily.co video
"app.daily.co".to_string(),
- "pop.com".to_string(), // Pop pair programming
- "tuple.app".to_string(), // Tuple pair programming
- "tandem.chat".to_string(), // Tandem virtual office
+ "pop.com".to_string(), // Pop pair programming
+ "tuple.app".to_string(), // Tuple pair programming
+ "tandem.chat".to_string(), // Tandem virtual office
"meet.ringcentral.com".to_string(),
"bluejeans.com".to_string(),
"gotomeeting.com".to_string(),
- "app.chime.aws".to_string(), // Amazon Chime
+ "app.chime.aws".to_string(), // Amazon Chime
"dialpad.com/meetings".to_string(),
"8x8.vc".to_string(),
- "webex.com".to_string(), // Webex in browser
- "loom.com/share".to_string(), // Loom live sessions
+ "webex.com".to_string(), // Webex in browser
+ "loom.com/share".to_string(), // Loom live sessions
];
Self {
diff --git a/crates/screenpipe-audio/src/transcription/deepgram/batch.rs b/crates/screenpipe-audio/src/transcription/deepgram/batch.rs
index ecaec94ea..3bcc4bade 100644
--- a/crates/screenpipe-audio/src/transcription/deepgram/batch.rs
+++ b/crates/screenpipe-audio/src/transcription/deepgram/batch.rs
@@ -6,9 +6,9 @@ use crate::transcription::VocabularyEntry;
use anyhow::Result;
use mp3lame_encoder::{Builder, FlushNoGap, MonoPcm};
use reqwest::{Client, Response};
-use std::mem::MaybeUninit;
use screenpipe_core::Language;
use serde_json::Value;
+use std::mem::MaybeUninit;
use tracing::{debug, error, info};
use crate::transcription::deepgram::{CUSTOM_DEEPGRAM_API_TOKEN, DEEPGRAM_API_URL};
@@ -106,9 +106,7 @@ fn create_mp3_data(audio_data: &[f32], sample_rate: u32) -> Result<(Vec<u8>, &'s
// Flush remaining frames
let mut flush_buf: Vec<MaybeUninit<u8>> = vec![MaybeUninit::uninit(); 7200];
- let flush_size = encoder
- .flush::<FlushNoGap>(&mut flush_buf)
- .unwrap_or(0);
+ let flush_size = encoder.flush::<FlushNoGap>(&mut flush_buf).unwrap_or(0);
let mut result = mp3_buf;
if flush_size > 0 {
let flushed: Vec<u8> = flush_buf[..flush_size]
diff --git a/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs b/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs
index d085de7f7..4ac06ba71 100644
--- a/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs
+++ b/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs
@@ -5,9 +5,9 @@
use anyhow::Result;
use mp3lame_encoder::{Builder, FlushNoGap, MonoPcm};
use reqwest::{multipart, Client, Response};
-use std::mem::MaybeUninit;
use screenpipe_core::Language;
use serde_json::Value;
+use std::mem::MaybeUninit;
use std::sync::Arc;
use tracing::{debug, error, info};
@@ -164,9 +164,7 @@ fn create_mp3_data(audio_data: &[f32], sample_rate: u32) -> Result<(Vec<u8>, &'s
// Flush remaining frames
let mut flush_buf: Vec<MaybeUninit<u8>> = vec![MaybeUninit::uninit(); 7200];
- let flush_size = encoder
- .flush::<FlushNoGap>(&mut flush_buf)
- .unwrap_or(0);
+ let flush_size = encoder.flush::<FlushNoGap>(&mut flush_buf).unwrap_or(0);
let mut result = mp3_buf;
if flush_size > 0 {
let flushed: Vec<u8> = flush_buf[..flush_size]
diff --git a/crates/screenpipe-audio/src/transcription/transcription_result.rs b/crates/screenpipe-audio/src/transcription/transcription_result.rs
index 94c82842a..6d7711128 100644
--- a/crates/screenpipe-audio/src/transcription/transcription_result.rs
+++ b/crates/screenpipe-audio/src/transcription/transcription_result.rs
@@ -133,7 +133,9 @@ pub async fn process_transcription_result(
name: result.input.device.name.clone(),
device_type: match result.input.device.device_type {
crate::core::device::DeviceType::Input => screenpipe_db::DeviceType::Input,
- crate::core::device::DeviceType::Output => screenpipe_db::DeviceType::Output,
+ crate::core::device::DeviceType::Output => {
+ screenpipe_db::DeviceType::Output
+ }
},
},
Some(speaker.id),
@@ -157,7 +159,8 @@ pub async fn process_transcription_result(
"Failed to insert audio chunk+transcription for device {} (attempt {}/3): {}, retrying...",
result.input.device, retry + 1, e
);
- tokio::time::sleep(std::time::Duration::from_millis(500 * (retry as u64 + 1))).await;
+ tokio::time::sleep(std::time::Duration::from_millis(500 * (retry as u64 + 1)))
+ .await;
} else {
error!(
"Failed to insert audio chunk+transcription for device {} after 3 retries: {}",
@@ -182,7 +185,11 @@ pub async fn get_or_create_speaker_from_embedding(
debug!(
"matched speaker id={} name={:?}",
speaker.id,
- if speaker.name.is_empty() { "unnamed" } else { &speaker.name }
+ if speaker.name.is_empty() {
+ "unnamed"
+ } else {
+ &speaker.name
+ }
);
// Improve cluster over time: update centroid and store diverse embeddings
if let Err(e) = db.update_speaker_centroid(speaker.id, embedding).await {
diff --git a/crates/screenpipe-config/src/lib.rs b/crates/screenpipe-config/src/lib.rs
index dc98a0742..ec27691ce 100644
--- a/crates/screenpipe-config/src/lib.rs
+++ b/crates/screenpipe-config/src/lib.rs
@@ -20,10 +20,10 @@
//! or a TOML config file. Both paths produce the same type that the
//! engine consumes.
-mod recording;
mod defaults;
mod persistence;
+mod recording;
-pub use recording::*;
pub use defaults::*;
pub use persistence::*;
+pub use recording::*;
diff --git a/crates/screenpipe-config/src/persistence.rs b/crates/screenpipe-config/src/persistence.rs
index c7ecd9323..9d4e19efd 100644
--- a/crates/screenpipe-config/src/persistence.rs
+++ b/crates/screenpipe-config/src/persistence.rs
@@ -26,8 +26,7 @@ pub fn load_toml(path: &Path) -> Result<RecordingSettings, String> {
}
let contents = std::fs::read_to_string(path)
.map_err(|e| format!("failed to read {}: {}", path.display(), e))?;
- toml::from_str(&contents)
- .map_err(|e| format!("failed to parse {}: {}", path.display(), e))
+ toml::from_str(&contents).map_err(|e| format!("failed to parse {}: {}", path.display(), e))
}
/// Save `RecordingSettings` to a TOML file.
@@ -40,8 +39,7 @@ pub fn save_toml(settings: &RecordingSettings, path: &Path) -> Result<(), String
}
let contents = toml::to_string_pretty(settings)
.map_err(|e| format!("failed to serialize settings: {}", e))?;
- std::fs::write(path, contents)
- .map_err(|e| format!("failed to write {}: {}", path.display(), e))
+ std::fs::write(path, contents).map_err(|e| format!("failed to write {}: {}", path.display(), e))
}
/// Resolve the screenpipe config directory: `~/.screenpipe/`
diff --git a/crates/screenpipe-config/src/recording.rs b/crates/screenpipe-config/src/recording.rs
index aec02754d..36b9cc677 100644
--- a/crates/screenpipe-config/src/recording.rs
+++ b/crates/screenpipe-config/src/recording.rs
@@ -32,7 +32,6 @@ pub struct VocabEntry {
#[serde(default)]
pub struct RecordingSettings {
// ── Audio ──────────────────────────────────────────────────────────
-
/// Disable all audio capture and transcription.
#[serde(rename = "disableAudio")]
pub disable_audio: bool,
@@ -87,7 +86,6 @@ pub struct RecordingSettings {
pub vocabulary: Vec<VocabEntry>,
// ── Vision ─────────────────────────────────────────────────────────
-
/// Disable all screen capture.
#[serde(rename = "disableVision")]
pub disable_vision: bool,
@@ -112,7 +110,6 @@ pub struct RecordingSettings {
pub video_quality: String,
// ── Filters ────────────────────────────────────────────────────────
-
/// Window titles to exclude from capture.
#[serde(rename = "ignoredWindows")]
pub ignored_windows: Vec<String>,
@@ -133,13 +130,11 @@ pub struct RecordingSettings {
pub languages: Vec<String>,
// ── Privacy ────────────────────────────────────────────────────────
-
/// Redact personally identifiable information from transcriptions.
#[serde(rename = "usePiiRemoval")]
pub use_pii_removal: bool,
// ── Cloud / Auth ───────────────────────────────────────────────────
-
/// Screenpipe cloud user ID. Empty string means not logged in.
/// Kept as String (not Option) to match existing store.bin schema.
#[serde(rename = "userId")]
@@ -167,7 +162,6 @@ pub struct RecordingSettings {
pub openai_compatible_model: Option<String>,
// ── System ─────────────────────────────────────────────────────────
-
/// HTTP server port for the screenpipe API.
pub port: u16,
@@ -367,11 +361,17 @@ mod tests {
let settings: RecordingSettings = serde_json::from_str(json).unwrap();
// Recording fields parsed correctly
- assert_eq!(settings.audio_transcription_engine, "whisper-large-v3-turbo");
+ assert_eq!(
+ settings.audio_transcription_engine,
+ "whisper-large-v3-turbo"
+ );
assert_eq!(settings.audio_devices, vec!["MacBook Pro Microphone"]);
assert_eq!(settings.deepgram_api_key, "");
assert_eq!(settings.user_id, "abc-123");
- assert_eq!(settings.ignored_windows, vec!["Control Center", "Notification Center"]);
+ assert_eq!(
+ settings.ignored_windows,
+ vec!["Control Center", "Notification Center"]
+ );
assert_eq!(settings.analytics_id, "posthog-uuid");
// Fields that don't exist in RecordingSettings (UI-only) are silently ignored
diff --git a/crates/screenpipe-connect/src/whatsapp/mod.rs b/crates/screenpipe-connect/src/whatsapp/mod.rs
index 3bcc74c16..8e7b43afc 100644
--- a/crates/screenpipe-connect/src/whatsapp/mod.rs
+++ b/crates/screenpipe-connect/src/whatsapp/mod.rs
@@ -152,7 +152,7 @@ impl WhatsAppGateway {
let mut child = Command::new(&node_path)
.arg(script_path.to_str().unwrap())
.env("WHATSAPP_SESSION_DIR", session_dir.to_str().unwrap())
- .stdin(Stdio::piped()) // keep stdin open so gateway doesn't self-terminate
+ .stdin(Stdio::piped()) // keep stdin open so gateway doesn't self-terminate
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
@@ -226,7 +226,9 @@ impl WhatsAppGateway {
let _keep_alive = _stdin;
// Block forever — stdin handle stays open, keeping the gateway alive.
// When stop_process() kills the child, this task becomes inert.
- loop { tokio::time::sleep(std::time::Duration::from_secs(3600)).await; }
+ loop {
+ tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
+ }
});
// Log stderr
@@ -288,7 +290,9 @@ impl WhatsAppGateway {
// Process is dead — should we restart?
if !auto_restart.load(Ordering::SeqCst) {
- info!("whatsapp: gateway exited and auto-restart is disabled, watchdog stopping");
+ info!(
+ "whatsapp: gateway exited and auto-restart is disabled, watchdog stopping"
+ );
*status.lock().await = WhatsAppStatus::Disconnected;
*http_port.lock().await = None;
return;
@@ -368,8 +372,7 @@ impl WhatsAppGateway {
}
Ok(GatewayEvent::Connected { name, phone }) => {
info!("whatsapp: connected as {} ({})", name, phone);
- *s.lock().await =
- WhatsAppStatus::Connected { name, phone };
+ *s.lock().await = WhatsAppStatus::Connected { name, phone };
}
Ok(GatewayEvent::Disconnected { reason }) => {
warn!("whatsapp: disconnected — {}", reason);
@@ -401,8 +404,10 @@ impl WhatsAppGateway {
tokio::spawn(async move {
let _keep = stdin_handle;
// Block forever — stdin handle stays open, keeping the gateway alive.
- // When stop_process() kills the child, this task becomes inert.
- loop { tokio::time::sleep(std::time::Duration::from_secs(3600)).await; }
+ // When stop_process() kills the child, this task becomes inert.
+ loop {
+ tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
+ }
});
// Log stderr
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index c275b480d..7e384df21 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -1309,7 +1309,10 @@ impl PipeManager {
if cb_error_type.as_deref() == Some("context_overflow") {
let pipe_dir = pipes_dir_for_log.join(&pipe_name);
if let Err(e) = delete_pi_sessions(&pipe_dir) {
- warn!("failed to clear Pi session after context overflow for '{}': {}", pipe_name, e);
+ warn!(
+ "failed to clear Pi session after context overflow for '{}': {}",
+ pipe_name, e
+ );
} else {
info!("cleared Pi session for '{}' after context overflow — next run starts fresh", pipe_name);
}
@@ -1383,58 +1386,64 @@ impl PipeManager {
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))?;
-
- 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 — \
+ 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 — \
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 {
diff --git a/crates/screenpipe-core/src/pipes/preset_fallback.rs b/crates/screenpipe-core/src/pipes/preset_fallback.rs
index 12fee044b..822ad23f7 100644
--- a/crates/screenpipe-core/src/pipes/preset_fallback.rs
+++ b/crates/screenpipe-core/src/pipes/preset_fallback.rs
@@ -192,10 +192,7 @@ impl PresetFallbackRegistry {
state
}
Err(e) => {
- warn!(
- "corrupt preset fallback state, starting fresh: {}",
- e
- );
+ warn!("corrupt preset fallback state, starting fresh: {}", e);
PersistedState::default()
}
},
@@ -291,12 +288,7 @@ impl PresetFallbackRegistry {
/// Record failure from raw stderr/stdout content (for errors not caught
/// by the structured parser).
- pub fn record_failure_from_output(
- &self,
- preset_id: &str,
- stderr: &str,
- stdout: &str,
- ) -> bool {
+ pub fn record_failure_from_output(&self, preset_id: &str, stderr: &str, stdout: &str) -> bool {
let combined = format!("{} {}", stderr, stdout).to_lowercase();
let reason = if combined.contains("rate limit")
@@ -345,10 +337,7 @@ impl PresetFallbackRegistry {
for (id, breaker) in state.presets.iter_mut() {
if breaker.state == BreakerState::Open && now >= breaker.cooldown_until {
breaker.state = BreakerState::HalfOpen;
- info!(
- "startup recovery: preset '{}' moved to half-open",
- id
- );
+ info!("startup recovery: preset '{}' moved to half-open", id);
changed = true;
}
// Sanity: if cooldown_until is more than 24h in the future, reset it
@@ -418,10 +407,7 @@ mod tests {
#[test]
fn test_parse_preset_list_array() {
let v = serde_json::json!(["primary", "fallback"]);
- assert_eq!(
- parse_preset_list(&v),
- vec!["primary", "fallback"]
- );
+ assert_eq!(parse_preset_list(&v), vec!["primary", "fallback"]);
}
#[test]
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index b5232ed25..d56eb7d75 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -29,10 +29,10 @@ use futures::future::try_join_all;
use crate::{
text_similarity::is_similar_transcription, AudioChunksResponse, AudioDevice, AudioEntry,
AudioResult, AudioResultRaw, ContentType, DeviceType, Element, ElementRow, ElementSource,
- FrameData, FrameRow, FrameRowLight, FrameWindowData, InsertUiEvent, MeetingRecord, MemoryRecord, OCREntry,
- OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock, Order, SearchMatch, SearchMatchGroup,
- SearchResult, Speaker, TagContentType, TextBounds, TextPosition, TimeSeriesChunk, UiContent,
- UiEventRecord, UiEventRow, VideoMetadata,
+ FrameData, FrameRow, FrameRowLight, FrameWindowData, InsertUiEvent, MeetingRecord,
+ MemoryRecord, OCREntry, OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock, Order, SearchMatch,
+ SearchMatchGroup, SearchResult, Speaker, TagContentType, TextBounds, TextPosition,
+ TimeSeriesChunk, UiContent, UiEventRecord, UiEventRow, VideoMetadata,
};
/// Time window (in seconds) to check for similar transcriptions across devices.
@@ -225,10 +225,8 @@ impl DatabaseManager {
.await?;
let write_semaphore = Arc::new(Semaphore::new(1));
- let write_queue = crate::write_queue::spawn_write_drain(
- write_pool.clone(),
- Arc::clone(&write_semaphore),
- );
+ let write_queue =
+ crate::write_queue::spawn_write_drain(write_pool.clone(), Arc::clone(&write_semaphore));
let db_manager = DatabaseManager {
pool: read_pool,
write_pool,
@@ -396,7 +394,8 @@ impl DatabaseManager {
let mut last_error = None;
for attempt in 1..=max_retries {
let mut conn =
- match tokio::time::timeout(Duration::from_secs(3), self.write_pool.acquire()).await {
+ match tokio::time::timeout(Duration::from_secs(3), self.write_pool.acquire()).await
+ {
Ok(Ok(conn)) => conn,
Ok(Err(e)) => return Err(e),
Err(_) => return Err(sqlx::Error::PoolTimedOut),
@@ -571,12 +570,11 @@ impl DatabaseManager {
/// Check whether an audio chunk row exists.
pub async fn audio_chunk_exists(&self, chunk_id: i64) -> Result<bool, sqlx::Error> {
- let exists: bool = sqlx::query_scalar(
- "SELECT EXISTS(SELECT 1 FROM audio_chunks WHERE id = ?1)",
- )
- .bind(chunk_id)
- .fetch_one(&self.pool)
- .await?;
+ let exists: bool =
+ sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM audio_chunks WHERE id = ?1)")
+ .bind(chunk_id)
+ .fetch_one(&self.pool)
+ .await?;
Ok(exists)
}
@@ -1618,12 +1616,10 @@ impl DatabaseManager {
Some(format!("{}\n{}", a11y, ocr))
}
}
- _ => {
- accessibility_text
- .filter(|t| !t.is_empty())
- .map(String::from)
- .or_else(|| ocr_text_str.filter(|t| !t.is_empty()).map(String::from))
- }
+ _ => accessibility_text
+ .filter(|t| !t.is_empty())
+ .map(String::from)
+ .or_else(|| ocr_text_str.filter(|t| !t.is_empty()).map(String::from)),
};
let result = self
@@ -1777,7 +1773,11 @@ impl DatabaseManager {
for (idx, window) in windows.iter().enumerate() {
// Compute full_text for FTS indexing
- let full_text = if window.text.is_empty() { None } else { Some(window.text.as_str()) };
+ let full_text = if window.text.is_empty() {
+ None
+ } else {
+ Some(window.text.as_str())
+ };
// Insert frame
let frame_id = sqlx::query(
@@ -1896,7 +1896,11 @@ impl DatabaseManager {
for (idx, window) in windows.iter().enumerate() {
// Compute full_text for FTS indexing
- let full_text = if window.text.is_empty() { None } else { Some(window.text.as_str()) };
+ let full_text = if window.text.is_empty() {
+ None
+ } else {
+ Some(window.text.as_str())
+ };
let frame_id = sqlx::query(
"INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url, app_name, window_name, focused, device_name, full_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
@@ -2163,14 +2167,18 @@ impl DatabaseManager {
SearchResult::Audio(audio) => audio.timestamp,
SearchResult::UI(ui) => ui.timestamp,
SearchResult::Input(input) => input.timestamp,
- SearchResult::Memory(m) => m.created_at.parse::<DateTime<Utc>>().unwrap_or_default(),
+ SearchResult::Memory(m) => {
+ m.created_at.parse::<DateTime<Utc>>().unwrap_or_default()
+ }
};
let timestamp_b = match b {
SearchResult::OCR(ocr) => ocr.timestamp,
SearchResult::Audio(audio) => audio.timestamp,
SearchResult::UI(ui) => ui.timestamp,
SearchResult::Input(input) => input.timestamp,
- SearchResult::Memory(m) => m.created_at.parse::<DateTime<Utc>>().unwrap_or_default(),
+ SearchResult::Memory(m) => {
+ m.created_at.parse::<DateTime<Utc>>().unwrap_or_default()
+ }
};
timestamp_b.cmp(&timestamp_a)
});
@@ -2732,8 +2740,7 @@ impl DatabaseManager {
speaker_name,
));
- let (frames_count, audio_count) =
- tokio::try_join!(frames_future, audio_future)?;
+ let (frames_count, audio_count) = tokio::try_join!(frames_future, audio_future)?;
return Ok(frames_count + audio_count);
} else {
let frames_count = frames_future.await?;
@@ -2910,11 +2917,7 @@ impl DatabaseManager {
let count: i64 = match content_type {
ContentType::OCR | ContentType::Accessibility => {
sqlx::query_scalar(&sql)
- .bind(if has_fts {
- fts_query
- } else {
- "*".to_owned()
- })
+ .bind(if has_fts { fts_query } else { "*".to_owned() })
.bind(start_time)
.bind(end_time)
.bind(min_length.map(|l| l as i64))
@@ -4057,7 +4060,8 @@ impl DatabaseManager {
.fetch_all(&self.pool)
.await?;
- let mut map: std::collections::HashMap<String, (i64, i64)> = std::collections::HashMap::new();
+ let mut map: std::collections::HashMap<String, (i64, i64)> =
+ std::collections::HashMap::new();
for (mid, count) in rows {
map.entry(mid).or_default().0 = count;
}
@@ -5808,9 +5812,8 @@ LIMIT ? OFFSET ?
let merged_start: Option<String> = row.try_get("ms")?;
let merged_end: Option<String> = row.try_get("me")?;
// Update the survivor row
- let update_sql = format!(
- "UPDATE meetings SET meeting_start = ?1, meeting_end = ?2 WHERE id = ?3"
- );
+ let update_sql =
+ format!("UPDATE meetings SET meeting_start = ?1, meeting_end = ?2 WHERE id = ?3");
sqlx::query(&update_sql)
.bind(&merged_start)
.bind(&merged_end)
@@ -5942,10 +5945,7 @@ LIMIT ? OFFSET ?
sets.push("source_context = ?5");
}
- let sql = format!(
- "UPDATE memories SET {} WHERE id = ?6",
- sets.join(", ")
- );
+ let sql = format!("UPDATE memories SET {} WHERE id = ?6", sets.join(", "));
sqlx::query(&sql)
.bind(&now)
@@ -6087,7 +6087,6 @@ LIMIT ? OFFSET ?
.fetch_one(&self.pool)
.await
}
-
}
pub fn find_matching_positions(blocks: &[OcrTextBlock], query: &str) -> Vec<TextPosition> {
@@ -6172,7 +6171,9 @@ pub fn find_matching_a11y_positions(tree_json: &str, query: &str) -> Vec<TextPos
matches.sort_by(|a, b| {
let area_a = a.bounds.width * a.bounds.height;
let area_b = b.bounds.width * b.bounds.height;
- area_b.partial_cmp(&area_a).unwrap_or(std::cmp::Ordering::Equal)
+ area_b
+ .partial_cmp(&area_a)
+ .unwrap_or(std::cmp::Ordering::Equal)
});
matches.dedup_by(|a, b| a.text == b.text);
diff --git a/crates/screenpipe-db/src/lib.rs b/crates/screenpipe-db/src/lib.rs
index 852e0d080..46d4ce648 100644
--- a/crates/screenpipe-db/src/lib.rs
+++ b/crates/screenpipe-db/src/lib.rs
@@ -9,11 +9,13 @@ mod types;
mod video_db;
pub(crate) mod write_queue;
-pub use db::{find_matching_a11y_positions, parse_all_text_positions, DatabaseManager, DeleteTimeRangeResult};
-pub use write_queue::SyncTable;
+pub use db::{
+ find_matching_a11y_positions, parse_all_text_positions, DatabaseManager, DeleteTimeRangeResult,
+};
pub use migration_worker::{
create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,
MigrationWorker,
};
pub use text_normalizer::{expand_search_query, sanitize_fts5_query};
pub use types::*;
+pub use write_queue::SyncTable;
diff --git a/crates/screenpipe-db/src/write_queue.rs b/crates/screenpipe-db/src/write_queue.rs
index 9448844e5..b222356ff 100644
--- a/crates/screenpipe-db/src/write_queue.rs
+++ b/crates/screenpipe-db/src/write_queue.rs
@@ -25,7 +25,6 @@ use std::time::Duration;
use tokio::sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore};
use tracing::{debug, error, warn};
-
/// Maximum writes per batch. Caps transaction size to avoid holding
/// the write lock too long and starving readers.
const MAX_BATCH_SIZE: usize = 500;
@@ -333,13 +332,12 @@ async fn execute_single_write(
timestamp,
} => {
let ts = timestamp.unwrap_or_else(Utc::now);
- let id =
- sqlx::query("INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)")
- .bind(file_path.as_str())
- .bind(ts)
- .execute(&mut **conn)
- .await?
- .last_insert_rowid();
+ let id = sqlx::query("INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)")
+ .bind(file_path.as_str())
+ .bind(ts)
+ .execute(&mut **conn)
+ .await?
+ .last_insert_rowid();
Ok(WriteResult::Id(id))
}
@@ -402,14 +400,13 @@ async fn execute_single_write(
if *existing_chunk_id != 0 {
return Ok(WriteResult::Id(*existing_chunk_id));
}
- let id = sqlx::query(
- "INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)",
- )
- .bind(file_path.as_str())
- .bind(ts)
- .execute(&mut **conn)
- .await?
- .last_insert_rowid();
+ let id =
+ sqlx::query("INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)")
+ .bind(file_path.as_str())
+ .bind(ts)
+ .execute(&mut **conn)
+ .await?
+ .last_insert_rowid();
return Ok(WriteResult::Id(id));
}
@@ -418,14 +415,13 @@ async fn execute_single_write(
if *existing_chunk_id != 0 {
return Ok(WriteResult::Id(*existing_chunk_id));
}
- let id = sqlx::query(
- "INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)",
- )
- .bind(file_path.as_str())
- .bind(ts)
- .execute(&mut **conn)
- .await?
- .last_insert_rowid();
+ let id =
+ sqlx::query("INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)")
+ .bind(file_path.as_str())
+ .bind(ts)
+ .execute(&mut **conn)
+ .await?
+ .last_insert_rowid();
return Ok(WriteResult::Id(id));
}
@@ -433,14 +429,12 @@ async fn execute_single_write(
let audio_chunk_id = if *existing_chunk_id != 0 {
*existing_chunk_id
} else {
- sqlx::query(
- "INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)",
- )
- .bind(file_path.as_str())
- .bind(ts)
- .execute(&mut **conn)
- .await?
- .last_insert_rowid()
+ sqlx::query("INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)")
+ .bind(file_path.as_str())
+ .bind(ts)
+ .execute(&mut **conn)
+ .await?
+ .last_insert_rowid()
};
// Insert transcription
@@ -517,9 +511,11 @@ async fn execute_single_write(
.last_insert_rowid();
// Insert OCR text in same transaction
- if let (Some(text), Some(text_json), Some(engine)) =
- (ocr_text.as_deref(), ocr_text_json.as_deref(), ocr_engine.as_deref())
- {
+ if let (Some(text), Some(text_json), Some(engine)) = (
+ ocr_text.as_deref(),
+ ocr_text_json.as_deref(),
+ ocr_engine.as_deref(),
+ ) {
let text_length = text.len() as i64;
sqlx::query(
"INSERT INTO ocr_text (frame_id, text, text_json, ocr_engine, text_length) VALUES (?1, ?2, ?3, ?4, ?5)",
@@ -820,11 +816,10 @@ mod tests {
}
// Verify transcription is linked to chunk
- let row: (i64,) =
- sqlx::query_as("SELECT audio_chunk_id FROM audio_transcriptions LIMIT 1")
- .fetch_one(&pool)
- .await
- .unwrap();
+ let row: (i64,) = sqlx::query_as("SELECT audio_chunk_id FROM audio_transcriptions LIMIT 1")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
assert_eq!(row.0, chunk_id);
}
diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
index d1699ab81..e65b02bc8 100644
--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
@@ -1011,9 +1011,9 @@ async fn main() -> anyhow::Result<()> {
.map(|detector| start_meeting_watcher(detector.clone()));
// Persist meeting state transitions to DB (smart mode only)
- let _meeting_persister_handle = meeting_detector
- .as_ref()
- .map(|detector| start_meeting_persister(detector.clone(), db.clone(), manual_meeting.clone()));
+ let _meeting_persister_handle = meeting_detector.as_ref().map(|detector| {
+ start_meeting_persister(detector.clone(), db.clone(), manual_meeting.clone())
+ });
// Bridge calendar events from event bus into meeting detector
let _calendar_bridge_handle = meeting_detector
diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rs
index c7aaa4372..235904f25 100644
--- a/crates/screenpipe-engine/src/cli/mod.rs
+++ b/crates/screenpipe-engine/src/cli/mod.rs
@@ -53,7 +53,9 @@ fn cli_engine_to_str(engine: &CliAudioTranscriptionEngine) -> &'static str {
CliAudioTranscriptionEngine::WhisperLargeV3 => "whisper-large",
CliAudioTranscriptionEngine::WhisperLargeV3Quantized => "whisper-large-quantized",
CliAudioTranscriptionEngine::WhisperLargeV3Turbo => "whisper-large-v3-turbo",
- CliAudioTranscriptionEngine::WhisperLargeV3TurboQuantized => "whisper-large-v3-turbo-quantized",
+ CliAudioTranscriptionEngine::WhisperLargeV3TurboQuantized => {
+ "whisper-large-v3-turbo-quantized"
+ }
CliAudioTranscriptionEngine::OpenAICompatible => "openai-compatible",
CliAudioTranscriptionEngine::Qwen3Asr => "qwen3-asr",
CliAudioTranscriptionEngine::Disabled => "disabled",
@@ -362,7 +364,11 @@ impl RecordArgs {
ignored_windows: self.ignored_windows.clone(),
included_windows: self.included_windows.clone(),
ignored_urls: self.ignored_urls.clone(),
- languages: self.language.iter().map(|l| l.as_lang_code().to_string()).collect(),
+ languages: self
+ .language
+ .iter()
+ .map(|l| l.as_lang_code().to_string())
+ .collect(),
deepgram_api_key: self.deepgram_api_key.clone().unwrap_or_default(),
video_quality: self.video_quality.clone(),
analytics_enabled: !self.disable_telemetry,
diff --git a/crates/screenpipe-engine/src/cli/pipe.rs b/crates/screenpipe-engine/src/cli/pipe.rs
index a26ea92d9..2724f7f56 100644
--- a/crates/screenpipe-engine/src/cli/pipe.rs
+++ b/crates/screenpipe-engine/src/cli/pipe.rs
@@ -138,8 +138,7 @@ pub async fn handle_pipe_command(command: &PipeCommand) -> anyhow::Result<()> {
/// Get the API base URL from env or default.
fn api_base_url() -> String {
- std::env::var("SCREENPIPE_API_BASE_URL")
- .unwrap_or_else(|_| "https://screenpi.pe".to_string())
+ std::env::var("SCREENPIPE_API_BASE_URL").unwrap_or_else(|_| "https://screenpi.pe".to_string())
}
/// Get the auth token from SCREENPIPE_API_KEY env var or ~/.screenpipe/auth.json.
@@ -162,10 +161,7 @@ fn get_auth_token() -> Option<String> {
}
/// Publish a local pipe to the registry.
-async fn handle_publish_command(
- name: &str,
- pipes_dir: &std::path::Path,
-) -> anyhow::Result<()> {
+async fn handle_publish_command(name: &str, pipes_dir: &std::path::Path) -> anyhow::Result<()> {
let pipe_dir = pipes_dir.join(name);
let pipe_md_path = pipe_dir.join("pipe.md");
@@ -243,7 +239,14 @@ async fn handle_publish_command(
}
/// Parse YAML frontmatter from pipe.md content.
-fn parse_frontmatter(content: &str) -> (Option<String>, Option<String>, Option<String>, Option<String>) {
+fn parse_frontmatter(
+ content: &str,
+) -> (
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+) {
let trimmed = content.trim_start();
if !trimmed.starts_with("---") {
return (None, None, None, None);
@@ -305,10 +308,7 @@ async fn handle_search_command(query: &str) -> anyhow::Result<()> {
println!("{}", "-".repeat(95));
for pipe in pipes {
let slug = pipe.get("slug").and_then(|v| v.as_str()).unwrap_or("?");
- let category = pipe
- .get("category")
- .and_then(|v| v.as_str())
- .unwrap_or("-");
+ let category = pipe.get("category").and_then(|v| v.as_str()).unwrap_or("-");
let installs = pipe
.get("install_count")
.or_else(|| pipe.get("installs"))
@@ -361,10 +361,7 @@ async fn handle_info_command(slug: &str) -> anyhow::Result<()> {
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("-");
- let category = pipe
- .get("category")
- .and_then(|v| v.as_str())
- .unwrap_or("-");
+ let category = pipe.get("category").and_then(|v| v.as_str()).unwrap_or("-");
let installs = pipe
.get("install_count")
.or_else(|| pipe.get("installs"))
@@ -374,10 +371,7 @@ async fn handle_info_command(slug: &str) -> anyhow::Result<()> {
.get("average_rating")
.or_else(|| pipe.get("rating"))
.and_then(|v| v.as_f64());
- let author = pipe
- .get("author")
- .and_then(|v| v.as_str())
- .unwrap_or("-");
+ let author = pipe.get("author").and_then(|v| v.as_str()).unwrap_or("-");
println!("{}", title);
println!("{}", "=".repeat(title.len()));
@@ -437,10 +431,7 @@ async fn handle_status_command(slug: &str) -> anyhow::Result<()> {
let pipe = body.get("data").unwrap_or(&body);
let title = pipe.get("title").and_then(|v| v.as_str()).unwrap_or(slug);
- let version = pipe
- .get("version")
- .and_then(|v| v.as_str())
- .unwrap_or("-");
+ let version = pipe.get("version").and_then(|v| v.as_str()).unwrap_or("-");
let review_status = pipe
.get("review_status")
.and_then(|v| v.as_str())
diff --git a/crates/screenpipe-engine/src/power/mod.rs b/crates/screenpipe-engine/src/power/mod.rs
index 11cfafa19..c0406393d 100644
--- a/crates/screenpipe-engine/src/power/mod.rs
+++ b/crates/screenpipe-engine/src/power/mod.rs
@@ -21,6 +21,8 @@ pub mod monitor;
pub mod profile;
// Re-export the public API at the module level
-pub use manager::{start_power_manager, start_power_manager_with_pref, PowerManagerHandle, PowerStatus};
+pub use manager::{
+ start_power_manager, start_power_manager_with_pref, PowerManagerHandle, PowerStatus,
+};
pub use monitor::{PowerState, ThermalState};
pub use profile::{PowerMode, PowerProfile, ProfileName};
diff --git a/crates/screenpipe-engine/src/recording_config.rs b/crates/screenpipe-engine/src/recording_config.rs
index 8b9e42097..3f679d243 100644
--- a/crates/screenpipe-engine/src/recording_config.rs
+++ b/crates/screenpipe-engine/src/recording_config.rs
@@ -102,8 +102,7 @@ impl RecordingConfig {
data_dir: std::path::PathBuf,
audio_engine_override: Option<&str>,
) -> Self {
- let engine_str = audio_engine_override
- .unwrap_or(&settings.audio_transcription_engine);
+ let engine_str = audio_engine_override.unwrap_or(&settings.audio_transcription_engine);
Self {
audio_chunk_duration: settings.audio_chunk_duration.max(0) as u64,
diff --git a/crates/screenpipe-engine/src/resource_monitor.rs b/crates/screenpipe-engine/src/resource_monitor.rs
index 4b96fb00a..77211d657 100644
--- a/crates/screenpipe-engine/src/resource_monitor.rs
+++ b/crates/screenpipe-engine/src/resource_monitor.rs
@@ -67,7 +67,13 @@ fn detect_gpus() -> Vec<String> {
// Cap to 8 GPUs (more than enough) and truncate long names
gpus.into_iter()
.take(8)
- .map(|s| if s.len() > 200 { s[..200].to_string() } else { s })
+ .map(|s| {
+ if s.len() > 200 {
+ s[..200].to_string()
+ } else {
+ s
+ }
+ })
.collect()
}
@@ -210,11 +216,9 @@ fn detect_gpus_windows() -> Vec<String> {
}
// Fallback to wmic (older Windows)
- if let Some(output) = run_cmd_with_timeout(
- "wmic",
- &["path", "win32_VideoController", "get", "name"],
- 5,
- ) {
+ if let Some(output) =
+ run_cmd_with_timeout("wmic", &["path", "win32_VideoController", "get", "name"], 5)
+ {
return output
.lines()
.skip(1) // skip header "Name"
diff --git a/crates/screenpipe-engine/src/routes/data.rs b/crates/screenpipe-engine/src/routes/data.rs
index 7ea88ed87..d4d7790d4 100644
--- a/crates/screenpipe-engine/src/routes/data.rs
+++ b/crates/screenpipe-engine/src/routes/data.rs
@@ -157,7 +157,10 @@ pub(crate) async fn delete_device_data_handler(
info!(
"deleted device data for {}: frames={}, ocr={}, audio={}",
- payload.machine_id, result.frames_deleted, result.ocr_deleted, result.audio_transcriptions_deleted
+ payload.machine_id,
+ result.frames_deleted,
+ result.ocr_deleted,
+ result.audio_transcriptions_deleted
);
Ok(JsonResponse(DeleteTimeRangeResponse {
diff --git a/crates/screenpipe-engine/src/routes/frames.rs b/crates/screenpipe-engine/src/routes/frames.rs
index 4cba6b287..d2954e6a5 100644
--- a/crates/screenpipe-engine/src/routes/frames.rs
+++ b/crates/screenpipe-engine/src/routes/frames.rs
@@ -105,9 +105,18 @@ pub async fn get_frame_data(
// Synced frame from another device — no local file exists.
// Return metadata (OCR text, app/window context) instead of 410.
if file_path.starts_with("cloud://") {
- let ocr_text = state.db.get_frame_ocr_text_json(frame_id).await.ok().flatten();
+ let ocr_text = state
+ .db
+ .get_frame_ocr_text_json(frame_id)
+ .await
+ .ok()
+ .flatten();
let timestamp = state.db.get_frame_timestamp(frame_id).await.ok().flatten();
- let (acc_text, _) = state.db.get_frame_accessibility_data(frame_id).await.unwrap_or((None, None));
+ let (acc_text, _) = state
+ .db
+ .get_frame_accessibility_data(frame_id)
+ .await
+ .unwrap_or((None, None));
let metadata = json!({
"error": "Frame is on a remote device",
@@ -117,10 +126,7 @@ pub async fn get_frame_data(
"ocr_text": ocr_text,
"accessibility_text": acc_text,
});
- return Err((
- StatusCode::NOT_FOUND,
- JsonResponse(metadata),
- ));
+ return Err((StatusCode::NOT_FOUND, JsonResponse(metadata)));
}
if is_snapshot {
diff --git a/crates/screenpipe-engine/src/routes/meetings.rs b/crates/screenpipe-engine/src/routes/meetings.rs
index 9523c7d3a..396ea0a79 100644
--- a/crates/screenpipe-engine/src/routes/meetings.rs
+++ b/crates/screenpipe-engine/src/routes/meetings.rs
@@ -12,10 +12,10 @@ use oasgen::{oasgen, OaSchema};
use screenpipe_db::MeetingRecord;
use crate::server::AppState;
+use chrono::Utc;
use serde::Deserialize;
use serde_json::{json, Value};
use std::sync::Arc;
-use chrono::Utc;
#[derive(OaSchema, Deserialize, Debug)]
pub struct UpdateMeetingRequest {
@@ -164,7 +164,9 @@ pub(crate) async fn bulk_delete_meetings_handler(
Err(e) => {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": format!("failed to delete meeting {}: {}", id, e)})),
+ JsonResponse(
+ json!({"error": format!("failed to delete meeting {}: {}", id, e)}),
+ ),
));
}
}
@@ -247,9 +249,7 @@ pub(crate) async fn stop_meeting_handler(
)
})?;
- 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();
state.db.end_meeting(id, &now).await.map_err(|e| {
(
diff --git a/crates/screenpipe-engine/src/routes/memories.rs b/crates/screenpipe-engine/src/routes/memories.rs
index feb4764d9..0624c8b7d 100644
--- a/crates/screenpipe-engine/src/routes/memories.rs
+++ b/crates/screenpipe-engine/src/routes/memories.rs
@@ -246,16 +246,12 @@ pub(crate) async fn delete_memory_handler(
State(state): State<Arc<AppState>>,
Path(id): Path<i64>,
) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
- state
- .db
- .delete_memory(id)
- .await
- .map_err(|e| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": e.to_string()})),
- )
- })?;
+ state.db.delete_memory(id).await.map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
Ok(JsonResponse(json!({"ok": true})))
}
diff --git a/crates/screenpipe-engine/src/routes/mod.rs b/crates/screenpipe-engine/src/routes/mod.rs
index 65b924db6..9a2ad6209 100644
--- a/crates/screenpipe-engine/src/routes/mod.rs
+++ b/crates/screenpipe-engine/src/routes/mod.rs
@@ -11,6 +11,7 @@ pub mod frames;
pub mod health;
pub mod meetings;
pub mod memories;
+pub mod pipe_store;
pub mod power;
pub mod retranscribe;
pub mod search;
@@ -19,5 +20,4 @@ pub mod streaming;
pub mod time;
pub mod timezone;
pub mod vault;
-pub mod pipe_store;
pub mod websocket;
diff --git a/crates/screenpipe-engine/src/routes/pipe_store.rs b/crates/screenpipe-engine/src/routes/pipe_store.rs
index f30f416b0..41af7c029 100644
--- a/crates/screenpipe-engine/src/routes/pipe_store.rs
+++ b/crates/screenpipe-engine/src/routes/pipe_store.rs
@@ -27,8 +27,7 @@ static REGISTRY_CLIENT: Lazy<reqwest::Client> = Lazy::new(|| {
/// Base URL for the screenpipe registry API.
fn api_base_url() -> String {
- std::env::var("SCREENPIPE_API_BASE_URL")
- .unwrap_or_else(|_| "https://screenpi.pe".to_string())
+ std::env::var("SCREENPIPE_API_BASE_URL").unwrap_or_else(|_| "https://screenpi.pe".to_string())
}
/// Extract the Bearer token from the Authorization header.
@@ -137,10 +136,7 @@ pub async fn pipe_store_detail(headers: HeaderMap, Path(slug): Path<String>) ->
///
/// Unpublish a pipe from the registry. Requires auth (Bearer token).
/// Only the pipe's author can unpublish it.
-pub async fn pipe_store_unpublish(
- headers: HeaderMap,
- Path(slug): Path<String>,
-) -> Json<Value> {
+pub async fn pipe_store_unpublish(headers: HeaderMap, Path(slug): Path<String>) -> Json<Value> {
let token = match extract_auth_token(&headers) {
Some(t) => t,
None => return Json(json!({ "error": "authorization required" })),
@@ -150,12 +146,7 @@ pub async fn pipe_store_unpublish(
let client = &*REGISTRY_CLIENT;
let url = format!("{}/api/pipes/store/{}", base, slug);
- match client
- .delete(&url)
- .bearer_auth(&token)
- .send()
- .await
- {
+ match client.delete(&url).bearer_auth(&token).send().await {
Ok(resp) => match resp.json::<Value>().await {
Ok(resp_body) => Json(resp_body),
Err(e) => Json(json!({ "error": format!("failed to parse registry response: {}", e) })),
@@ -241,9 +232,7 @@ pub async fn pipe_store_install(
.and_then(|v| v.as_str())
{
Some(md) => md.to_string(),
- None => {
- return Json(json!({ "error": "pipe not found or missing source_md" }))
- }
+ None => return Json(json!({ "error": "pipe not found or missing source_md" })),
}
}
};
diff --git a/crates/screenpipe-engine/src/snapshot_compaction.rs b/crates/screenpipe-engine/src/snapshot_compaction.rs
index 8cddae5d3..2f681e30c 100644
--- a/crates/screenpipe-engine/src/snapshot_compaction.rs
+++ b/crates/screenpipe-engine/src/snapshot_compaction.rs
@@ -277,7 +277,10 @@ async fn compact_chunk(
for (frame_id, snapshot_path, _) in frames {
let jpeg_path = Path::new(snapshot_path);
if !jpeg_path.exists() {
- debug!("snapshot file missing, clearing DB pointer: {}", snapshot_path);
+ debug!(
+ "snapshot file missing, clearing DB pointer: {}",
+ snapshot_path
+ );
let _ = sqlx::query("UPDATE frames SET snapshot_path = NULL WHERE id = ?")
.bind(frame_id)
.execute(&db.pool)
diff --git a/crates/screenpipe-engine/src/sync_provider.rs b/crates/screenpipe-engine/src/sync_provider.rs
index b797ab078..798cc40fb 100644
--- a/crates/screenpipe-engine/src/sync_provider.rs
+++ b/crates/screenpipe-engine/src/sync_provider.rs
@@ -344,16 +344,18 @@ impl ScreenpipeSyncProvider {
let accessibility_records: Vec<AccessibilityRecord> = records
.into_iter()
- .map(|(_, timestamp, app_name, window_name, text_content, browser_url)| {
- AccessibilityRecord {
- sync_id: Uuid::new_v4().to_string(),
- timestamp,
- app_name,
- window_name,
- text_content,
- browser_url,
- }
- })
+ .map(
+ |(_, timestamp, app_name, window_name, text_content, browser_url)| {
+ AccessibilityRecord {
+ sync_id: Uuid::new_v4().to_string(),
+ timestamp,
+ app_name,
+ window_name,
+ text_content,
+ browser_url,
+ }
+ },
+ )
.collect();
let chunk = SyncChunk {
@@ -671,14 +673,13 @@ impl ScreenpipeSyncProvider {
let mut imported_accessibility = 0;
for acc in &chunk.accessibility_records {
// Check if already imported via sync_id on frames
- let exists: Option<(i64,)> =
- sqlx::query_as("SELECT 1 FROM frames WHERE sync_id = ?")
- .bind(&acc.sync_id)
- .fetch_optional(pool)
- .await
- .map_err(|e| {
- SyncError::Database(format!("failed to check accessibility frame: {}", e))
- })?;
+ let exists: Option<(i64,)> = sqlx::query_as("SELECT 1 FROM frames WHERE sync_id = ?")
+ .bind(&acc.sync_id)
+ .fetch_optional(pool)
+ .await
+ .map_err(|e| {
+ SyncError::Database(format!("failed to check accessibility frame: {}", e))
+ })?;
if exists.is_some() {
skipped += 1;
@@ -805,14 +806,17 @@ impl ScreenpipeSyncProvider {
.mark_synced(table, &now, time_start, time_end)
.await
.map_err(|e| {
- SyncError::Database(format!("failed to mark {} synced: {}",
+ SyncError::Database(format!(
+ "failed to mark {} synced: {}",
match blob_type {
BlobType::Ocr => "frames",
BlobType::Transcripts => "transcriptions",
BlobType::Accessibility => "accessibility",
BlobType::Input => "ui_events",
_ => "unknown",
- }, e))
+ },
+ e
+ ))
})?;
Ok(())
diff --git a/crates/screenpipe-engine/src/ui_recorder.rs b/crates/screenpipe-engine/src/ui_recorder.rs
index 5554fa773..f1d45cb78 100644
--- a/crates/screenpipe-engine/src/ui_recorder.rs
+++ b/crates/screenpipe-engine/src/ui_recorder.rs
@@ -366,7 +366,6 @@ pub async fn start_ui_recording(
})
}
-
// Dead code below removed: TreeWalkerMetrics, run_tree_walker, constants.
// Tree walker is disabled — paired_capture.rs handles accessibility capture.
// Keeping this comment as a tombstone for git blame.
diff --git a/crates/screenpipe-screen/src/capture_screenshot_by_window.rs b/crates/screenpipe-screen/src/capture_screenshot_by_window.rs
index e32ea8c41..f0867937a 100644
--- a/crates/screenpipe-screen/src/capture_screenshot_by_window.rs
+++ b/crates/screenpipe-screen/src/capture_screenshot_by_window.rs
@@ -253,6 +253,12 @@ impl WindowFilters {
return false;
}
+ // Check if window title suggests a blocked URL (catches streaming sites
+ // like DAZN/Netflix where URL detection only works for focused windows)
+ if self.is_title_suggesting_blocked_url(title) {
+ return false;
+ }
+
// If include list is set, only allow windows that match it
if !self.include_set.is_empty() {
return self