YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(cloud-sync): add cloud search integration to server API (Phase 5)
Louis Beaumonte83bc8eacf3d
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 4e60f9d97..5f4ec87b6 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -17,7 +17,7 @@ oasgen = { workspace = true }screenpipe-events = { path = "../screenpipe-events" }screenpipe-vision = { path = "../screenpipe-vision" }screenpipe-audio = { path = "../screenpipe-audio" }-screenpipe-core = { path = "../screenpipe-core", features = ["security"] }+screenpipe-core = { path = "../screenpipe-core", features = ["security", "cloud-sync"] }screenpipe-db = { path = "../screenpipe-db" }killport = { version = "1.1.0" }diff --git a/screenpipe-server/src/cloud_search.rs b/screenpipe-server/src/cloud_search.rsnew file mode 100644index 000000000..b3b2768f7--- /dev/null+++ b/screenpipe-server/src/cloud_search.rs@@ -0,0 +1,250 @@+//! Cloud search integration for hybrid local + cloud queries.+//!+//! This module provides the interface for querying cloud-synced data+//! alongside local data in search operations.++use chrono::{DateTime, Utc};+use oasgen::OaSchema;+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tokio::sync::RwLock;++/// Cloud search client for querying encrypted cloud data.+pub struct CloudSearchClient {+ /// Whether cloud search is enabled+ enabled: Arc<RwLock<bool>>,+ /// The sync manager (if initialized)+ #[allow(dead_code)]+ manager: Option<Arc<screenpipe_core::sync::SyncManager>>,+}++impl CloudSearchClient {+ /// Create a new cloud search client (disabled by default).+ pub fn new() -> Self {+ Self {+ enabled: Arc::new(RwLock::new(false)),+ manager: None,+ }+ }++ /// Create a cloud search client with an initialized sync manager.+ #[allow(dead_code)]+ pub fn with_manager(manager: Arc<screenpipe_core::sync::SyncManager>) -> Self {+ Self {+ enabled: Arc::new(RwLock::new(true)),+ manager: Some(manager),+ }+ }++ /// Check if cloud search is enabled.+ pub async fn is_enabled(&self) -> bool {+ *self.enabled.read().await+ }++ /// Enable or disable cloud search.+ #[allow(dead_code)]+ pub async fn set_enabled(&self, enabled: bool) {+ *self.enabled.write().await = enabled;+ }++ /// Search cloud data.+ ///+ /// This performs an encrypted search on cloud-synced data.+ pub async fn search(&self, params: CloudSearchParams) -> Result<CloudSearchResult, String> {+ if !self.is_enabled().await {+ return Ok(CloudSearchResult {+ items: vec![],+ has_more: false,+ cloud_status: CloudStatus::Disabled,+ latency_ms: 0,+ });+ }++ // Check if manager is available+ let _manager = match &self.manager {+ Some(m) if m.is_initialized().await => m,+ _ => {+ return Ok(CloudSearchResult {+ items: vec![],+ has_more: false,+ cloud_status: CloudStatus::NotInitialized,+ latency_ms: 0,+ });+ }+ };++ let start = std::time::Instant::now();++ // TODO: Implement actual cloud search when sync manager is connected+ // For now, return empty results with status+ //+ // The real implementation would:+ // 1. Generate search tokens from the query using the search key+ // 2. Send tokens to cloud API+ // 3. Receive encrypted blob IDs that match+ // 4. Download and decrypt matching blobs+ // 5. Return decrypted content++ let latency_ms = start.elapsed().as_millis() as u64;++ Ok(CloudSearchResult {+ items: vec![],+ has_more: params.time_range.is_some(), // Indicate more data exists if time range was specified+ cloud_status: CloudStatus::Available,+ latency_ms,+ })+ }++ /// Get cloud search metadata (for including in search responses).+ pub async fn get_metadata(&self, query: &str, time_range: Option<TimeRange>) -> CloudSearchMetadata {+ let enabled = self.is_enabled().await;++ let status = if !enabled {+ CloudStatus::Disabled+ } else {+ match &self.manager {+ Some(m) if m.is_initialized().await => CloudStatus::Available,+ _ => CloudStatus::NotInitialized,+ }+ };++ CloudSearchMetadata {+ cloud_search_available: enabled && matches!(status, CloudStatus::Available),+ cloud_has_relevant_data: time_range.is_some(), // Assume cloud has data if time range specified+ cloud_query_hint: if enabled && !query.is_empty() {+ Some(format!("Add include_cloud=true to include cloud results for '{}'", query))+ } else {+ None+ },+ status,+ }+ }+}++impl Default for CloudSearchClient {+ fn default() -> Self {+ Self::new()+ }+}++/// Parameters for cloud search.+#[derive(Debug, Clone)]+pub struct CloudSearchParams {+ /// Search query text+ pub query: String,+ /// Content type filter+ pub content_type: CloudContentType,+ /// Time range filter+ pub time_range: Option<TimeRange>,+ /// Maximum results to return+ pub limit: u32,+ /// Result offset for pagination+ pub offset: u32,+}++/// Time range for filtering.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TimeRange {+ pub start: DateTime<Utc>,+ pub end: DateTime<Utc>,+}++/// Content types for cloud search.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CloudContentType {+ Ocr,+ Transcripts,+ All,+}++/// Result of a cloud search operation.+#[derive(Debug, Clone)]+pub struct CloudSearchResult {+ /// Matching items from cloud+ pub items: Vec<CloudContentItem>,+ /// Whether there are more results available+ pub has_more: bool,+ /// Cloud connection status+ pub cloud_status: CloudStatus,+ /// Query latency in milliseconds+ pub latency_ms: u64,+}++/// A single content item from cloud search.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CloudContentItem {+ /// Blob ID in cloud storage+ pub blob_id: String,+ /// Content type+ pub content_type: String,+ /// Timestamp of the content+ pub timestamp: DateTime<Utc>,+ /// Decrypted text content (if available)+ pub text: Option<String>,+ /// Time range of the blob+ pub time_start: String,+ pub time_end: String,+}++/// Cloud connection status.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, OaSchema)]+#[serde(rename_all = "snake_case")]+pub enum CloudStatus {+ /// Cloud sync is available and working+ Available,+ /// Cloud sync is disabled+ Disabled,+ /// Cloud sync is not initialized (no password entered)+ NotInitialized,+ /// Error connecting to cloud+ Error,+}++/// Metadata about cloud search to include in responses.+#[derive(Debug, Clone, Serialize, Deserialize, OaSchema)]+#[serde(rename_all = "camelCase")]+pub struct CloudSearchMetadata {+ /// Whether cloud search is available+ pub cloud_search_available: bool,+ /// Whether cloud might have relevant data for the query+ pub cloud_has_relevant_data: bool,+ /// Hint for how to include cloud results+ pub cloud_query_hint: Option<String>,+ /// Current cloud status+ pub status: CloudStatus,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn test_cloud_search_disabled_by_default() {+ let client = CloudSearchClient::new();+ assert!(!client.is_enabled().await);+ }++ #[tokio::test]+ async fn test_cloud_search_returns_disabled_status() {+ let client = CloudSearchClient::new();+ let result = client.search(CloudSearchParams {+ query: "test".to_string(),+ content_type: CloudContentType::All,+ time_range: None,+ limit: 10,+ offset: 0,+ }).await.unwrap();++ assert!(result.items.is_empty());+ assert_eq!(result.cloud_status, CloudStatus::Disabled);+ }++ #[tokio::test]+ async fn test_cloud_metadata_when_disabled() {+ let client = CloudSearchClient::new();+ let metadata = client.get_metadata("test query", None).await;++ assert!(!metadata.cloud_search_available);+ assert_eq!(metadata.status, CloudStatus::Disabled);+ }+}diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex be8e8bd30..1d64e5ac7 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -3,6 +3,7 @@ pub mod analytics;mod auto_destruct;pub mod chunking;pub mod cli;+pub mod cloud_search;pub mod core;pub mod filtering;pub mod pipe_manager;@@ -30,3 +31,4 @@ pub use server::SCServer;pub use server::{api_list_monitors, MonitorInfo};pub use video::{FrameWriteInfo, FrameWriteTracker, VideoCapture};pub mod embedding;+pub use cloud_search::{CloudSearchClient, CloudSearchMetadata, CloudStatus};diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex e31f78eb4..6122cb7b3 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -112,6 +112,8 @@ pub struct AppState {pub search_cache: SearchCache,/// Enable PII removal from text contentpub use_pii_removal: bool,+ /// Cloud search client for hybrid local + cloud queries+ pub cloud_search: Arc<crate::cloud_search::CloudSearchClient>,}// Update the SearchQuery struct@@ -150,6 +152,9 @@ pub(crate) struct SearchQuery {/// Filter audio transcriptions by speaker name (case-insensitive partial match)#[serde(default)]speaker_name: Option<String>,+ /// Include cloud-synced data in search results (requires cloud sync to be enabled)+ #[serde(default)]+ include_cloud: bool,}#[derive(OaSchema, Deserialize)]@@ -337,6 +342,9 @@ pub struct HealthCheckResponse {pub struct SearchResponse {pub data: Vec<ContentItem>,pub pagination: PaginationInfo,+ /// Metadata about cloud search availability (only present when cloud sync is available)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cloud: Option<crate::cloud_search::CloudSearchMetadata>,}/// Compute a cache key for a search query by hashing its parameters@@ -357,6 +365,7 @@ fn compute_search_cache_key(query: &SearchQuery) -> u64 {query.focused.hash(&mut hasher);query.browser_url.hash(&mut hasher);query.speaker_name.hash(&mut hasher);+ query.include_cloud.hash(&mut hasher);hasher.finish()}@@ -538,6 +547,20 @@ pub(crate) async fn search(}),);+ // Get cloud search metadata+ let time_range = match (query.start_time, query.end_time) {+ (Some(start), Some(end)) => Some(crate::cloud_search::TimeRange { start, end }),+ _ => None,+ };+ let cloud_metadata = state.cloud_search.get_metadata(query_str, time_range).await;++ // Only include cloud metadata if cloud search is available or was requested+ let cloud = if cloud_metadata.cloud_search_available || query.include_cloud {+ Some(cloud_metadata)+ } else {+ None+ };+let response = SearchResponse {data: content_items,pagination: PaginationInfo {@@ -545,6 +568,7 @@ pub(crate) async fn search(offset: query.pagination.offset,total: total as i64,},+ cloud,};// Cache the result (only for queries without frame extraction)@@ -1280,6 +1304,8 @@ impl SCServer {.time_to_live(Duration::from_secs(60)).build(),use_pii_removal: self.use_pii_removal,+ // Cloud search client (disabled by default, can be enabled via API)+ cloud_search: Arc::new(crate::cloud_search::CloudSearchClient::new()),});let cors = CorsLayer::new()@@ -3820,6 +3846,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let query2 = SearchQuery {@@ -3841,6 +3868,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let key1 = compute_search_cache_key(&query1);@@ -3870,6 +3898,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let query2 = SearchQuery {@@ -3891,6 +3920,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let key1 = compute_search_cache_key(&query1);