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
fix(sync): connection sync self-initializes (no password); stop credential toggle from uploading screen data (#4469)
Louis Beaumont82501379ab05
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/auth_token.rs b/apps/screenpipe-app-tauri/src-tauri/src/auth_token.rsindex 4a7369cd0..dcbd5f145 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/auth_token.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/auth_token.rs@@ -36,6 +36,11 @@ use screenpipe_secrets::SecretStore;/// SecretStore row key for the cloud auth token.const AUTH_TOKEN_KEY: &str = "cloud.auth_token";+/// SecretStore row key for the cloud-sync master password. MUST match the+/// engine's `SYNC_MASTER_PASSWORD_KEY` in+/// `crates/screenpipe-engine/src/sync_api.rs` so the lazy engine init and the+/// app auto-start read the same value.+const SYNC_PASSWORD_KEY: &str = "sync.master_password";/// Magic header that marks an *encrypted* store.bin (so we never try to JSON/// parse / scrub it as plaintext).const STORE_MAGIC: &[u8; 8] = b"SPSTORE1";@@ -152,6 +157,37 @@ pub async fn load_cloud_token() -> Option<String> {load_token_at(&dir, read_encryption_key()).await}+/// Persist the cloud-sync master password to the encrypted SecretStore.+///+/// The SecretStore (`db.sqlite`) is ALWAYS keychain-encrypted, unlike+/// `store.bin` (only encrypted when the user enabled store encryption), so this+/// avoids keeping the password as a merely-base64 blob in `store.bin`.+pub async fn store_sync_password(password: &str) -> anyhow::Result<()> {+ let dir = screenpipe_core::paths::default_screenpipe_data_dir();+ let store = secret_store_at(&dir, write_encryption_key()?)+ .await+ .ok_or_else(|| anyhow::anyhow!("could not open secret store at {}", dir.display()))?;+ store.set(SYNC_PASSWORD_KEY, password.as_bytes()).await+}++/// Load the cloud-sync master password from the encrypted SecretStore.+pub async fn load_sync_password() -> Option<String> {+ let dir = screenpipe_core::paths::default_screenpipe_data_dir();+ let store = secret_store_at(&dir, read_encryption_key()).await?;+ let bytes = store.get(SYNC_PASSWORD_KEY).await.ok()??;+ String::from_utf8(bytes).ok().filter(|s| !s.is_empty())+}++/// Clear the cloud-sync master password from the SecretStore (on disable/lock).+/// Deleting a row needs no encryption key.+pub async fn clear_sync_password() -> anyhow::Result<()> {+ let dir = screenpipe_core::paths::default_screenpipe_data_dir();+ let store = secret_store_at(&dir, None)+ .await+ .ok_or_else(|| anyhow::anyhow!("could not open secret store at {}", dir.display()))?;+ store.delete(SYNC_PASSWORD_KEY).await+}+/// One-time migration (#3943): move the cloud token out of the plaintext files/// into the SecretStore, seed the cache, then scrub the plaintext copies./// Idempotent and best-effort — safe to call on every startup.diff --git a/apps/screenpipe-app-tauri/src-tauri/src/sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/sync.rsindex 9c005790c..371638df4 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/sync.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/sync.rs@@ -397,10 +397,16 @@ pub async fn init_sync(if is_new_user { "new" } else { "existing" });- // Save password to persistent store for auto-init on restart+ // Persist the master password to the encrypted SecretStore (always+ // keychain-encrypted) rather than as base64 in store.bin. CloudSyncSettings+ // keeps only the enabled flag for auto-start; the password lives in the+ // secret store under the same key the engine reads.+ if let Err(e) = crate::auth_token::store_sync_password(&password).await {+ warn!("failed to persist sync password to secret store: {}", e);+ }let cloud_settings = CloudSyncSettingsStore {enabled: true,- encrypted_password: BASE64.encode(password.as_bytes()),+ encrypted_password: String::new(),};if let Err(e) = cloud_settings.save(&app) {warn!("failed to save cloud sync settings: {}", e);@@ -458,7 +464,9 @@ pub async fn lock_sync(app: AppHandle, state: State<'_, SyncState>) -> Result<()}*state.enabled.write().await = false;- // Clear saved password+ // Clear saved password (both the encrypted secret store and any legacy+ // base64 copy in store.bin).+ let _ = crate::auth_token::clear_sync_password().await;let cloud_settings = CloudSyncSettingsStore {enabled: false,encrypted_password: String::new(),@@ -486,26 +494,64 @@ pub async fn lock_sync(app: AppHandle, state: State<'_, SyncState>) -> Result<()/// Auto-start cloud sync on app launch if previously enabled./// Called from main.rs during startup.pub async fn auto_start_sync(app: &AppHandle, state: &SyncState) {- // Only auto-start if user previously enabled sync and saved a password- let password = match CloudSyncSettingsStore::get(app) {- Ok(Some(s)) if s.enabled && !s.encrypted_password.is_empty() => {- match BASE64.decode(&s.encrypted_password) {- Ok(bytes) => match String::from_utf8(bytes) {- Ok(p) => p,- Err(_) => {- warn!("cloud sync: saved password is not valid UTF-8");- return;- }- },- Err(_) => {- warn!("cloud sync: saved password is not valid base64");+ // Only auto-start if the user previously enabled sync.+ let settings = match CloudSyncSettingsStore::get(app) {+ Ok(Some(s)) => s,+ Ok(None) => {+ info!("cloud sync: no settings found, skipping auto-start");+ return;+ }+ Err(e) => {+ warn!("cloud sync: failed to read settings: {}", e);+ return;+ }+ };+ if !settings.enabled {+ info!("cloud sync: not enabled, skipping auto-start");+ return;+ }++ // Resolve the master password. Prefer the encrypted SecretStore; fall back+ // to the legacy base64 copy in store.bin and migrate it (one-time) so the+ // password is no longer kept as base64 outside the keychain-encrypted store.+ let password = match crate::auth_token::load_sync_password().await {+ Some(p) => p,+ None => {+ if settings.encrypted_password.is_empty() {+ info!("cloud sync: enabled but no saved password, skipping auto-start");+ return;+ }+ let legacy = match BASE64+ .decode(&settings.encrypted_password)+ .ok()+ .and_then(|b| String::from_utf8(b).ok())+ {+ Some(p) => p,+ None => {+ warn!("cloud sync: saved password is not valid base64/UTF-8");return;}+ };+ // Migrate into the encrypted SecretStore and drop the base64 copy.+ // On failure, keep the legacy copy so the next launch can retry+ // rather than losing the password entirely.+ match crate::auth_token::store_sync_password(&legacy).await {+ Ok(()) => {+ let cleaned = CloudSyncSettingsStore {+ enabled: true,+ encrypted_password: String::new(),+ };+ let _ = cleaned.save(app);+ info!("cloud sync: migrated saved password from store.bin to the encrypted secret store");+ }+ Err(e) => {+ warn!(+ "cloud sync: failed to migrate password to secret store: {}",+ e+ );+ }}- }- _ => {- info!("cloud sync: not enabled, skipping auto-start");- return;+ legacy}};diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rsindex 1059f66db..24c57d6ce 100644--- a/crates/screenpipe-engine/src/cli/mod.rs+++ b/crates/screenpipe-engine/src/cli/mod.rs@@ -19,7 +19,7 @@ pub mod profile;pub mod search;pub mod service;pub mod status;-mod store_file;+pub(crate) mod store_file;pub mod survey;pub mod sync;pub mod team;diff --git a/crates/screenpipe-engine/src/sync_api.rs b/crates/screenpipe-engine/src/sync_api.rsindex d7a93db87..39a9edfe3 100644--- a/crates/screenpipe-engine/src/sync_api.rs+++ b/crates/screenpipe-engine/src/sync_api.rs@@ -48,6 +48,11 @@ pub struct SyncRuntimeState {pub last_error: Arc<RwLock<Option<String>>>,/// Cursor for downloads — only fetch blobs newer than thispub last_download_at: Arc<RwLock<Option<String>>>,+ /// Whether the OCR/Transcripts/Accessibility upload service is active.+ /// `false` for runtimes started by the lazy connection-sync path (no screen+ /// data egress); flipped to `true` when an explicit `/sync/init` upgrades a+ /// connection-only runtime to full data sync.+ pub blob_upload_enabled: Arc<RwLock<bool>>,}/// Thread-safe container for optional runtime sync state@@ -89,10 +94,60 @@ pub async fn sync_init(State(state): State<Arc<AppState>>,Json(request): Json<SyncInitRequest>,) -> Result<JsonResponse<SyncInitResponse>, (StatusCode, JsonResponse<Value>)> {- // Check if already initialized+ sync_init_inner(state, request, true)+ .await+ .map(JsonResponse)+}++/// Build the sync runtime (manager + background upload/download/connection/+/// memory loops) and store it in `AppState.sync_state`.+///+/// Shared by the `/sync/init` handler (app-driven, password from the desktop+/// store) and the lazy [`ensure_sync_runtime`] path (engine-driven, password+/// from the encrypted secret store) so connection/memory sync can initialize+/// itself instead of returning "sync not initialized".+///+/// `blob_upload` controls whether the OCR/Transcripts/Accessibility upload+/// service runs. The `/sync/init` path (explicit data-sync intent) passes+/// `true`; the lazy connection-sync path passes `false`, so enabling credential+/// sync never starts uploading screen data. A later explicit `/sync/init`+/// upgrades a connection-only runtime in place — see the already-initialized+/// branch below.+async fn sync_init_inner(+ state: Arc<AppState>,+ request: SyncInitRequest,+ blob_upload: bool,+) -> Result<SyncInitResponse, (StatusCode, JsonResponse<Value>)> {+ // Already initialized? Either no-op (409) or, when an explicit /sync/init+ // asks for blob upload and the live runtime is connection-only (started by+ // the lazy path with upload off), upgrade it in place instead of erroring.{let sync_state = state.sync_state.read().await;- if sync_state.is_some() {+ if let Some(rt) = sync_state.as_ref() {+ let already_uploading = *rt.blob_upload_enabled.read().await;+ if blob_upload && !already_uploading {+ info!("sync: upgrading connection-only runtime to full blob upload");+ *rt.blob_upload_enabled.write().await = true;+ let cfg = SyncServiceConfig {+ enabled: true,+ sync_interval_secs: request.sync_interval_secs.unwrap_or(300),+ sync_types: vec![+ BlobType::Ocr,+ BlobType::Transcripts,+ BlobType::Accessibility,+ ],+ max_blobs_per_cycle: 10,+ sync_on_startup: true,+ };+ let _ = rt.service_handle.update_config(cfg).await;+ let _ = rt.service_handle.resume().await;+ let _ = rt.service_handle.sync_now().await;+ return Ok(SyncInitResponse {+ success: true,+ is_new_user: false,+ machine_id: rt.machine_id.clone(),+ });+ }return Err((StatusCode::CONFLICT,JsonResponse(json!({"error": "sync already initialized"})),@@ -138,15 +193,20 @@ pub async fn sync_init(let manager = Arc::new(manager);- // Create sync data provider- let provider = Arc::new(ScreenpipeSyncProvider::new(- state.db.clone(),- machine_id.clone(),- ));+ // Create sync data provider. Gate uploads on the user's per-type toggles so+ // disabling OCR/transcript sync actually stops those uploads (the toggles+ // were previously cosmetic against this loop).+ let provider = Arc::new(+ ScreenpipeSyncProvider::new(state.db.clone(), machine_id.clone())+ .with_sync_gating(state.screenpipe_dir.clone()),+ );- // Create sync service config+ // Create sync service config. `blob_upload` gates whether screen-data+ // (OCR/Transcripts/Accessibility) is uploaded at all — the lazy+ // connection-sync path passes false so credential sync never starts+ // uploading screen data.let service_config = SyncServiceConfig {- enabled: true,+ enabled: blob_upload,sync_interval_secs: request.sync_interval_secs.unwrap_or(300),sync_types: vec![BlobType::Ocr,@@ -154,7 +214,7 @@ pub async fn sync_init(BlobType::Accessibility,],max_blobs_per_cycle: 10,- sync_on_startup: true,+ sync_on_startup: blob_upload,};// Create and start service@@ -176,6 +236,7 @@ pub async fn sync_init(last_sync: Arc::new(RwLock::new(None)),last_error: Arc::new(RwLock::new(None)),last_download_at: Arc::new(RwLock::new(None)),+ blob_upload_enabled: Arc::new(RwLock::new(blob_upload)),};// Spawn event handler (upload events only)@@ -398,11 +459,133 @@ pub async fn sync_init(// Store in app state*state.sync_state.write().await = Some(runtime_state);- Ok(JsonResponse(SyncInitResponse {+ Ok(SyncInitResponse {success: true,is_new_user,machine_id,- }))+ })+}++/// Secret-store key holding the auto-generated sync master password.+///+/// The password is an implementation detail — it derives the E2E master key+/// but is never shown to or typed by the user. Persisting it here (encrypted)+/// keeps it stable across restarts and consistent between the app-driven+/// `/sync/init` path and the engine-driven [`ensure_sync_runtime`] path.+const SYNC_MASTER_PASSWORD_KEY: &str = "sync.master_password";++/// Generate a strong random password (256-bit, hex-encoded) used to derive the+/// sync master key. Uses the sync crypto RNG so we add no new dependency.+fn generate_sync_password() -> String {+ let a = screenpipe_core::sync::generate_salt();+ let b = screenpipe_core::sync::generate_salt();+ a.iter()+ .chain(b.iter())+ .map(|byte| format!("{:02x}", byte))+ .collect()+}++/// Lazily initialize the sync runtime if it isn't already running.+///+/// Connection- and memory-sync endpoints used to hard-fail with+/// "sync not initialized" whenever the app hadn't already POSTed `/sync/init`+/// — e.g. when the user enabled "connection sync across devices" from the+/// account page, which flips a setting and calls `/sync/connections/*` but+/// never triggers init. This resolves the cloud token + an auto-managed master+/// password from the encrypted secret store and initializes sync in-engine, so+/// no user-facing password is ever required.+///+/// Returns `Ok(())` once sync is initialized, or a structured error when the+/// user isn't signed in, has no subscription, or the stored password can't+/// unlock pre-existing server keys.+pub async fn ensure_sync_runtime(+ state: &Arc<AppState>,+) -> Result<(), (StatusCode, JsonResponse<Value>)> {+ // Fast path: already initialized.+ if state.sync_state.read().await.is_some() {+ return Ok(());+ }++ // Serialize concurrent first-time inits so we don't spawn duplicate sync+ // loops or race two `/init` posts.+ static INIT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+ let _guard = INIT_LOCK.lock().await;+ if state.sync_state.read().await.is_some() {+ return Ok(());+ }++ // Resolve the cloud auth token: freshest in-memory handle first, then the+ // shared encrypted secret store as a fallback.+ let token = {+ let in_mem = (**state.cloud_token.load()).clone();+ match in_mem.filter(|t| !t.is_empty()) {+ Some(t) => t,+ None => crate::auth_key::find_cloud_token(&state.screenpipe_dir)+ .await+ .unwrap_or_default(),+ }+ };+ if token.is_empty() {+ return Err((+ StatusCode::UNAUTHORIZED,+ JsonResponse(+ json!({"error": "not signed in: cloud sync requires a logged-in account"}),+ ),+ ));+ }++ // The encrypted secret store is the source of truth for the auto-managed+ // master password (survives restarts; consistent across app/engine paths).+ let secret_store = state.secret_store.as_ref().ok_or_else(|| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": "secret store unavailable; cannot manage sync password"})),+ )+ })?;++ let existing = match secret_store.get(SYNC_MASTER_PASSWORD_KEY).await {+ Ok(Some(bytes)) => String::from_utf8(bytes).unwrap_or_default(),+ _ => String::new(),+ };+ let password = if existing.is_empty() {+ let generated = generate_sync_password();+ if let Err(e) = secret_store+ .set(SYNC_MASTER_PASSWORD_KEY, generated.as_bytes())+ .await+ {+ error!("failed to persist sync master password: {}", e);+ return Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": "failed to persist sync password"})),+ ));+ }+ generated+ } else {+ existing+ };++ let machine_id = screenpipe_core::sync::get_or_create_machine_id();++ let request = SyncInitRequest {+ token,+ password,+ machine_id: Some(machine_id),+ sync_interval_secs: Some(300),+ };++ // blob_upload = false: connection/credential sync only. Enabling credential+ // sync must never start uploading OCR/transcripts/accessibility to the+ // cloud — that requires an explicit /sync/init (data-sync intent), which+ // upgrades this runtime in place.+ match sync_init_inner(state.clone(), request, false).await {+ Ok(_) => {+ info!("sync auto-initialized (lazy) for connection/memory sync");+ Ok(())+ }+ // A concurrent caller initialized first — fine.+ Err((StatusCode::CONFLICT, _)) => Ok(()),+ Err(e) => Err(e),+ }}/// Response for sync status.@@ -637,6 +820,11 @@ pub async fn sync_connections_push() -> Result<JsonResponse<ConnectionsSyncResponse>, (StatusCode, JsonResponse<Value>)> {use screenpipe_core::connections::sync::*;+ // Lazily initialize sync if the app never POSTed /sync/init (e.g. the user+ // toggled "connection sync across devices" from the account page). No+ // user-facing password is required — the master password is auto-managed.+ ensure_sync_runtime(&state).await?;+let sync_state = state.sync_state.read().await;let runtime = sync_state.as_ref().ok_or_else(|| {(@@ -680,6 +868,11 @@ pub async fn sync_connections_pull() -> Result<JsonResponse<ConnectionsSyncResponse>, (StatusCode, JsonResponse<Value>)> {use screenpipe_core::connections::sync::*;+ // Lazily initialize sync if the app never POSTed /sync/init (e.g. the user+ // toggled "connection sync across devices" from the account page). No+ // user-facing password is required — the master password is auto-managed.+ ensure_sync_runtime(&state).await?;+let sync_state = state.sync_state.read().await;let runtime = sync_state.as_ref().ok_or_else(|| {(@@ -1127,12 +1320,11 @@ fn is_connections_sync_enabled(screenpipe_dir: &std::path::Path) -> bool {/// Returns false on any failure (missing file, corrupt JSON, missing key)./// Shared with pipe sync to keep both feature toggles consistent.fn is_settings_bool_enabled(screenpipe_dir: &std::path::Path, key: &str) -> bool {- let store_path = screenpipe_dir.join("store.bin");- let content = match std::fs::read_to_string(&store_path) {- Ok(c) => c,- Err(_) => return false,- };- let store: serde_json::Value = match serde_json::from_str(&content) {+ // Use the keychain-decrypting store reader: store.bin is SPSTORE1-encrypted+ // when the user enabled store encryption, and a plaintext read_to_string ++ // serde parse silently fails on it — returning false for EVERY toggle, which+ // silently disabled background connection/pipe/memory sync for those users.+ let store = match crate::cli::store_file::read_store_for(screenpipe_dir) {Ok(v) => v,Err(_) => return false,};@@ -1615,6 +1807,45 @@ mod tests {assert!(guard.is_none());}+ #[test]+ fn test_generate_sync_password() {+ let a = generate_sync_password();+ let b = generate_sync_password();+ // Two SALT_SIZE (32-byte) salts hex-encoded => 128 chars, all hex.+ assert_eq!(a.len(), 128);+ assert!(a.bytes().all(|c| c.is_ascii_hexdigit()));+ // Random: two generations must not collide.+ assert_ne!(a, b);+ }++ #[test]+ fn test_is_settings_bool_enabled_reads_store() {+ use std::io::Write;+ let dir = tempfile::tempdir().unwrap();++ // Missing store → false.+ assert!(!is_settings_bool_enabled(+ dir.path(),+ "connectionsSyncEnabled"+ ));++ // Plaintext store via the keychain-aware reader.+ let store = serde_json::json!({+ "settings": { "connectionsSyncEnabled": true, "pipeSyncEnabled": false }+ });+ let mut f = std::fs::File::create(dir.path().join("store.bin")).unwrap();+ f.write_all(serde_json::to_string(&store).unwrap().as_bytes())+ .unwrap();++ assert!(is_settings_bool_enabled(+ dir.path(),+ "connectionsSyncEnabled"+ ));+ assert!(!is_settings_bool_enabled(dir.path(), "pipeSyncEnabled"));+ // Absent key → false.+ assert!(!is_settings_bool_enabled(dir.path(), "memoriesSyncEnabled"));+ }+#[test]fn test_sync_init_request_serialization() {let request = SyncInitRequest {diff --git a/crates/screenpipe-engine/src/sync_provider.rs b/crates/screenpipe-engine/src/sync_provider.rsindex 201431317..d7fe3a3c0 100644--- a/crates/screenpipe-engine/src/sync_provider.rs+++ b/crates/screenpipe-engine/src/sync_provider.rs@@ -13,6 +13,7 @@ use screenpipe_core::sync::{BlobType, PendingBlob, SyncDataProvider, SyncError,use screenpipe_db::DatabaseManager;use serde::{Deserialize, Serialize};use sqlx::Row;+use std::path::PathBuf;use std::sync::Arc;use tracing::debug;use uuid::Uuid;@@ -144,16 +145,70 @@ pub struct UiEventSyncRecord {/// Current schema version for sync chunkspub const SCHEMA_VERSION: u32 = 2;+/// Whether cloud sync is enabled for `blob_type`, per the user's per-type+/// toggles in `<dir>/store.bin` → `sync_config`. Reads the (possibly encrypted)+/// store on each call so changes take effect on the next cycle without re-init.+///+/// Fail-OPEN: returns `true` when gating is off (`None`), the type has no toggle,+/// the key is absent, or the store can't be read — so existing data-sync users+/// are never silently regressed.+fn sync_data_type_enabled(gate_dir: Option<&std::path::Path>, blob_type: BlobType) -> bool {+ let dir = match gate_dir {+ Some(d) => d,+ None => return true,+ };+ // Map upload blob types to the UI's sync_config toggles. The accessibility+ // tree is screen text, so it follows the OCR toggle.+ let key = match blob_type {+ BlobType::Ocr | BlobType::Accessibility => "syncOcr",+ BlobType::Transcripts => "syncTranscripts",+ _ => return true,+ };+ let store = match crate::cli::store_file::read_store_for(dir) {+ Ok(v) => v,+ Err(_) => return true,+ };+ store+ .get("sync_config")+ .and_then(|c| c.get(key))+ .and_then(|v| v.as_bool())+ .unwrap_or(true)+}+/// Data provider implementation for screenpipe database.pub struct ScreenpipeSyncProvider {db: Arc<DatabaseManager>,machine_id: String,+ /// When set, OCR/Transcripts/Accessibility uploads are gated on the user's+ /// per-type sync toggles (`<dir>/store.bin` → `sync_config`). Only the+ /// upload provider sets this; the download/import and CLI providers leave+ /// it `None` (no gating).+ sync_gate_dir: Option<PathBuf>,}impl ScreenpipeSyncProvider {/// Create a new sync provider.pub fn new(db: Arc<DatabaseManager>, machine_id: String) -> Self {- Self { db, machine_id }+ Self {+ db,+ machine_id,+ sync_gate_dir: None,+ }+ }++ /// Enable per-type upload gating, reading `<dir>/store.bin` → `sync_config`.+ pub fn with_sync_gating(mut self, dir: PathBuf) -> Self {+ self.sync_gate_dir = Some(dir);+ self+ }++ /// Whether cloud sync is enabled for this blob type. Reads the (possibly+ /// encrypted) store on each call so toggle changes take effect on the next+ /// cycle without a re-init. Fail-OPEN: defaults to enabled when gating is+ /// off, the key is absent, or the store can't be read, so existing+ /// data-sync users are never silently regressed.+ fn data_type_enabled(&self, blob_type: BlobType) -> bool {+ sync_data_type_enabled(self.sync_gate_dir.as_deref(), blob_type)}/// Get unsynced frames and their OCR data for a time window.@@ -809,6 +864,10 @@ impl SyncDataProvider for ScreenpipeSyncProvider {blob_type: BlobType,limit: usize,) -> SyncResult<Vec<PendingBlob>> {+ // Respect the user's per-type cloud-sync toggles (default on).+ if !self.data_type_enabled(blob_type) {+ return Ok(Vec::new());+ }let chunk_result = match blob_type {BlobType::Ocr => self.get_unsynced_ocr_chunk(limit).await?,BlobType::Transcripts => self.get_unsynced_transcriptions_chunk(limit).await?,@@ -866,6 +925,40 @@ pub struct ImportResult {mod tests {use super::*;+ #[test]+ fn test_sync_data_type_gating() {+ use std::io::Write;+ // No gate dir → always enabled (download/CLI providers).+ assert!(sync_data_type_enabled(None, BlobType::Ocr));+ assert!(sync_data_type_enabled(None, BlobType::Transcripts));++ let dir = tempfile::tempdir().unwrap();++ // No store.bin yet → fail-open (enabled), no regression.+ assert!(sync_data_type_enabled(Some(dir.path()), BlobType::Ocr));++ // Plaintext store with OCR off, transcripts on.+ let store = serde_json::json!({+ "sync_config": { "syncOcr": false, "syncTranscripts": true }+ });+ let mut f = std::fs::File::create(dir.path().join("store.bin")).unwrap();+ f.write_all(serde_json::to_string(&store).unwrap().as_bytes())+ .unwrap();++ assert!(!sync_data_type_enabled(Some(dir.path()), BlobType::Ocr));+ // Accessibility follows the OCR toggle.+ assert!(!sync_data_type_enabled(+ Some(dir.path()),+ BlobType::Accessibility+ ));+ assert!(sync_data_type_enabled(+ Some(dir.path()),+ BlobType::Transcripts+ ));+ // Types without a toggle are always enabled.+ assert!(sync_data_type_enabled(Some(dir.path()), BlobType::Input));+ }+#[test]fn test_sync_chunk_serialization() {let chunk = SyncChunk {