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

Bump app to v2.0.206

Louis Beaumont5dbc0030791b
diff --git a/screenpipe-app-tauri/lib/utils/tauri.ts b/screenpipe-app-tauri/lib/utils/tauri.ts
index d256e0883..3b70b8978 100644
--- a/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -300,6 +300,8 @@ async removeSyncDevice(deviceId: string) : Promise<Result<null, string>> {
},
/**
* Initialize sync with password.
+ * This initializes both the local SyncManager (for device queries) and
+ * the server's SyncService (for actual data sync).
*/
async initSync(password: string) : Promise<Result<boolean, string>> {
try {
@@ -310,7 +312,7 @@ async initSync(password: string) : Promise<Result<boolean, string>> {
}
},
/**
- * Lock sync (clear keys from memory).
+ * Lock sync (clear keys from memory and stop server sync service).
*/
async lockSync() : Promise<Result<null, string>> {
try {
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 1ee50bc81..b83ac85ee 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -6733,7 +6733,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "screenpipe-app"
-version = "2.0.203"
+version = "2.0.206"
dependencies = [
"anyhow",
"async-stream",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 40d4f3256..cdedd90c4 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.0.204"
+version = "2.0.206"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/src/sync.rs b/screenpipe-app-tauri/src-tauri/src/sync.rs
index 22c35b0c8..355291841 100644
--- a/screenpipe-app-tauri/src-tauri/src/sync.rs
+++ b/screenpipe-app-tauri/src-tauri/src/sync.rs
@@ -293,6 +293,8 @@ pub async fn remove_sync_device(
}
/// Initialize sync with password.
+/// This initializes both the local SyncManager (for device queries) and
+/// the server's SyncService (for actual data sync).
#[tauri::command]
#[specta::specta]
pub async fn init_sync(
@@ -315,10 +317,10 @@ pub async fn init_sync(
let device_os = std::env::consts::OS.to_string();
- // Create sync client config
- let config = SyncClientConfig::new(token, state.machine_id.clone(), device_name, device_os);
+ // Create sync client config for local manager (used for device queries)
+ let config = SyncClientConfig::new(token.clone(), state.machine_id.clone(), device_name, device_os);
- // Create sync manager
+ // Create local sync manager
let manager = SyncManager::new(config).map_err(|e| format!("failed to create sync manager: {}", e))?;
// Initialize with password (this will either create new keys or derive from existing)
@@ -327,7 +329,7 @@ pub async fn init_sync(
.await
.map_err(|e| format!("failed to initialize sync: {}", e))?;
- // Store the manager
+ // Store the local manager
*state.manager.write().await = Some(Arc::new(manager));
*state.enabled.write().await = true;
@@ -336,18 +338,69 @@ pub async fn init_sync(
if is_new_user { "new" } else { "existing" }
);
+ // Now initialize the server's sync service
+ let client = reqwest::Client::new();
+ let init_request = serde_json::json!({
+ "token": token,
+ "password": password,
+ "machine_id": state.machine_id.clone(),
+ "sync_interval_secs": 300
+ });
+
+ match client
+ .post("http://localhost:3030/sync/init")
+ .json(&init_request)
+ .send()
+ .await
+ {
+ Ok(response) if response.status().is_success() => {
+ info!("server sync service initialized");
+ }
+ Ok(response) if response.status().as_u16() == 409 => {
+ // Already initialized - that's fine
+ debug!("server sync service already initialized");
+ }
+ Ok(response) => {
+ let error_text = response.text().await.unwrap_or_else(|_| "unknown error".to_string());
+ // Log but don't fail - local manager is still useful
+ debug!("failed to initialize server sync: {}", error_text);
+ }
+ Err(e) => {
+ // Log but don't fail - server might not be running yet
+ debug!("failed to connect to server for sync init: {}", e);
+ }
+ }
+
Ok(is_new_user)
}
-/// Lock sync (clear keys from memory).
+/// Lock sync (clear keys from memory and stop server sync service).
#[tauri::command]
#[specta::specta]
pub async fn lock_sync(state: State<'_, SyncState>) -> Result<(), String> {
+ // Lock local manager
let manager_guard = state.manager.read().await;
if let Some(manager) = manager_guard.as_ref() {
manager.lock().await;
}
*state.enabled.write().await = false;
+
+ // Lock server sync service
+ let client = reqwest::Client::new();
+ match client
+ .post("http://localhost:3030/sync/lock")
+ .send()
+ .await
+ {
+ Ok(response) if response.status().is_success() => {
+ info!("server sync service locked");
+ }
+ Ok(_) | Err(_) => {
+ // Server might not be running or sync not initialized - that's fine
+ debug!("could not lock server sync (may not be running)");
+ }
+ }
+
Ok(())
}
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index c92467fd3..60031bb8d 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -10,6 +10,7 @@ pub mod pipe_manager;
mod resource_monitor;
mod server;
pub mod sleep_monitor;
+mod sync_api;
pub mod sync_provider;
pub mod text_embeds;
pub mod ui_events_api;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 0899f6fc8..86081a090 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -51,6 +51,8 @@ use screenpipe_core::pii_removal::detect_pii_regions;
use screenpipe_core::sync::SyncServiceHandle;
use tracing::{debug, error, info};
+use crate::sync_api::{self, SyncState};
+
use screenpipe_vision::monitor::{get_monitor_by_id, list_monitors};
use screenpipe_vision::OcrEngine;
use serde::{Deserialize, Deserializer, Serialize};
@@ -115,8 +117,10 @@ pub struct AppState {
pub use_pii_removal: bool,
/// Cloud search client for hybrid local + cloud queries
pub cloud_search: Arc<crate::cloud_search::CloudSearchClient>,
- /// Cloud sync service handle (if enabled)
+ /// Cloud sync service handle (if enabled via CLI)
pub sync_handle: Option<Arc<SyncServiceHandle>>,
+ /// Runtime sync state (initialized via /sync/init endpoint)
+ pub sync_state: SyncState,
}
// Update the SearchQuery struct
@@ -1368,8 +1372,10 @@ impl SCServer {
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()),
- // Cloud sync service handle
+ // Cloud sync service handle (from CLI)
sync_handle: self.sync_handle.clone(),
+ // Runtime sync state (initialized via /sync/init)
+ sync_state: sync_api::new_sync_state(),
});
let cors = CorsLayer::new()
@@ -1431,8 +1437,11 @@ impl SCServer {
.route("/ui-events", get(ui_events_search_handler))
.route("/ui-events/stats", get(ui_events_stats_handler))
// Cloud Sync API routes
- .route("/sync/status", get(sync_status_handler))
- .route("/sync/trigger", axum::routing::post(sync_trigger_handler))
+ .route("/sync/init", axum::routing::post(sync_api::sync_init))
+ .route("/sync/status", get(sync_api::sync_status))
+ .route("/sync/trigger", axum::routing::post(sync_api::sync_trigger))
+ .route("/sync/lock", axum::routing::post(sync_api::sync_lock))
+ .route("/sync/download", axum::routing::post(sync_api::sync_download))
// NOTE: websockerts and sse is not supported by openapi so we move it down here
.route("/stream/frames", get(stream_frames_handler))
.route("/ws/events", get(ws_events_handler))
@@ -4005,49 +4014,6 @@ struct MergeSpeakersRequest {
#[derive(Debug, OaSchema, Deserialize)]
pub struct PurgePipeRequest {}
-// ============================================================================
-// Cloud Sync Handlers
-// ============================================================================
-
-#[derive(Serialize)]
-struct SyncStatusResponse {
- enabled: bool,
- is_syncing: bool,
- last_sync: Option<String>,
- last_error: Option<String>,
-}
-
-async fn sync_status_handler(
- State(state): State<Arc<AppState>>,
-) -> Result<Json<SyncStatusResponse>, (StatusCode, Json<Value>)> {
- let enabled = state.sync_handle.is_some();
-
- Ok(Json(SyncStatusResponse {
- enabled,
- is_syncing: false, // TODO: Track this in AppState
- last_sync: None, // TODO: Track this in AppState
- last_error: None,
- }))
-}
-
-async fn sync_trigger_handler(
- State(state): State<Arc<AppState>>,
-) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
- match &state.sync_handle {
- Some(handle) => match handle.sync_now().await {
- Ok(_) => Ok(Json(json!({"success": true, "message": "sync triggered"}))),
- Err(e) => Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({"error": format!("failed to trigger sync: {}", e)})),
- )),
- },
- None => Err((
- StatusCode::BAD_REQUEST,
- Json(json!({"error": "sync not enabled"})),
- )),
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/screenpipe-server/src/sync_api.rs b/screenpipe-server/src/sync_api.rs
index b1e0406ca..a64a526dc 100644
--- a/screenpipe-server/src/sync_api.rs
+++ b/screenpipe-server/src/sync_api.rs
@@ -1,23 +1,59 @@
//! Sync API endpoints for cloud sync operations.
//!
//! These endpoints allow the Tauri app to:
+//! - Initialize sync at runtime with credentials
//! - Get pending (unsynced) data for upload
//! - Mark data as synced after upload
//! - Import data from other machines
+//! - Trigger sync and check status
use axum::{
extract::State,
http::StatusCode,
Json,
};
-use screenpipe_core::sync::{PendingBlob, SyncDataProvider};
+use screenpipe_core::sync::{
+ BlobType, PendingBlob, SyncClientConfig, SyncDataProvider, SyncManager, SyncService,
+ SyncServiceConfig, SyncServiceHandle,
+};
+use screenpipe_db::DatabaseManager;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
-use tracing::error;
+use tokio::sync::RwLock;
+use tracing::{debug, error, info};
use crate::server::AppState;
-use crate::sync_provider::{ScreenpipeSyncProvider, SyncChunk};
+use crate::sync_provider::ScreenpipeSyncProvider;
+pub use crate::sync_provider::SyncChunk;
+
+// ============================================================================
+// Runtime Sync State
+// ============================================================================
+
+/// Runtime sync state that can be initialized after server startup.
+pub struct SyncRuntimeState {
+ /// The sync manager for API operations
+ pub manager: Arc<SyncManager>,
+ /// The sync service handle for triggering syncs
+ pub service_handle: SyncServiceHandle,
+ /// Machine ID for this device
+ pub machine_id: String,
+ /// Whether sync is currently in progress
+ pub is_syncing: Arc<RwLock<bool>>,
+ /// Last sync timestamp
+ pub last_sync: Arc<RwLock<Option<String>>>,
+ /// Last sync error
+ pub last_error: Arc<RwLock<Option<String>>>,
+}
+
+/// Thread-safe container for optional runtime sync state
+pub type SyncState = Arc<RwLock<Option<SyncRuntimeState>>>;
+
+/// Create a new empty sync state container
+pub fn new_sync_state() -> SyncState {
+ Arc::new(RwLock::new(None))
+}
/// Request to get pending sync data.
#[derive(Debug, Deserialize)]
@@ -198,3 +234,358 @@ pub async fn import_chunk(
}
}
}
+
+// ============================================================================
+// Runtime Sync Initialization & Control Endpoints
+// ============================================================================
+
+/// Request to initialize sync at runtime.
+#[derive(Debug, Deserialize)]
+pub struct SyncInitRequest {
+ /// API token for cloud authentication
+ pub token: String,
+ /// Password for encryption key derivation
+ pub password: String,
+ /// Machine ID for this device (optional, will be generated if not provided)
+ pub machine_id: Option<String>,
+ /// Sync interval in seconds (optional, defaults to 300)
+ pub sync_interval_secs: Option<u64>,
+}
+
+/// Response from sync initialization.
+#[derive(Debug, Serialize)]
+pub struct SyncInitResponse {
+ pub success: bool,
+ pub is_new_user: bool,
+ pub machine_id: String,
+}
+
+/// Initialize sync at runtime with credentials.
+pub async fn sync_init(
+ State(state): State<Arc<AppState>>,
+ Json(request): Json<SyncInitRequest>,
+) -> Result<Json<SyncInitResponse>, (StatusCode, Json<Value>)> {
+ // Check if already initialized
+ {
+ let sync_state = state.sync_state.read().await;
+ if sync_state.is_some() {
+ return Err((
+ StatusCode::CONFLICT,
+ Json(json!({"error": "sync already initialized"})),
+ ));
+ }
+ }
+
+ // Generate or use provided machine ID
+ let machine_id = request.machine_id.unwrap_or_else(|| {
+ if let Ok(hostname) = hostname::get() {
+ let hostname_str = hostname.to_string_lossy();
+ format!("{:x}", md5::compute(hostname_str.as_bytes()))
+ } else {
+ uuid::Uuid::new_v4().to_string()
+ }
+ });
+
+ // Get device info
+ let device_name = hostname::get()
+ .map(|h| h.to_string_lossy().to_string())
+ .unwrap_or_else(|_| "Unknown".to_string());
+ let device_os = std::env::consts::OS.to_string();
+
+ // Create sync manager
+ let config = SyncClientConfig::new(
+ request.token.clone(),
+ machine_id.clone(),
+ device_name,
+ device_os,
+ );
+
+ let manager = SyncManager::new(config).map_err(|e| {
+ error!("failed to create sync manager: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({"error": format!("failed to create sync manager: {}", e)})),
+ )
+ })?;
+
+ // Initialize with password
+ let is_new_user = manager.initialize(&request.password).await.map_err(|e| {
+ error!("failed to initialize sync: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({"error": format!("failed to initialize sync: {}", e)})),
+ )
+ })?;
+
+ let manager = Arc::new(manager);
+
+ // Create sync data provider
+ let provider = Arc::new(ScreenpipeSyncProvider::new(
+ state.db.clone(),
+ machine_id.clone(),
+ ));
+
+ // Create sync service config
+ let service_config = SyncServiceConfig {
+ enabled: true,
+ sync_interval_secs: request.sync_interval_secs.unwrap_or(300),
+ sync_types: vec![BlobType::Ocr, BlobType::Transcripts],
+ max_blobs_per_cycle: 10,
+ sync_on_startup: true,
+ };
+
+ // Create and start service
+ let service = SyncService::new(manager.clone(), service_config, provider);
+ let (handle, mut event_rx) = service.start();
+
+ info!(
+ "sync initialized for {} user, machine_id: {}",
+ if is_new_user { "new" } else { "existing" },
+ machine_id
+ );
+
+ // Create runtime state
+ let runtime_state = SyncRuntimeState {
+ manager,
+ service_handle: handle,
+ machine_id: machine_id.clone(),
+ is_syncing: Arc::new(RwLock::new(false)),
+ last_sync: Arc::new(RwLock::new(None)),
+ last_error: Arc::new(RwLock::new(None)),
+ };
+
+ // Spawn event handler
+ let is_syncing = runtime_state.is_syncing.clone();
+ let last_sync = runtime_state.last_sync.clone();
+ let last_error = runtime_state.last_error.clone();
+
+ tokio::spawn(async move {
+ use screenpipe_core::sync::SyncEvent;
+ while let Some(event) = event_rx.recv().await {
+ match event {
+ SyncEvent::Started => {
+ info!("sync cycle started");
+ *is_syncing.write().await = true;
+ }
+ SyncEvent::Completed(report) => {
+ info!(
+ "sync cycle completed: {} blobs uploaded ({} bytes) in {:.2}s",
+ report.blobs_uploaded, report.bytes_uploaded, report.duration_secs
+ );
+ *is_syncing.write().await = false;
+ *last_sync.write().await = Some(chrono::Utc::now().to_rfc3339());
+ *last_error.write().await = None;
+ }
+ SyncEvent::Failed(err) => {
+ error!("sync cycle failed: {}", err);
+ *is_syncing.write().await = false;
+ *last_error.write().await = Some(err);
+ }
+ SyncEvent::Progress { uploaded, total, bytes_transferred } => {
+ debug!(
+ "sync progress: {}/{} blobs, {} bytes",
+ uploaded, total, bytes_transferred
+ );
+ }
+ SyncEvent::Stopped => {
+ info!("sync service stopped");
+ break;
+ }
+ }
+ }
+ });
+
+ // Store in app state
+ *state.sync_state.write().await = Some(runtime_state);
+
+ Ok(Json(SyncInitResponse {
+ success: true,
+ is_new_user,
+ machine_id,
+ }))
+}
+
+/// Response for sync status.
+#[derive(Debug, Serialize)]
+pub struct SyncStatusResponse {
+ pub enabled: bool,
+ pub is_syncing: bool,
+ pub last_sync: Option<String>,
+ pub last_error: Option<String>,
+ pub machine_id: Option<String>,
+}
+
+/// Get current sync status.
+pub async fn sync_status(
+ State(state): State<Arc<AppState>>,
+) -> Result<Json<SyncStatusResponse>, (StatusCode, Json<Value>)> {
+ let sync_state = state.sync_state.read().await;
+
+ match sync_state.as_ref() {
+ Some(runtime) => {
+ let is_syncing = *runtime.is_syncing.read().await;
+ let last_sync = runtime.last_sync.read().await.clone();
+ let last_error = runtime.last_error.read().await.clone();
+
+ Ok(Json(SyncStatusResponse {
+ enabled: true,
+ is_syncing,
+ last_sync,
+ last_error,
+ machine_id: Some(runtime.machine_id.clone()),
+ }))
+ }
+ None => Ok(Json(SyncStatusResponse {
+ enabled: false,
+ is_syncing: false,
+ last_sync: None,
+ last_error: None,
+ machine_id: None,
+ })),
+ }
+}
+
+/// Trigger an immediate sync.
+pub async fn sync_trigger(
+ State(state): State<Arc<AppState>>,
+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
+ let sync_state = state.sync_state.read().await;
+
+ match sync_state.as_ref() {
+ Some(runtime) => {
+ runtime.service_handle.sync_now().await.map_err(|e| {
+ error!("failed to trigger sync: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({"error": format!("failed to trigger sync: {}", e)})),
+ )
+ })?;
+ Ok(Json(json!({"success": true, "message": "sync triggered"})))
+ }
+ None => Err((
+ StatusCode::BAD_REQUEST,
+ Json(json!({"error": "sync not initialized"})),
+ )),
+ }
+}
+
+/// Lock sync (stop service and clear state).
+pub async fn sync_lock(
+ State(state): State<Arc<AppState>>,
+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
+ let mut sync_state = state.sync_state.write().await;
+
+ match sync_state.take() {
+ Some(runtime) => {
+ // Stop the service
+ if let Err(e) = runtime.service_handle.stop().await {
+ error!("failed to stop sync service: {}", e);
+ }
+ // Lock the manager (clear keys from memory)
+ runtime.manager.lock().await;
+ info!("sync locked and service stopped");
+ Ok(Json(json!({"success": true, "message": "sync locked"})))
+ }
+ None => Ok(Json(json!({"success": true, "message": "sync was not initialized"}))),
+ }
+}
+
+/// Request to download data from other devices.
+#[derive(Debug, Deserialize)]
+pub struct SyncDownloadRequest {
+ /// Time range in hours to download (default: 24)
+ #[serde(default = "default_hours")]
+ pub hours: u32,
+}
+
+fn default_hours() -> u32 {
+ 24
+}
+
+/// Response from download operation.
+#[derive(Debug, Serialize)]
+pub struct SyncDownloadResponse {
+ pub success: bool,
+ pub blobs_downloaded: usize,
+ pub records_imported: usize,
+}
+
+/// Download and import data from other devices.
+pub async fn sync_download(
+ State(state): State<Arc<AppState>>,
+ Json(request): Json<SyncDownloadRequest>,
+) -> Result<Json<SyncDownloadResponse>, (StatusCode, Json<Value>)> {
+ let sync_state = state.sync_state.read().await;
+
+ let runtime = sync_state.as_ref().ok_or_else(|| {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(json!({"error": "sync not initialized"})),
+ )
+ })?;
+
+ // Calculate time range
+ let end = chrono::Utc::now();
+ let start = end - chrono::Duration::hours(request.hours as i64);
+
+ // Download blobs from cloud
+ let blobs = runtime
+ .manager
+ .download_by_time_range(
+ Some(start.to_rfc3339()),
+ Some(end.to_rfc3339()),
+ None,
+ Some(100),
+ )
+ .await
+ .map_err(|e| {
+ error!("failed to download blobs: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({"error": format!("failed to download: {}", e)})),
+ )
+ })?;
+
+ let blobs_downloaded = blobs.len();
+ let mut records_imported = 0;
+
+ // Import each blob
+ let provider = ScreenpipeSyncProvider::new(state.db.clone(), runtime.machine_id.clone());
+
+ for blob in blobs {
+ // Deserialize the chunk
+ let chunk: SyncChunk = serde_json::from_slice(&blob.data).map_err(|e| {
+ error!("failed to deserialize chunk: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({"error": format!("failed to deserialize chunk: {}", e)})),
+ )
+ })?;
+
+ // Import it
+ match provider.import_chunk(&chunk).await {
+ Ok(result) => {
+ records_imported += result.imported_frames
+ + result.imported_ocr
+ + result.imported_transcriptions
+ + result.imported_accessibility
+ + result.imported_ui_events;
+ }
+ Err(e) => {
+ error!("failed to import chunk: {}", e);
+ // Continue with other chunks
+ }
+ }
+ }
+
+ info!(
+ "sync download complete: {} blobs, {} records imported",
+ blobs_downloaded, records_imported
+ );
+
+ Ok(Json(SyncDownloadResponse {
+ success: true,
+ blobs_downloaded,
+ records_imported,
+ }))
+}