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

feat(ui): add cloud sync docs and link in settings

Louis Beaumont804854f91ee4
diff --git a/CLOUD_SYNC_IMPLEMENTATION_PLAN.md b/CLOUD_SYNC_IMPLEMENTATION_PLAN.md
deleted file mode 100644
index f1a34c79c..000000000
--- a/CLOUD_SYNC_IMPLEMENTATION_PLAN.md
+++ /dev/null
@@ -1,1347 +0,0 @@
-# Screenpipe Cloud Sync - Implementation Plan
-
-## Executive Summary
-
-This document outlines the implementation plan for encrypted cloud sync in Screenpipe, enabling users to:
-1. Sync screen/audio recording data across devices
-2. Keep data private with end-to-end encryption (E2E)
-3. Allow AI to query historical data from the cloud
-4. Support cross-platform sync (macOS, Windows, Linux)
-
-**Key Principle**: Zero-knowledge architecture - Screenpipe servers never see plaintext data.
-
----
-
-## Table of Contents
-
-1. [Architecture Overview](#1-architecture-overview)
-2. [Database Schema Changes](#2-database-schema-changes)
-3. [Backend API Implementation](#3-backend-api-implementation)
-4. [Desktop App Changes](#4-desktop-app-changes)
-5. [Encryption Implementation](#5-encryption-implementation)
-6. [AI Integration](#6-ai-integration)
-7. [Cross-Platform Sync](#7-cross-platform-sync)
-8. [Pricing & Stripe Integration](#8-pricing--stripe-integration)
-9. [Implementation Phases](#9-implementation-phases)
-10. [File-by-File Changes](#10-file-by-file-changes)
-
----
-
-## 1. Architecture Overview
-
-### High-Level Data Flow
-
-```
-┌─────────────────────────────────────────────────────────────────────────┐
-│ USER DEVICE │
-├─────────────────────────────────────────────────────────────────────────┤
-│ │
-│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │
-│ │ Local SQLite │───▶│ Encryption │───▶│ Sync Manager │ │
-│ │ Database │ │ Layer │ │ (Rust/Tauri) │ │
-│ └──────────────┘ └──────────────┘ └──────────────────────────┘ │
-│ │ │ │ │
-│ │ │ │ │
-│ ┌──────▼──────┐ ┌───────▼──────┐ ┌───────────▼─────────────┐ │
-│ │ Hot Cache │ │ Key Manager │ │ Background Sync Service │ │
-│ │ (7-30 days) │ │ (libsodium) │ │ (tokio async) │ │
-│ └─────────────┘ └──────────────┘ └─────────────────────────┘ │
-│ │ │
-└─────────────────────────────────────────────────────│───────────────────┘
- │
- HTTPS + E2E Encrypted
- │
- ▼
-┌─────────────────────────────────────────────────────────────────────────┐
-│ SCREENPIPE CLOUD │
-├─────────────────────────────────────────────────────────────────────────┤
-│ │
-│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
-│ │ Supabase │ │ S3/R2 Storage │ │ Sync API │ │
-│ │ (Postgres) │ │ (Encrypted Blobs)│ │ (Next.js) │ │
-│ │ │ │ │ │ │ │
-│ │ - sync_devices │ │ - /sync/{user}/ │ │ - /api/sync/* │ │
-│ │ - sync_metadata │ │ ├── frames/ │ │ │ │
-│ │ - sync_index │ │ ├── audio/ │ │ │ │
-│ │ - sync_keys │ │ └── index/ │ │ │ │
-│ └──────────────────┘ └──────────────────┘ └──────────────────┘ │
-│ │
-│ WE NEVER SEE PLAINTEXT - Only encrypted blobs + hashed search tokens │
-│ │
-└─────────────────────────────────────────────────────────────────────────┘
-```
-
-### Key Components
-
-| Component | Location | Purpose |
-|-----------|----------|---------|
-| Sync Manager | `screenpipe-app-tauri/src-tauri/src/sync/` | Coordinates sync operations |
-| Encryption Layer | `screenpipe-core/src/encryption/` | E2E encryption/decryption |
-| Key Manager | `screenpipe-app-tauri/src-tauri/src/sync/keys.rs` | Key derivation & storage |
-| Sync API | `screen-pipe-website/app/api/sync/` | Cloud endpoints |
-| Sync Worker | `screenpipe-app-tauri/src-tauri/src/sync/worker.rs` | Background sync |
-
----
-
-## 2. Database Schema Changes
-
-### 2.1 New Tables in Supabase (screen-pipe-website)
-
-```sql
--- Migration: 20260201_add_cloud_sync_tables.sql
-
--- User encryption keys (stores encrypted master key, not plaintext)
-CREATE TABLE sync_keys (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-
- -- Key derivation parameters (public, needed to re-derive key)
- salt BYTEA NOT NULL, -- 32 bytes, random per user
- kdf_algorithm TEXT NOT NULL DEFAULT 'argon2id',
- kdf_iterations INTEGER NOT NULL DEFAULT 3,
- kdf_memory INTEGER NOT NULL DEFAULT 65536, -- 64MB
-
- -- Encrypted master key (encrypted with password-derived key)
- encrypted_master_key BYTEA NOT NULL, -- AES-256-GCM encrypted
- master_key_nonce BYTEA NOT NULL, -- 12 bytes
-
- -- Key version for rotation
- key_version INTEGER NOT NULL DEFAULT 1,
-
- created_at TIMESTAMPTZ DEFAULT NOW(),
- rotated_at TIMESTAMPTZ,
-
- UNIQUE(user_id)
-);
-
--- Registered sync devices
-CREATE TABLE sync_devices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-
- device_id TEXT NOT NULL, -- Unique device identifier
- device_name TEXT, -- User-friendly name
- device_os TEXT, -- 'macos', 'windows', 'linux'
- device_os_version TEXT,
-
- -- Device-specific key (for secure key exchange)
- device_public_key BYTEA, -- X25519 public key
-
- last_sync_at TIMESTAMPTZ,
- last_ip INET,
-
- created_at TIMESTAMPTZ DEFAULT NOW(),
-
- UNIQUE(user_id, device_id)
-);
-
--- Encrypted data blobs metadata
-CREATE TABLE sync_blobs (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-
- blob_type TEXT NOT NULL, -- 'frames', 'audio', 'transcripts', 'ocr'
- s3_key TEXT NOT NULL, -- Path in S3: sync/{user_id}/{blob_type}/{id}
-
- -- Time range this blob covers
- time_start TIMESTAMPTZ NOT NULL,
- time_end TIMESTAMPTZ NOT NULL,
-
- -- Encryption metadata
- encryption_nonce BYTEA NOT NULL, -- 12 bytes
- key_version INTEGER NOT NULL, -- Which master key version
-
- -- Integrity
- size_bytes BIGINT NOT NULL,
- checksum TEXT NOT NULL, -- SHA-256 of plaintext (before encryption)
-
- -- Source device
- source_device_id TEXT NOT NULL,
-
- created_at TIMESTAMPTZ DEFAULT NOW(),
-
- INDEX idx_sync_blobs_user_time (user_id, time_start, time_end),
- INDEX idx_sync_blobs_type (user_id, blob_type)
-);
-
--- Encrypted search index (for finding data without decrypting everything)
-CREATE TABLE sync_search_index (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- blob_id UUID NOT NULL REFERENCES sync_blobs(id) ON DELETE CASCADE,
-
- -- Hashed search tokens (deterministic, can match but not reverse)
- -- Generated as: HMAC-SHA256(search_key, lowercase(keyword))
- search_token BYTEA NOT NULL, -- 32 bytes
-
- -- Approximate timestamp for time-based filtering
- timestamp_bucket TIMESTAMPTZ NOT NULL, -- Rounded to nearest hour
-
- INDEX idx_sync_search_token (user_id, search_token),
- INDEX idx_sync_search_time (user_id, timestamp_bucket)
-);
-
--- Sync operation log (for conflict resolution and debugging)
-CREATE TABLE sync_operations (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- device_id TEXT NOT NULL,
-
- operation TEXT NOT NULL, -- 'upload', 'download', 'delete', 'key_rotation'
- blob_type TEXT,
- blob_count INTEGER,
- bytes_transferred BIGINT,
-
- status TEXT NOT NULL, -- 'pending', 'success', 'failed'
- error_message TEXT,
-
- started_at TIMESTAMPTZ DEFAULT NOW(),
- completed_at TIMESTAMPTZ,
-
- INDEX idx_sync_ops_user (user_id, started_at DESC)
-);
-
--- Storage usage tracking
-CREATE TABLE sync_storage (
- user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
-
- total_bytes BIGINT NOT NULL DEFAULT 0,
- blob_count INTEGER NOT NULL DEFAULT 0,
-
- -- Per-type breakdown
- frames_bytes BIGINT NOT NULL DEFAULT 0,
- audio_bytes BIGINT NOT NULL DEFAULT 0,
- transcripts_bytes BIGINT NOT NULL DEFAULT 0,
-
- last_calculated_at TIMESTAMPTZ DEFAULT NOW()
-);
-
--- Update cloud_subscriptions to include sync tier
-ALTER TABLE cloud_subscriptions
-ADD COLUMN sync_tier TEXT DEFAULT NULL, -- 'starter', 'pro', 'team'
-ADD COLUMN storage_limit_bytes BIGINT DEFAULT 0, -- Based on tier
-ADD COLUMN device_limit INTEGER DEFAULT 0; -- Based on tier
-
--- RLS Policies
-ALTER TABLE sync_keys ENABLE ROW LEVEL SECURITY;
-ALTER TABLE sync_devices ENABLE ROW LEVEL SECURITY;
-ALTER TABLE sync_blobs ENABLE ROW LEVEL SECURITY;
-ALTER TABLE sync_search_index ENABLE ROW LEVEL SECURITY;
-ALTER TABLE sync_operations ENABLE ROW LEVEL SECURITY;
-ALTER TABLE sync_storage ENABLE ROW LEVEL SECURITY;
-
--- Users can only access their own data
-CREATE POLICY sync_keys_user_policy ON sync_keys
- FOR ALL USING (user_id = auth.uid());
-
-CREATE POLICY sync_devices_user_policy ON sync_devices
- FOR ALL USING (user_id = auth.uid());
-
-CREATE POLICY sync_blobs_user_policy ON sync_blobs
- FOR ALL USING (user_id = auth.uid());
-
--- ... (similar policies for other tables)
-```
-
-### 2.2 RPC Functions
-
-```sql
--- Check storage quota
-CREATE OR REPLACE FUNCTION check_sync_quota(p_user_id UUID)
-RETURNS TABLE(
- storage_used BIGINT,
- storage_limit BIGINT,
- device_count INTEGER,
- device_limit INTEGER,
- can_sync BOOLEAN
-) AS $$
-BEGIN
- RETURN QUERY
- SELECT
- COALESCE(s.total_bytes, 0) as storage_used,
- COALESCE(cs.storage_limit_bytes, 0) as storage_limit,
- (SELECT COUNT(*)::INTEGER FROM sync_devices WHERE user_id = p_user_id) as device_count,
- COALESCE(cs.device_limit, 0) as device_limit,
- (COALESCE(s.total_bytes, 0) < COALESCE(cs.storage_limit_bytes, 0)
- AND (SELECT COUNT(*) FROM sync_devices WHERE user_id = p_user_id) <= COALESCE(cs.device_limit, 0)) as can_sync
- FROM users u
- LEFT JOIN sync_storage s ON s.user_id = u.id
- LEFT JOIN cloud_subscriptions cs ON cs.user_id = u.id AND cs.status = 'active'
- WHERE u.id = p_user_id;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
--- Update storage after upload
-CREATE OR REPLACE FUNCTION update_sync_storage()
-RETURNS TRIGGER AS $$
-BEGIN
- IF TG_OP = 'INSERT' THEN
- INSERT INTO sync_storage (user_id, total_bytes, blob_count)
- VALUES (NEW.user_id, NEW.size_bytes, 1)
- ON CONFLICT (user_id) DO UPDATE SET
- total_bytes = sync_storage.total_bytes + NEW.size_bytes,
- blob_count = sync_storage.blob_count + 1,
- last_calculated_at = NOW();
- ELSIF TG_OP = 'DELETE' THEN
- UPDATE sync_storage SET
- total_bytes = GREATEST(0, total_bytes - OLD.size_bytes),
- blob_count = GREATEST(0, blob_count - 1),
- last_calculated_at = NOW()
- WHERE user_id = OLD.user_id;
- END IF;
- RETURN NULL;
-END;
-$$ LANGUAGE plpgsql;
-
-CREATE TRIGGER sync_storage_trigger
-AFTER INSERT OR DELETE ON sync_blobs
-FOR EACH ROW EXECUTE FUNCTION update_sync_storage();
-```
-
----
-
-## 3. Backend API Implementation
-
-### 3.1 New API Routes (screen-pipe-website/app/api/sync/)
-
-```
-app/api/sync/
-├── init/
-│ └── route.ts # Initialize encryption for user
-├── devices/
-│ ├── route.ts # List/register devices
-│ └── [deviceId]/
-│ └── route.ts # Device management
-├── upload/
-│ └── route.ts # Get presigned URL + register blob
-├── download/
-│ └── route.ts # Get presigned URL for download
-├── search/
-│ └── route.ts # Search encrypted index
-├── status/
-│ └── route.ts # Sync status & storage usage
-├── key-rotation/
-│ └── route.ts # Rotate encryption keys
-└── webhook/
- └── route.ts # Stripe webhook for sync subscriptions
-```
-
-### 3.2 API Endpoint Details
-
-#### POST /api/sync/init
-Initialize encryption for a new user or device.
-
-```typescript
-// Request
-{
- device_id: string,
- device_name: string,
- device_os: "macos" | "windows" | "linux",
- device_public_key: string, // Base64 X25519 public key
-
- // For new users: encrypted master key
- encrypted_master_key?: string,
- master_key_nonce?: string,
- salt?: string,
-}
-
-// Response
-{
- success: true,
- salt: string,
- kdf_params: { algorithm: string, iterations: number, memory: number },
- encrypted_master_key: string, // For existing users
- master_key_nonce: string,
- key_version: number,
-}
-```
-
-#### POST /api/sync/upload
-Get presigned URL for uploading encrypted blob.
-
-```typescript
-// Request
-{
- blob_type: "frames" | "audio" | "transcripts" | "ocr",
- time_start: string, // ISO timestamp
- time_end: string,
- size_bytes: number,
- checksum: string, // SHA-256 of plaintext
- device_id: string,
- key_version: number,
-
- // For search index
- search_tokens?: string[], // Base64 HMAC tokens
-}
-
-// Response
-{
- success: true,
- blob_id: string,
- upload_url: string, // Presigned S3 URL
- expires_in: number,
-}
-```
-
-#### POST /api/sync/download
-Get presigned URLs for downloading encrypted blobs.
-
-```typescript
-// Request
-{
- blob_ids?: string[], // Specific blobs
- time_range?: { start: string, end: string },
- blob_types?: string[],
- limit?: number,
-}
-
-// Response
-{
- success: true,
- blobs: [{
- blob_id: string,
- blob_type: string,
- download_url: string,
- encryption_nonce: string,
- key_version: number,
- size_bytes: number,
- checksum: string,
- }],
-}
-```
-
-#### POST /api/sync/search
-Search encrypted index.
-
-```typescript
-// Request
-{
- search_tokens: string[], // Base64 HMAC tokens (generated client-side)
- time_range?: { start: string, end: string },
- blob_types?: string[],
- limit?: number,
-}
-
-// Response
-{
- success: true,
- matches: [{
- blob_id: string,
- blob_type: string,
- time_start: string,
- time_end: string,
- match_count: number,
- }],
-}
-```
-
-### 3.3 Implementation Example
-
-```typescript
-// app/api/sync/upload/route.ts
-import { NextResponse } from "next/server";
-import { verifyToken } from "@clerk/backend";
-import { createClient } from "@supabase/supabase-js";
-import { createSignedUploadUrlWithContentType } from "@/app/utils/s3";
-
-export async function POST(request: Request) {
- const supabase = createClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.SUPABASE_SERVICE_KEY!
- );
-
- try {
- // 1. Authenticate
- const authHeader = request.headers.get("authorization");
- const token = authHeader?.replace("Bearer ", "");
- if (!token) {
- return NextResponse.json({ error: "unauthorized" }, { status: 401 });
- }
-
- const payload = await verifyToken(token, {
- secretKey: process.env.CLERK_SECRET_KEY,
- });
-
- // 2. Get user
- const { data: user } = await supabase
- .from("users")
- .select("id")
- .eq("clerk_id", payload.sub)
- .single();
-
- if (!user) {
- return NextResponse.json({ error: "user not found" }, { status: 404 });
- }
-
- // 3. Check quota
- const { data: quota } = await supabase
- .rpc("check_sync_quota", { p_user_id: user.id });
-
- if (!quota?.can_sync) {
- return NextResponse.json({ error: "quota exceeded" }, { status: 403 });
- }
-
- // 4. Parse request
- const body = await request.json();
- const {
- blob_type,
- time_start,
- time_end,
- size_bytes,
- checksum,
- device_id,
- key_version,
- search_tokens,
- } = body;
-
- // 5. Generate blob ID and S3 key
- const blobId = crypto.randomUUID();
- const s3Key = `sync/${user.id}/${blob_type}/${blobId}.enc`;
-
- // 6. Create blob record
- const { error: insertError } = await supabase
- .from("sync_blobs")
- .insert({
- id: blobId,
- user_id: user.id,
- blob_type,
- s3_key: s3Key,
- time_start,
- time_end,
- encryption_nonce: body.encryption_nonce,
- key_version,
- size_bytes,
- checksum,
- source_device_id: device_id,
- });
-
- if (insertError) {
- throw insertError;
- }
-
- // 7. Insert search tokens
- if (search_tokens?.length) {
- const searchRecords = search_tokens.map((token: string) => ({
- user_id: user.id,
- blob_id: blobId,
- search_token: Buffer.from(token, "base64"),
- timestamp_bucket: new Date(time_start).toISOString(),
- }));
-
- await supabase.from("sync_search_index").insert(searchRecords);
- }
-
- // 8. Generate presigned upload URL
- const { data: urlData } = await createSignedUploadUrlWithContentType(
- s3Key,
- "application/octet-stream",
- 300
- );
-
- // 9. Log operation
- await supabase.from("sync_operations").insert({
- user_id: user.id,
- device_id,
- operation: "upload",
- blob_type,
- blob_count: 1,
- bytes_transferred: size_bytes,
- status: "pending",
- });
-
- return NextResponse.json({
- success: true,
- blob_id: blobId,
- upload_url: urlData?.signedUrl,
- expires_in: 300,
- });
-
- } catch (error) {
- console.error("sync upload error:", error);
- return NextResponse.json(
- { error: "internal server error" },
- { status: 500 }
- );
- }
-}
-```
-
----
-
-## 4. Desktop App Changes
-
-### 4.1 New Rust Modules
-
-```
-screenpipe-app-tauri/src-tauri/src/
-├── sync/
-│ ├── mod.rs # Module exports
-│ ├── manager.rs # SyncManager - main coordinator
-│ ├── encryption.rs # Encryption/decryption using libsodium
-│ ├── keys.rs # Key derivation and storage
-│ ├── worker.rs # Background sync worker
-│ ├── protocol.rs # Sync protocol implementation
-│ ├── conflict.rs # Conflict resolution
-│ └── types.rs # Shared types
-```
-
-### 4.2 Tauri Commands
-
-```rust
-// src-tauri/src/commands/sync.rs
-
-#[tauri::command]
-pub async fn sync_init(
- password: String,
- device_name: String,
- state: State<'_, AppState>,
-) -> Result<SyncInitResult, String> {
- // Initialize encryption with user password
- // Returns: salt, encrypted_master_key, etc.
-}
-
-#[tauri::command]
-pub async fn sync_unlock(
- password: String,
- state: State<'_, AppState>,
-) -> Result<bool, String> {
- // Derive key from password, unlock sync
-}
-
-#[tauri::command]
-pub async fn sync_now(
- state: State<'_, AppState>,
-) -> Result<SyncStatus, String> {
- // Trigger immediate sync
-}
-
-#[tauri::command]
-pub async fn sync_status(
- state: State<'_, AppState>,
-) -> Result<SyncStatus, String> {
- // Get current sync status
-}
-
-#[tauri::command]
-pub async fn sync_search_historical(
- query: String,
- time_range: Option<TimeRange>,
- state: State<'_, AppState>,
-) -> Result<Vec<SearchResult>, String> {
- // Search local cache + cloud index
-}
-
-#[tauri::command]
-pub async fn sync_download_blob(
- blob_id: String,
- state: State<'_, AppState>,
-) -> Result<Vec<u8>, String> {
- // Download and decrypt specific blob
-}
-
-#[tauri::command]
-pub async fn sync_list_devices(
- state: State<'_, AppState>,
-) -> Result<Vec<SyncDevice>, String> {
- // List registered devices
-}
-
-#[tauri::command]
-pub async fn sync_remove_device(
- device_id: String,
- state: State<'_, AppState>,
-) -> Result<(), String> {
- // Remove a device from sync
-}
-```
-
-### 4.3 Core Encryption Implementation
-
-```rust
-// screenpipe-core/src/encryption/mod.rs
-
-use chacha20poly1305::{
- aead::{Aead, KeyInit},
- ChaCha20Poly1305, Nonce,
-};
-use argon2::{Argon2, Params};
-use rand::RngCore;
-
-pub struct EncryptionKey([u8; 32]);
-
-impl EncryptionKey {
- /// Derive key from password using Argon2id
- pub fn derive_from_password(password: &str, salt: &[u8; 32]) -> Result<Self> {
- let params = Params::new(65536, 3, 1, Some(32))?;
- let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
-
- let mut key = [0u8; 32];
- argon2.hash_password_into(password.as_bytes(), salt, &mut key)?;
-
- Ok(Self(key))
- }
-
- /// Generate random key
- pub fn generate() -> Self {
- let mut key = [0u8; 32];
- rand::thread_rng().fill_bytes(&mut key);
- Self(key)
- }
-
- /// Encrypt data
- pub fn encrypt(&self, plaintext: &[u8]) -> Result<EncryptedData> {
- let cipher = ChaCha20Poly1305::new_from_slice(&self.0)?;
-
- let mut nonce_bytes = [0u8; 12];
- rand::thread_rng().fill_bytes(&mut nonce_bytes);
- let nonce = Nonce::from_slice(&nonce_bytes);
-
- let ciphertext = cipher.encrypt(nonce, plaintext)?;
-
- Ok(EncryptedData {
- ciphertext,
- nonce: nonce_bytes,
- })
- }
-
- /// Decrypt data
- pub fn decrypt(&self, encrypted: &EncryptedData) -> Result<Vec<u8>> {
- let cipher = ChaCha20Poly1305::new_from_slice(&self.0)?;
- let nonce = Nonce::from_slice(&encrypted.nonce);
-
- let plaintext = cipher.decrypt(nonce, encrypted.ciphertext.as_slice())?;
-
- Ok(plaintext)
- }
-}
-
-pub struct EncryptedData {
- pub ciphertext: Vec<u8>,
- pub nonce: [u8; 12],
-}
-
-/// Generate search tokens (deterministic, for server-side matching)
-pub fn generate_search_token(search_key: &[u8; 32], keyword: &str) -> [u8; 32] {
- use hmac::{Hmac, Mac};
- use sha2::Sha256;
-
- type HmacSha256 = Hmac<Sha256>;
-
- let mut mac = HmacSha256::new_from_slice(search_key).unwrap();
- mac.update(keyword.to_lowercase().as_bytes());
-
- let result = mac.finalize();
- let mut token = [0u8; 32];
- token.copy_from_slice(&result.into_bytes());
- token
-}
-```
-
-### 4.4 Sync Manager
-
-```rust
-// screenpipe-app-tauri/src-tauri/src/sync/manager.rs
-
-pub struct SyncManager {
- api_client: SyncApiClient,
- encryption_key: Option<EncryptionKey>,
- search_key: Option<[u8; 32]>,
- device_id: String,
- db_path: PathBuf,
-
- // State
- is_syncing: AtomicBool,
- last_sync: RwLock<Option<DateTime<Utc>>>,
-}
-
-impl SyncManager {
- pub async fn new(config: SyncConfig) -> Result<Self> {
- let device_id = Self::get_or_create_device_id().await?;
-
- Ok(Self {
- api_client: SyncApiClient::new(config.api_url, config.token),
- encryption_key: None,
- search_key: None,
- device_id,
- db_path: config.db_path,
- is_syncing: AtomicBool::new(false),
- last_sync: RwLock::new(None),
- })
- }
-
- /// Initialize encryption with password
- pub async fn init_encryption(&mut self, password: &str) -> Result<()> {
- // 1. Check if user has existing keys on server
- let existing = self.api_client.get_sync_keys().await?;
-
- if let Some(keys) = existing {
- // Derive key from password using stored salt
- let password_key = EncryptionKey::derive_from_password(
- password,
- &keys.salt,
- )?;
-
- // Decrypt master key
- let master_key = password_key.decrypt(&EncryptedData {
- ciphertext: keys.encrypted_master_key,
- nonce: keys.master_key_nonce,
- })?;
-
- self.encryption_key = Some(EncryptionKey::from_bytes(&master_key)?);
- self.search_key = Some(self.derive_search_key(&master_key)?);
- } else {
- // New user - generate keys
- let salt = generate_random_salt();
- let master_key = EncryptionKey::generate();
- let password_key = EncryptionKey::derive_from_password(password, &salt)?;
-
- // Encrypt master key with password-derived key
- let encrypted_master = password_key.encrypt(&master_key.as_bytes())?;
-
- // Store on server
- self.api_client.init_sync_keys(SyncKeysInit {
- salt,
- encrypted_master_key: encrypted_master.ciphertext,
- master_key_nonce: encrypted_master.nonce,
- device_id: self.device_id.clone(),
- device_name: Self::get_device_name(),
- device_os: Self::get_device_os(),
- }).await?;
-
- self.encryption_key = Some(master_key);
- self.search_key = Some(self.derive_search_key(&master_key.as_bytes())?);
- }
-
- Ok(())
- }
-
- /// Sync local data to cloud
- pub async fn sync_up(&self) -> Result<SyncResult> {
- if !self.is_syncing.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
- return Err(SyncError::AlreadySyncing);
- }
-
- let _guard = scopeguard::guard((), |_| {
- self.is_syncing.store(false, Ordering::SeqCst);
- });
-
- let encryption_key = self.encryption_key.as_ref()
- .ok_or(SyncError::NotInitialized)?;
-
- // 1. Find data that needs syncing
- let pending = self.find_pending_sync_data().await?;
-
- let mut uploaded = 0;
- let mut bytes = 0;
-
- for batch in pending.chunks(100) {
- // 2. Serialize and encrypt batch
- let plaintext = self.serialize_batch(batch)?;
- let checksum = sha256(&plaintext);
- let encrypted = encryption_key.encrypt(&plaintext)?;
-
- // 3. Generate search tokens
- let tokens = self.extract_search_tokens(batch)?;
-
- // 4. Get upload URL from server
- let upload_info = self.api_client.request_upload(UploadRequest {
- blob_type: batch[0].blob_type.clone(),
- time_start: batch.first().unwrap().timestamp,
- time_end: batch.last().unwrap().timestamp,
- size_bytes: encrypted.ciphertext.len(),
- checksum,
- device_id: self.device_id.clone(),
- key_version: 1,
- encryption_nonce: encrypted.nonce.to_vec(),
- search_tokens: tokens,
- }).await?;
-
- // 5. Upload to S3
- self.upload_to_s3(&upload_info.upload_url, &encrypted.ciphertext).await?;
-
- // 6. Mark as synced locally
- self.mark_synced(&batch, &upload_info.blob_id).await?;
-
- uploaded += batch.len();
- bytes += encrypted.ciphertext.len();
- }
-
- *self.last_sync.write().await = Some(Utc::now());
-
- Ok(SyncResult {
- uploaded_count: uploaded,
- uploaded_bytes: bytes,
- errors: vec![],
- })
- }
-
- /// Search historical data (local + cloud)
- pub async fn search(&self, query: &str, time_range: Option<TimeRange>) -> Result<Vec<SearchResult>> {
- let search_key = self.search_key.as_ref()
- .ok_or(SyncError::NotInitialized)?;
-
- // 1. Search local cache first
- let local_results = self.search_local(&query, time_range).await?;
-
- // 2. Generate search tokens for cloud query
- let keywords = self.extract_keywords(query);
- let tokens: Vec<_> = keywords.iter()
- .map(|kw| generate_search_token(search_key, kw))
- .collect();
-
- // 3. Search cloud index
- let cloud_matches = self.api_client.search(SearchRequest {
- search_tokens: tokens.iter().map(|t| base64::encode(t)).collect(),
- time_range,
- limit: Some(100),
- }).await?;
-
- // 4. Download matching blobs if not in cache
- let mut all_results = local_results;
-
- for match_info in cloud_matches {
- if !self.is_blob_cached(&match_info.blob_id).await {
- // Download in background or on-demand
- all_results.push(SearchResult::Pending {
- blob_id: match_info.blob_id,
- time_range: (match_info.time_start, match_info.time_end),
- estimated_download_time: self.estimate_download_time(match_info.size_bytes),
- });
- }
- }
-
- Ok(all_results)
- }
-}
-```
-
----
-
-## 5. Encryption Implementation
-
-### 5.1 Key Hierarchy
-
-```
-User Password (never stored)
- │
- ▼
- Argon2id (salt, 3 iterations, 64MB memory)
- │
- ▼
-Password-Derived Key (32 bytes)
- │
- ▼
- Encrypts ──────────────────────────────────┐
- │ │
- ▼ ▼
-Master Key (32 bytes, random) Device Keys (for future use)
- │
- ├──► Data Encryption (ChaCha20-Poly1305)
- │ └── Each blob gets unique nonce
- │
- └──► Search Key Derivation (HKDF)
- └── HMAC-SHA256 for search tokens
-```
-
-### 5.2 Dependencies
-
-Add to `screenpipe-core/Cargo.toml`:
-
-```toml
-[dependencies]
-chacha20poly1305 = "0.10"
-argon2 = "0.5"
-hmac = "0.12"
-sha2 = "0.10"
-hkdf = "0.12"
-rand = "0.8"
-base64 = "0.21"
-```
-
-### 5.3 Security Considerations
-
-1. **Password never leaves device** - Only used for key derivation
-2. **Master key encrypted at rest** - Protected by password-derived key
-3. **Unique nonce per encryption** - 12 random bytes, never reused
-4. **Authenticated encryption** - ChaCha20-Poly1305 provides integrity
-5. **Search tokens are one-way** - Cannot reverse HMAC to get keywords
-6. **Key rotation supported** - `key_version` tracks which key encrypted data
-
----
-
-## 6. AI Integration
-
-### 6.1 Tool Definition for AI
-
-```typescript
-// In AI chat context
-const tools = [{
- name: "search_historical_screen_data",
- description: "Search user's encrypted screen recording history stored in the cloud",
- parameters: {
- type: "object",
- properties: {
- query: {
- type: "string",
- description: "Natural language search query"
- },
- time_range: {
- type: "object",
- properties: {
- start: { type: "string", description: "ISO timestamp" },
- end: { type: "string", description: "ISO timestamp" }
- }
- },
- content_types: {
- type: "array",
- items: { enum: ["ocr", "audio", "all"] }
- }
- },
- required: ["query"]
- }
-}];
-```
-
-### 6.2 Handling Slow Cloud Queries
-
-```typescript
-// In AI response handler
-async function handleHistoricalSearch(params: SearchParams): Promise<SearchResponse> {
- // 1. Search local cache (fast)
- const localResults = await searchLocal(params);
-
- // 2. Search cloud (may be slow)
- const cloudPromise = searchCloud(params);
-
- // 3. Race with timeout
- const cloudResults = await Promise.race([
- cloudPromise,
- new Promise(resolve => setTimeout(() => resolve({ timeout: true }), 3000))
- ]);
-
- if (cloudResults.timeout) {
- // Return partial results, continue in background
- return {
- results: localResults,
- status: "fetching_more",
- message: "Found recent results. Still searching older data...",
- callback_id: startBackgroundFetch(params)
- };
- }
-
- return {
- results: [...localResults, ...cloudResults],
- status: "complete"
- };
-}
-```
-
-### 6.3 Progressive Loading UI
-
-```tsx
-// In chat component
-function SearchResultsMessage({ results, status, onMoreLoaded }) {
- const [additionalResults, setAdditionalResults] = useState([]);
-
- useEffect(() => {
- if (status === "fetching_more") {
- // Listen for background fetch completion
- const unsubscribe = listen("search-results-ready", (event) => {
- setAdditionalResults(event.payload.results);
- onMoreLoaded?.(event.payload.results);
- });
- return unsubscribe;
- }
- }, [status]);
-
- return (
- <div>
- {results.map(r => <SearchResult key={r.id} result={r} />)}
-
- {status === "fetching_more" && (
- <div className="flex items-center gap-2 text-muted-foreground">
- <Loader2 className="animate-spin h-4 w-4" />
- <span>Fetching older data from cloud...</span>
- </div>
- )}
-
- {additionalResults.map(r => <SearchResult key={r.id} result={r} />)}
- </div>
- );
-}
-```
-
----
-
-## 7. Cross-Platform Sync
-
-### 7.1 What Syncs Across Platforms
-
-| Data Type | Cross-Platform? | Notes |
-|-----------|-----------------|-------|
-| OCR text | Yes | Universal |
-| Audio transcriptions | Yes | Universal |
-| Timestamps | Yes | UTC everywhere |
-| App names | Yes | May differ slightly |
-| Window titles | Yes | Universal |
-| Frame thumbnails | Yes | Resolution may vary |
-| Full frames | Yes | Quality may vary |
-
-### 7.2 Platform-Specific Considerations
-
-```rust
-// In sync protocol
-#[derive(Serialize, Deserialize)]
-pub struct SyncableFrame {
- pub id: i64,
- pub timestamp: DateTime<Utc>,
-
- // Universal fields
- pub ocr_text: String,
- pub window_title: String,
-
- // Platform-tagged fields
- pub app_name: String,
- pub source_os: String, // "macos", "windows", "linux"
- pub source_device_id: String,
-
- // Optional: normalized app identifier
- pub app_identifier: Option<String>, // e.g., "com.google.Chrome"
-}
-```
-
-### 7.3 Unified Timeline View
-
-```tsx
-// Timeline shows data from all devices
-function UnifiedTimeline({ frames }) {
- return (
- <div>
- {frames.map(frame => (
- <TimelineFrame
- key={frame.id}
- frame={frame}
- deviceBadge={
- <DeviceBadge
- os={frame.source_os}
- deviceName={frame.source_device_name}
- />
- }
- />
- ))}
- </div>
- );
-}
-```
-
----
-
-## 8. Pricing & Stripe Integration
-
-### 8.1 Pricing Tiers
-
-| Tier | Price | Storage | Devices | Retention |
-|------|-------|---------|---------|-----------|
-| Free | $0 | Local only | 1 | - |
-| Sync Starter | $12/mo | 20 GB | 3 | 6 months |
-| Sync Pro | $24/mo | 100 GB | 10 | 2 years |
-| Sync Team | $49/mo | 500 GB | Unlimited | Unlimited |
-
-### 8.2 Stripe Product Setup
-
-```typescript
-// Create products in Stripe
-const products = [
- {
- name: "Screenpipe Sync Starter",
- metadata: {
- tier: "starter",
- storage_bytes: String(20 * 1024 * 1024 * 1024), // 20 GB
- device_limit: "3",
- retention_days: "180",
- },
- default_price: {
- unit_amount: 1200, // $12.00
- currency: "usd",
- recurring: { interval: "month" },
- },
- },
- // ... similar for Pro and Team
-];
-```
-
-### 8.3 Webhook Handler
-
-```typescript
-// app/api/sync/webhook/route.ts (or extend existing stripe-webhook-cloud)
-
-case "customer.subscription.created":
-case "customer.subscription.updated":
- const subscription = event.data.object as Stripe.Subscription;
- const priceId = subscription.items.data[0].price.id;
-
- // Look up tier from price metadata
- const price = await stripe.prices.retrieve(priceId);
- const product = await stripe.products.retrieve(price.product as string);
-
- const tier = product.metadata.tier;
- const storageLimit = parseInt(product.metadata.storage_bytes);
- const deviceLimit = parseInt(product.metadata.device_limit);
-
- // Update cloud_subscriptions
- await supabase.from("cloud_subscriptions").upsert({
- user_id: userId,
- stripe_subscription_id: subscription.id,
- status: subscription.status,
- sync_tier: tier,
- storage_limit_bytes: storageLimit,
- device_limit: deviceLimit,
- // ...
- });
- break;
-```
-
----
-
-## 9. Implementation Phases
-
-### Phase 1: Foundation (Weeks 1-3)
-
-**Goal**: Basic encryption infrastructure
-
-- [ ] Add encryption dependencies to `screenpipe-core`
-- [ ] Implement `EncryptionKey` with Argon2id + ChaCha20-Poly1305
-- [ ] Create `sync_keys` table migration
-- [ ] Implement `/api/sync/init` endpoint
-- [ ] Add `sync_init` and `sync_unlock` Tauri commands
-- [ ] Basic key storage in Tauri secure store
-
-**Deliverable**: User can set sync password and derive encryption keys
-
-### Phase 2: Upload Pipeline (Weeks 4-6)
-
-**Goal**: Encrypted upload to cloud
-
-- [ ] Create remaining database migrations
-- [ ] Implement `/api/sync/upload` endpoint
-- [ ] Add S3 bucket configuration for sync data
-- [ ] Implement `SyncManager.sync_up()` in Rust
-- [ ] Background sync worker with scheduling
-- [ ] Storage quota tracking
-
-**Deliverable**: Local data automatically uploads encrypted to cloud
-
-### Phase 3: Download & Search (Weeks 7-8)
-
-**Goal**: Retrieve and search cloud data
-
-- [ ] Implement `/api/sync/download` endpoint
-- [ ] Implement `/api/sync/search` endpoint
-- [ ] Search token generation and matching
-- [ ] Local blob cache management
-- [ ] `SyncManager.search()` implementation
-
-**Deliverable**: User can search historical data from cloud
-
-### Phase 4: Multi-Device (Weeks 9-10)
-
-**Goal**: Sync across devices
-
-- [ ] Device registration and management
-- [ ] Key exchange protocol for new devices
-- [ ] Conflict resolution for concurrent edits
-- [ ] Device list UI in settings
-- [ ] Cross-device timeline view
-
-**Deliverable**: Data syncs between multiple devices
-
-### Phase 5: AI Integration (Weeks 11-12)
-
-**Goal**: AI can query cloud data
-
-- [ ] Tool definition for historical search
-- [ ] Progressive loading in chat UI
-- [ ] Background fetch with notifications
-- [ ] Latency handling (timeout, partial results)
-
-**Deliverable**: AI assistant can answer questions about old screen data
-
-### Phase 6: Polish & Launch (Weeks 13-14)
-
-**Goal**: Production ready
-
-- [ ] Stripe integration for sync tiers
-- [ ] Settings UI for sync management
-- [ ] Storage usage dashboard
-- [ ] Error handling and retry logic
-- [ ] Documentation
-- [ ] Beta testing
-
-**Deliverable**: Feature ready for public launch
-
----
-
-## 10. File-by-File Changes
-
-### Backend (screen-pipe-website)
-
-| File | Action | Description |
-|------|--------|-------------|
-| `supabase/migrations/20260201_add_cloud_sync.sql` | Create | Database schema |
-| `types_db.ts` | Modify | Add new table types (regenerate) |
-| `app/api/sync/init/route.ts` | Create | Key initialization |
-| `app/api/sync/devices/route.ts` | Create | Device management |
-| `app/api/sync/upload/route.ts` | Create | Upload presigned URLs |
-| `app/api/sync/download/route.ts` | Create | Download presigned URLs |
-| `app/api/sync/search/route.ts` | Create | Search encrypted index |
-| `app/api/sync/status/route.ts` | Create | Sync status |
-| `app/api/sync/key-rotation/route.ts` | Create | Key rotation |
-| `app/api/stripe-webhook-cloud/route.ts` | Modify | Handle sync tiers |
-| `app/api/tauri/route.ts` | Modify | Return sync status |
-| `app/utils/s3.ts` | Modify | Add sync bucket functions |
-| `middleware.ts` | Modify | Add sync routes |
-
-### Desktop App (screenpipe-app-tauri)
-
-| File | Action | Description |
-|------|--------|-------------|
-| `src-tauri/Cargo.toml` | Modify | Add crypto dependencies |
-| `src-tauri/src/sync/mod.rs` | Create | Module exports |
-| `src-tauri/src/sync/manager.rs` | Create | Main sync coordinator |
-| `src-tauri/src/sync/encryption.rs` | Create | Encryption wrapper |
-| `src-tauri/src/sync/keys.rs` | Create | Key management |
-| `src-tauri/src/sync/worker.rs` | Create | Background worker |
-| `src-tauri/src/sync/protocol.rs` | Create | API client |
-| `src-tauri/src/commands/sync.rs` | Create | Tauri commands |
-| `src-tauri/src/lib.rs` | Modify | Register sync commands |
-| `components/settings/sync-settings.tsx` | Create | Sync settings UI |
-| `lib/hooks/use-sync.ts` | Create | Sync React hook |
-| `lib/utils/tauri.ts` | Modify | Add sync command types |
-
-### Core Library (screenpipe-core)
-
-| File | Action | Description |
-|------|--------|-------------|
-| `Cargo.toml` | Modify | Add crypto dependencies |
-| `src/encryption/mod.rs` | Create | Encryption primitives |
-| `src/encryption/keys.rs` | Create | Key derivation |
-| `src/encryption/search.rs` | Create | Search token generation |
-| `src/lib.rs` | Modify | Export encryption module |
-
----
-
-## Appendix: Security Audit Checklist
-
-Before launch, verify:
-
-- [ ] Password never transmitted to server
-- [ ] Master key never stored in plaintext
-- [ ] All network traffic over HTTPS
-- [ ] Nonces never reused
-- [ ] Auth tags verified on decrypt
-- [ ] RLS policies enforce user isolation
-- [ ] Rate limiting on sync endpoints
-- [ ] Audit logging for all operations
-- [ ] Key rotation works correctly
-- [ ] Device removal revokes access
-- [ ] Data deletion is complete
diff --git a/CLOUD_SYNC_NEXT_STEPS.md b/CLOUD_SYNC_NEXT_STEPS.md
deleted file mode 100644
index 74fb9a9bc..000000000
--- a/CLOUD_SYNC_NEXT_STEPS.md
+++ /dev/null
@@ -1,409 +0,0 @@
-# Cloud Sync Implementation Plan - Next Steps
-
-## Current Status ✅
-- Database migration (tables, RPC functions, triggers)
-- Backend API routes (init, upload, download, search, status, devices)
-- Unit tests (29 passing)
-- TypeScript types
-
----
-
-## Phase 1: Rust Encryption Module
-
-**Location**: `screenpipe-core/src/sync/` (new module)
-
-### 1.1 Crypto Primitives
-```rust
-// crypto.rs
-- argon2id_derive_key(password, salt) -> DerivedKey
-- chacha20_encrypt(data, key, nonce) -> EncryptedData
-- chacha20_decrypt(encrypted, key, nonce) -> Data
-- hmac_sha256(data, key) -> Token
-- generate_nonce() -> [u8; 12]
-- generate_salt() -> [u8; 32]
-```
-
-**Crates needed**:
-- `argon2` - key derivation
-- `chacha20poly1305` - encryption
-- `hmac` + `sha2` - search tokens
-- `rand` - nonce/salt generation
-
-### 1.2 Key Management
-```rust
-// keys.rs
-struct SyncKeys {
- master_key: [u8; 32],
- data_key: [u8; 32], // derived from master
- search_key: [u8; 32], // derived from master
-}
-
-- derive_keys_from_password(password, salt, encrypted_master_key) -> SyncKeys
-- generate_new_master_key() -> (MasterKey, EncryptedMasterKey, Salt)
-- rotate_master_key(old_keys, new_password) -> NewKeys
-```
-
-### 1.3 Blob Encryption
-```rust
-// blob.rs
-struct EncryptedBlob {
- ciphertext: Vec<u8>,
- nonce: [u8; 12],
- checksum: String, // SHA256 of plaintext
-}
-
-- encrypt_blob(data, data_key) -> EncryptedBlob
-- decrypt_blob(encrypted, data_key) -> Data
-- generate_search_tokens(text, search_key) -> Vec<Token>
-```
-
----
-
-## Phase 2: Sync Client
-
-**Location**: `screenpipe-core/src/sync/client.rs`
-
-### 2.1 API Client
-```rust
-struct SyncClient {
- base_url: String,
- auth_token: String,
- device_id: String,
-}
-
-impl SyncClient {
- // Auth & Init
- async fn init(password, device_info) -> Result<SyncKeys>
-
- // Upload
- async fn request_upload(blob_meta) -> Result<UploadUrl>
- async fn upload_to_s3(url, encrypted_data) -> Result<()>
- async fn complete_upload(blob_id) -> Result<()>
-
- // Download
- async fn get_download_urls(blob_ids) -> Result<Vec<DownloadInfo>>
- async fn download_from_s3(url) -> Result<EncryptedData>
-
- // Search
- async fn search(tokens, time_range) -> Result<Vec<BlobMatch>>
-
- // Status
- async fn get_status() -> Result<SyncStatus>
- async fn list_devices() -> Result<Vec<Device>>
-}
-```
-
-### 2.2 Data Packager
-```rust
-// packager.rs
-// Bundles screenpipe data into uploadable blobs
-
-struct BlobPackager {
- db: DatabaseConnection,
- keys: SyncKeys,
-}
-
-impl BlobPackager {
- // Package frames from time range into encrypted blob
- async fn package_frames(start, end) -> Result<EncryptedBlob>
-
- // Package audio chunks
- async fn package_audio(start, end) -> Result<EncryptedBlob>
-
- // Package transcripts + OCR (text-only, smaller)
- async fn package_text(start, end) -> Result<EncryptedBlob>
-
- // Extract search tokens from text content
- fn extract_tokens(text) -> Vec<String>
-}
-```
-
-### 2.3 Data Unpacker
-```rust
-// unpacker.rs
-// Decrypts and imports cloud data into local DB
-
-struct BlobUnpacker {
- db: DatabaseConnection,
- keys: SyncKeys,
-}
-
-impl BlobUnpacker {
- async fn unpack_and_import(encrypted_blob, blob_type) -> Result<()>
-}
-```
-
----
-
-## Phase 3: Sync Service
-
-**Location**: `screenpipe-server/src/sync_service.rs`
-
-### 3.1 Background Sync Manager
-```rust
-struct SyncService {
- client: SyncClient,
- packager: BlobPackager,
- config: SyncConfig,
-}
-
-struct SyncConfig {
- enabled: bool,
- sync_interval_minutes: u32,
- sync_types: Vec<BlobType>, // frames, audio, text
- bandwidth_limit_mbps: Option<u32>,
-}
-
-impl SyncService {
- // Main sync loop
- async fn start_background_sync(&self)
-
- // Upload new local data to cloud
- async fn sync_upload(&self) -> Result<SyncReport>
-
- // Track what's been synced
- async fn get_last_sync_time(&self) -> Option<DateTime>
- async fn mark_synced(&self, blob_id, time_range)
-}
-```
-
-### 3.2 Sync State Tracking
-```sql
--- New local table to track what's synced
-CREATE TABLE sync_state (
- id INTEGER PRIMARY KEY,
- blob_type TEXT NOT NULL,
- time_start TIMESTAMP NOT NULL,
- time_end TIMESTAMP NOT NULL,
- cloud_blob_id TEXT NOT NULL,
- synced_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-```
-
----
-
-## Phase 4: Settings UI
-
-**Location**: `screenpipe-app-tauri/components/settings/sync-settings.tsx`
-
-### 4.1 Components
-```
-SyncSettings
-├── SyncToggle (enable/disable)
-├── SyncLogin (email/password for cloud account)
-├── SyncStatus
-│ ├── StorageUsage (progress bar: 30GB / 100GB)
-│ ├── LastSyncTime
-│ └── SyncHealth (connected, syncing, error)
-├── DeviceList
-│ ├── CurrentDevice
-│ └── OtherDevices (with remove button)
-├── SyncOptions
-│ ├── SyncFrequency (dropdown: 5min, 15min, 1hr, manual)
-│ ├── DataTypes (checkboxes: frames, audio, transcripts)
-│ └── BandwidthLimit (optional)
-└── DangerZone
- ├── DeleteCloudData
- └── UnlinkDevice
-```
-
-### 4.2 Tauri Commands
-```rust
-// src-tauri/src/commands/sync.rs
-#[tauri::command]
-async fn sync_init(password: String) -> Result<SyncInitResponse>
-
-#[tauri::command]
-async fn sync_get_status() -> Result<SyncStatus>
-
-#[tauri::command]
-async fn sync_trigger_now() -> Result<()>
-
-#[tauri::command]
-async fn sync_set_config(config: SyncConfig) -> Result<()>
-
-#[tauri::command]
-async fn sync_list_devices() -> Result<Vec<Device>>
-
-#[tauri::command]
-async fn sync_remove_device(device_id: String) -> Result<()>
-```
-
----
-
-## Phase 5: AI Integration
-
-**Location**: Modify existing AI/chat flow
-
-### 5.1 Query Flow
-```
-User: "What did I work on in January?"
- ↓
-Check local DB for January data
- ↓
-If gaps exist (data in cloud but not local):
- ↓
- 1. Generate search tokens for query
- 2. Search cloud index
- 3. Download matching blobs
- 4. Decrypt and cache locally (temp)
- 5. Merge with local results
- ↓
-Send combined context to AI
-```
-
-### 5.2 Cloud Query Helper
-```rust
-// screenpipe-server/src/cloud_query.rs
-struct CloudQueryHelper {
- sync_client: SyncClient,
- unpacker: BlobUnpacker,
- keys: SyncKeys,
-}
-
-impl CloudQueryHelper {
- // Check if time range has cloud data not yet local
- async fn needs_cloud_data(&self, start, end) -> bool
-
- // Fetch and decrypt cloud data for time range
- async fn fetch_cloud_data(&self, start, end, query_keywords) -> Result<Vec<Frame/Audio/Text>>
-
- // Merge local + cloud results
- async fn query_all(&self, start, end, keywords) -> Result<MergedResults>
-}
-```
-
-### 5.3 Modify Existing Search
-```rust
-// In screenpipe-server/src/server.rs or wherever search lives
-// Add cloud fallback to existing search endpoint
-
-async fn search(query: SearchQuery) -> Result<SearchResults> {
- let local_results = search_local_db(&query).await?;
-
- if sync_enabled && query.include_cloud {
- let cloud_results = cloud_helper.fetch_cloud_data(
- query.start,
- query.end,
- query.keywords
- ).await?;
-
- return Ok(merge_results(local_results, cloud_results));
- }
-
- Ok(local_results)
-}
-```
-
----
-
-## Phase 6: Stripe Integration
-
-**Location**: `screen-pipe-website/app/api/webhooks/stripe/`
-
-### 6.1 New Products
-```
-Sync Starter - $5/mo
- - 20 GB storage
- - 3 devices
- - 6 months retention
-
-Sync Pro - $15/mo
- - 100 GB storage
- - 10 devices
- - Unlimited retention
-
-Sync Team - $30/mo
- - 500 GB storage
- - Unlimited devices
- - Priority support
-```
-
-### 6.2 Webhook Handler Update
-```typescript
-// Handle subscription created/updated
-if (event.type === 'customer.subscription.created' ||
- event.type === 'customer.subscription.updated') {
-
- const syncTier = getSyncTierFromPrice(subscription.items[0].price.id);
-
- if (syncTier) {
- await supabase
- .from('cloud_subscriptions')
- .upsert({
- user_id: userId,
- sync_tier: syncTier,
- storage_limit_bytes: TIER_LIMITS[syncTier].storage,
- device_limit: TIER_LIMITS[syncTier].devices,
- status: 'active'
- });
- }
-}
-```
-
----
-
-## Implementation Order
-
-1. **Phase 1** - Rust Encryption (foundation, everything depends on this)
-2. **Phase 2** - Sync Client (API communication)
-3. **Phase 3** - Sync Service (background uploads)
-4. **Phase 4** - Settings UI (user can enable/configure)
-5. **Phase 6** - Stripe (monetization)
-6. **Phase 5** - AI Integration (query cloud data)
-
----
-
-## Files to Create/Modify
-
-### New Files
-```
-screenpipe-core/src/sync/
-├── mod.rs
-├── crypto.rs
-├── keys.rs
-├── blob.rs
-├── client.rs
-├── packager.rs
-└── unpacker.rs
-
-screenpipe-server/src/
-├── sync_service.rs
-└── cloud_query.rs
-
-screenpipe-app-tauri/
-├── components/settings/sync-settings.tsx
-└── src-tauri/src/commands/sync.rs
-
-screen-pipe-website/
-└── (already done - API routes)
-```
-
-### Modified Files
-```
-screenpipe-core/src/lib.rs # Export sync module
-screenpipe-server/src/server.rs # Add cloud search fallback
-screenpipe-app-tauri/src-tauri/
-├── src/main.rs # Register sync commands
-└── Cargo.toml # Add crypto crates
-```
-
----
-
-## Estimated Effort
-
-| Phase | Effort |
-|-------|--------|
-| Phase 1 - Encryption | 1-2 days |
-| Phase 2 - Client | 1-2 days |
-| Phase 3 - Sync Service | 1 day |
-| Phase 4 - Settings UI | 1 day |
-| Phase 5 - AI Integration | 1 day |
-| Phase 6 - Stripe | 0.5 day |
-| **Total** | **~1 week** |
-
----
-
-## Start Command
-
-When ready, say "start phase 1" and I'll implement the Rust encryption module.
diff --git a/content/docs-mintlify-mig-tmp/cloud-sync.mdx b/content/docs-mintlify-mig-tmp/cloud-sync.mdx
new file mode 100644
index 000000000..8def59fee
--- /dev/null
+++ b/content/docs-mintlify-mig-tmp/cloud-sync.mdx
@@ -0,0 +1,80 @@
+---
+title: "cloud sync - zero-knowledge encryption"
+sidebarTitle: "cloud sync"
+description: "Learn how screenpipe cloud sync keeps your data encrypted and private with zero-knowledge encryption."
+icon: "cloud"
+---
+
+cloud sync lets you access your screenpipe data across all your devices with end-to-end encryption. we use zero-knowledge encryption, meaning we physically cannot read your data.
+
+## zero-knowledge encryption
+
+your data is encrypted on your device before it ever leaves. we use your password to derive an encryption key locally - this key never leaves your device and we never see it.
+
+this means we physically cannot read your data, even if we wanted to. only you (and anyone you share your password with) can decrypt your data.
+
+## how it works
+
+<Steps>
+ <Step title="you set a password">
+ this password is used to derive your encryption key using argon2id (a secure key derivation function).
+ </Step>
+ <Step title="data is encrypted locally">
+ before any data leaves your device, it's encrypted using chacha20-poly1305 (a fast, secure cipher).
+ </Step>
+ <Step title="encrypted data is uploaded">
+ only encrypted blobs are sent to our servers. we store them but cannot read them.
+ </Step>
+ <Step title="other devices decrypt locally">
+ when you access data from another device, it's downloaded and decrypted on that device using your password.
+ </Step>
+</Steps>
+
+## what we store
+
+- encrypted blobs (we cannot read these)
+- your account email
+- encrypted master key (encrypted with your password - we cannot decrypt it)
+- salt for key derivation (not secret, needed to derive the same key)
+- device metadata (device name, os, last sync time)
+
+## what we cannot see
+
+<CardGroup cols={2}>
+ <Card title="your screen recordings" icon="display">
+ all visual data is encrypted
+ </Card>
+ <Card title="your audio transcriptions" icon="microphone">
+ all audio data is encrypted
+ </Card>
+ <Card title="your ocr text" icon="text">
+ all extracted text is encrypted
+ </Card>
+ <Card title="your encryption password" icon="key">
+ never leaves your device
+ </Card>
+ <Card title="your encryption key" icon="lock">
+ derived locally, never transmitted
+ </Card>
+ <Card title="any of your actual data" icon="shield">
+ we only see encrypted blobs
+ </Card>
+</CardGroup>
+
+## verify it yourself
+
+screenpipe is open source. you can audit the encryption code yourself:
+
+<Card title="view encryption source code" icon="github" href="https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-core/src/sync.rs">
+ review the rust implementation of our zero-knowledge encryption
+</Card>
+
+## important notes
+
+<Warning>
+if you forget your encryption password, your cloud data cannot be recovered. we recommend using a password manager.
+</Warning>
+
+<Info>
+cloud sync requires a screenpipe pro subscription. sync happens automatically in the background and uses approximately 0.8 gb per monitor per day.
+</Info>
diff --git a/content/docs-mintlify-mig-tmp/docs.json b/content/docs-mintlify-mig-tmp/docs.json
index 6f5a413d0..8cf1e1c96 100644
--- a/content/docs-mintlify-mig-tmp/docs.json
+++ b/content/docs-mintlify-mig-tmp/docs.json
@@ -27,7 +27,7 @@
},
{
"group": "guides",
- "pages": ["mcp-server", "mcp-apps"]
+ "pages": ["mcp-server", "mcp-apps", "cloud-sync"]
},
{
"group": "integrations",
diff --git a/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx b/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx
index 714a9aed3..ef8b22c53 100644
--- a/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx
+++ b/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx
@@ -21,9 +21,11 @@ interface TimelineSliderProps {
}
interface AppGroup {
- appName: string;
+ appName: string; // Primary app (for backwards compatibility)
+ appNames: string[]; // All unique apps in this group
frames: StreamTimeSeriesResponse[];
color: string;
+ colors: string[]; // Colors for all apps
iconSrc?: string;
}
@@ -48,6 +50,15 @@ export function getFrameAppName(frame: StreamTimeSeriesResponse | undefined): st
return deviceWithApp?.metadata?.app_name || 'Unknown';
}
+// Get ALL app names from a frame (for multi-app display)
+export function getFrameAppNames(frame: StreamTimeSeriesResponse | undefined): string[] {
+ if (!frame?.devices?.length) return ['Unknown'];
+ const appNames = frame.devices
+ .map(d => d.metadata?.app_name)
+ .filter((name): name is string => Boolean(name));
+ return appNames.length > 0 ? [...new Set(appNames)] : ['Unknown'];
+}
+
export const TimelineSlider = ({
frames = [],
currentIndex,
@@ -226,31 +237,43 @@ export const TimelineSlider = ({
const groups: AppGroup[] = [];
let currentApp = "";
let currentGroup: StreamTimeSeriesResponse[] = [];
+ let currentGroupAllApps = new Set<string>();
visibleFrames.forEach((frame) => {
const appName = getFrameAppName(frame);
+ const allAppsInFrame = getFrameAppNames(frame);
+
if (appName !== currentApp) {
if (currentGroup.length > 0) {
+ const allApps = [...currentGroupAllApps];
groups.push({
appName: currentApp,
+ appNames: allApps,
frames: currentGroup,
color: stringToColor(currentApp),
+ colors: allApps.map(app => stringToColor(app)),
});
}
currentApp = appName;
currentGroup = [frame];
+ currentGroupAllApps = new Set(allAppsInFrame);
} else {
currentGroup.push(frame);
+ allAppsInFrame.forEach(app => currentGroupAllApps.add(app));
}
});
if (currentGroup.length > 0) {
+ const allApps = [...currentGroupAllApps];
groups.push({
appName: currentApp,
+ appNames: allApps,
frames: currentGroup,
color: stringToColor(currentApp),
+ colors: allApps.map(app => stringToColor(app)),
});
}
+
return groups;
}, [visibleFrames]);
@@ -506,31 +529,108 @@ export const TimelineSlider = ({
borderLeft: groupIndex > 0 ? '1px solid rgba(255,255,255,0.1)' : 'none',
}}
>
- {/* App icon and label - improved visibility */}
- <div
- className="absolute top-0 left-1/2 -translate-x-1/2 flex items-center gap-1.5 z-10 pointer-events-none"
+ {/* Stacked app icons - vertical stack, hover to expand */}
+ <motion.div
+ className="absolute top-0 left-1/2 -translate-x-1/2 z-20"
style={{ direction: 'ltr' }}
+ initial={false}
>
- <div className="w-5 h-5 rounded-md bg-card/90 border border-border/50 p-0.5 shadow-sm">
- <img
- src={`http://localhost:11435/app-icon?name=${encodeURIComponent(group.appName)}`}
- className="w-full h-full opacity-80 rounded-sm"
- alt={group.appName}
- loading="lazy"
- decoding="async"
- />
- </div>
- {showLabel && (
- <span
- className={cn(
- "text-[10px] font-medium text-foreground/70 bg-background/60 backdrop-blur-sm px-1.5 py-0.5 rounded truncate",
- showFullLabel ? "max-w-[100px]" : "max-w-[50px]"
+ <motion.div
+ className="relative flex flex-col items-start pointer-events-auto cursor-pointer"
+ whileHover="expanded"
+ initial="collapsed"
+ >
+ {/* Vertical stack of icons */}
+ <div className="relative">
+ {group.appNames.slice(0, 4).map((appName, idx) => (
+ <motion.div
+ key={`${appName}-${idx}`}
+ className="flex items-center"
+ style={{ zIndex: 20 - idx }}
+ variants={{
+ collapsed: {
+ marginTop: idx === 0 ? 0 : -10,
+ height: 20,
+ },
+ expanded: {
+ marginTop: idx === 0 ? 0 : 2,
+ height: 20,
+ }
+ }}
+ transition={{ type: "spring", stiffness: 400, damping: 25 }}
+ >
+ {/* Icon */}
+ <motion.div
+ className={cn(
+ "w-5 h-5 rounded-md bg-card border p-0.5 shadow-md flex-shrink-0",
+ idx === 0 ? "border-foreground/40" : "border-border/50"
+ )}
+ variants={{
+ collapsed: {
+ scale: 1,
+ opacity: idx < 3 ? 1 : 0.5,
+ },
+ expanded: {
+ scale: 1,
+ opacity: 1,
+ }
+ }}
+ whileHover={{ scale: 1.1 }}
+ transition={{ type: "spring", stiffness: 400, damping: 25 }}
+ >
+ <img
+ src={`http://localhost:11435/app-icon?name=${encodeURIComponent(appName)}`}
+ className="w-full h-full rounded-sm"
+ alt={appName}
+ loading="lazy"
+ decoding="async"
+ />
+ </motion.div>
+ {/* App name label - appears on hover */}
+ <motion.span
+ className="ml-2 text-[9px] font-medium text-foreground bg-background/95 backdrop-blur-sm px-1.5 py-0.5 rounded shadow-md whitespace-nowrap border border-border/30"
+ variants={{
+ collapsed: { opacity: 0, width: 0, marginLeft: 0 },
+ expanded: { opacity: 1, width: "auto", marginLeft: 8 }
+ }}
+ transition={{ type: "spring", stiffness: 400, damping: 25, delay: idx * 0.02 }}
+ >
+ {appName.length > 15 ? appName.slice(0, 12) + '…' : appName}
+ </motion.span>
+ </motion.div>
+ ))}
+ {/* +N indicator for overflow */}
+ {group.appNames.length > 4 && (
+ <motion.div
+ className="flex items-center"
+ style={{ zIndex: 15 }}
+ variants={{
+ collapsed: { marginTop: -10, height: 20 },
+ expanded: { marginTop: 2, height: 20 }
+ }}
+ transition={{ type: "spring", stiffness: 400, damping: 25 }}
+ >
+ <div className="w-5 h-5 rounded-md bg-muted border border-border/50 flex items-center justify-center text-[8px] font-medium text-foreground/70">
+ +{group.appNames.length - 4}
+ </div>
+ </motion.div>
)}
- >
- {group.appName}
- </span>
- )}
- </div>
+ </div>
+ {/* Badge showing total app count - only in collapsed state */}
+ {group.appNames.length > 1 && (
+ <motion.div
+ className="absolute -right-2 -top-1 min-w-[14px] h-[14px] rounded-full bg-foreground text-background text-[8px] font-bold flex items-center justify-center shadow-sm"
+ variants={{
+ collapsed: { scale: 1, opacity: 1 },
+ expanded: { scale: 0, opacity: 0 }
+ }}
+ transition={{ type: "spring", stiffness: 400, damping: 25 }}
+ >
+ {group.appNames.length}
+ </motion.div>
+ )}
+ </motion.div>
+ </motion.div>
{group.frames.map((frame, frameIdx) => {
// O(1) lookup instead of O(n) indexOf
@@ -555,7 +655,7 @@ export const TimelineSlider = ({
return (
<motion.div
- key={frame.timestamp}
+ key={`${frame.timestamp}-${frameIdx}`}
data-timestamp={frame.timestamp}
className={cn(
"flex-shrink-0 cursor-ew-resize rounded-t relative hover:z-50 transition-all duration-200",
diff --git a/screenpipe-app-tauri/components/settings/sync-settings.tsx b/screenpipe-app-tauri/components/settings/sync-settings.tsx
index 3cb63861e..6243b8cf6 100644
--- a/screenpipe-app-tauri/components/settings/sync-settings.tsx
+++ b/screenpipe-app-tauri/components/settings/sync-settings.tsx
@@ -209,7 +209,7 @@ function SyncOnboarding({ onSubscribe, onRefresh, isLoading, isRefreshing }: { o
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
<a
- href="https://screenpi.pe/docs/cloud-sync"
+ href="https://docs.screenpi.pe/cloud-sync"
target="_blank"
rel="noopener noreferrer"
className="text-xs text-center text-muted-foreground mt-3 block hover:text-primary underline"
@@ -447,7 +447,7 @@ function ActiveSyncSettings({
Uses ~0.8 GB per monitor per day.
</p>
<a
- href="https://screenpi.pe/docs/cloud-sync"
+ href="https://docs.screenpi.pe/cloud-sync"
target="_blank"
rel="noopener noreferrer"
className="text-xs text-muted-foreground hover:text-primary underline"
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 8d57291aa..03f6abd1c 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.176"
+version = "2.0.178"
dependencies = [
"anyhow",
"async-stream",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 7f27631f6..d43ae9dc6 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.177"
+version = "2.0.178"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/screenpipe-audio/src/segmentation/segmentation_manager.rs b/screenpipe-audio/src/segmentation/segmentation_manager.rs
index f858845b3..28f367ccd 100644
--- a/screenpipe-audio/src/segmentation/segmentation_manager.rs
+++ b/screenpipe-audio/src/segmentation/segmentation_manager.rs
@@ -11,7 +11,7 @@ use crate::speaker::{
};
pub struct SegmentationManager {
- pub embedding_manager: EmbeddingManager,
+ pub embedding_manager: Arc<StdMutex<EmbeddingManager>>,
pub embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
pub segmentation_model_path: PathBuf,
}
@@ -27,7 +27,7 @@ impl SegmentationManager {
.ok_or_else(|| anyhow!("Invalid embedding model path"))?,
)?));
- let embedding_manager = EmbeddingManager::new(usize::MAX);
+ let embedding_manager = Arc::new(StdMutex::new(EmbeddingManager::new(usize::MAX)));
Ok(SegmentationManager {
embedding_manager,
embedding_extractor,
diff --git a/screenpipe-audio/src/speaker/prepare_segments.rs b/screenpipe-audio/src/speaker/prepare_segments.rs
index 32b55dcf7..0e4bb5b0c 100644
--- a/screenpipe-audio/src/speaker/prepare_segments.rs
+++ b/screenpipe-audio/src/speaker/prepare_segments.rs
@@ -17,7 +17,7 @@ pub async fn prepare_segments(
audio_data: &[f32],
vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
segmentation_model_path: &PathBuf,
- embedding_manager: EmbeddingManager,
+ embedding_manager: Arc<StdMutex<EmbeddingManager>>,
embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
device: &str,
) -> Result<(tokio::sync::mpsc::Receiver<SpeechSegment>, bool)> {
diff --git a/screenpipe-audio/src/speaker/segment.rs b/screenpipe-audio/src/speaker/segment.rs
index 54eda21bf..6472c766a 100644
--- a/screenpipe-audio/src/speaker/segment.rs
+++ b/screenpipe-audio/src/speaker/segment.rs
@@ -36,7 +36,7 @@ fn create_speech_segment(
samples: &[f32],
padded_samples: &[f32],
embedding_extractor: Arc<Mutex<EmbeddingExtractor>>,
- embedding_manager: &mut EmbeddingManager,
+ embedding_manager: &Arc<Mutex<EmbeddingManager>>,
) -> Result<SpeechSegment> {
let start = start_offset / sample_rate as f64;
let end = offset as f64 / sample_rate as f64;
@@ -76,7 +76,10 @@ fn create_speech_segment(
vec![0.0; 512]
}
};
- let speaker = get_speaker_from_embedding(embedding_manager, embedding.clone());
+ let speaker = {
+ let mut manager = embedding_manager.lock().unwrap();
+ get_speaker_from_embedding(&mut manager, embedding.clone())
+ };
Ok(SpeechSegment {
start,
@@ -114,7 +117,7 @@ pub struct SegmentIterator {
sample_rate: u32,
session: ort::Session,
embedding_extractor: Arc<Mutex<EmbeddingExtractor>>,
- embedding_manager: EmbeddingManager,
+ embedding_manager: Arc<Mutex<EmbeddingManager>>,
current_position: usize,
frame_size: i32,
window_size: usize,
@@ -131,7 +134,7 @@ impl SegmentIterator {
sample_rate: u32,
model_path: P,
embedding_extractor: Arc<Mutex<EmbeddingExtractor>>,
- embedding_manager: EmbeddingManager,
+ embedding_manager: Arc<Mutex<EmbeddingManager>>,
) -> Result<Self> {
let session = super::create_session(model_path.as_ref())?;
let window_size = (sample_rate * 10) as usize;
@@ -197,7 +200,7 @@ impl SegmentIterator {
&self.samples,
&self.padded_samples,
self.embedding_extractor.clone(),
- &mut self.embedding_manager,
+ &self.embedding_manager,
) {
Ok(segment) => segment,
Err(e) => {
@@ -273,7 +276,7 @@ pub fn get_segments<P: AsRef<Path>>(
sample_rate: u32,
model_path: P,
embedding_extractor: Arc<Mutex<EmbeddingExtractor>>,
- embedding_manager: EmbeddingManager,
+ embedding_manager: Arc<Mutex<EmbeddingManager>>,
) -> Result<SegmentIterator> {
SegmentIterator::new(
samples.to_vec(),
diff --git a/screenpipe-audio/src/transcription/stt.rs b/screenpipe-audio/src/transcription/stt.rs
index 253566d1f..7a92d8444 100644
--- a/screenpipe-audio/src/transcription/stt.rs
+++ b/screenpipe-audio/src/transcription/stt.rs
@@ -94,7 +94,7 @@ pub async fn process_audio_input(
audio: AudioInput,
vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
segmentation_model_path: PathBuf,
- embedding_manager: EmbeddingManager,
+ embedding_manager: Arc<StdMutex<EmbeddingManager>>,
embedding_extractor: Arc<StdMutex<EmbeddingExtractor>>,
output_path: &PathBuf,
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
diff --git a/screenpipe-audio/tests/speaker_identification.rs b/screenpipe-audio/tests/speaker_identification.rs
index 0650ce984..4d9f2605a 100644
--- a/screenpipe-audio/tests/speaker_identification.rs
+++ b/screenpipe-audio/tests/speaker_identification.rs
@@ -6,6 +6,114 @@ mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
+ /// Test that reproduces the speaker fragmentation bug.
+ ///
+ /// The bug: EmbeddingManager is cloned for each audio chunk processing,
+ /// but Clone creates an independent copy. New speakers added to the clone
+ /// are lost when the function returns, causing the same voice to get
+ /// different speaker IDs across chunks.
+ #[test]
+ fn test_embedding_manager_clone_does_not_share_state() {
+ let mut original = EmbeddingManager::new(100);
+
+ // Create embeddings with different DIRECTIONS (cosine similarity measures angle)
+ // embedding1: positive in first half, zero in second half
+ let mut embedding1 = vec![0.0; 512];
+ for i in 0..256 {
+ embedding1[i] = 1.0;
+ }
+
+ // embedding2: zero in first half, positive in second half (orthogonal to embedding1)
+ let mut embedding2 = vec![0.0; 512];
+ for i in 256..512 {
+ embedding2[i] = 1.0;
+ }
+
+ // Simulate: first audio chunk creates speaker 1
+ let speaker1 = original.search_speaker(embedding1.clone(), 0.5);
+ assert_eq!(speaker1, Some(1), "First speaker should be ID 1");
+
+ // Simulate: what happens in the audio processing loop
+ // Each call to process_audio_input gets a CLONE of embedding_manager
+ let mut cloned = original.clone();
+
+ // In the clone, add a new speaker (simulating a new voice detected)
+ let speaker2_in_clone = cloned.search_speaker(embedding2.clone(), 0.5);
+ assert_eq!(speaker2_in_clone, Some(2), "Second speaker should be ID 2 in clone");
+
+ // BUG: The original doesn't see the new speaker!
+ // When cloned goes out of scope (function returns), speaker 2 is LOST
+
+ // Next audio chunk gets another clone of original (not the modified clone)
+ let mut another_clone = original.clone();
+
+ // The same voice (embedding2) now gets a NEW ID because speaker 2 was never
+ // added to original - it only existed in the first clone which was dropped
+ let _speaker2_again = another_clone.search_speaker(embedding2.clone(), 0.5);
+
+ // The real test: original should have both speakers if state was shared properly
+ let speakers_in_original = original.get_all_speakers();
+
+ // BUG DEMONSTRATION: original only has 1 speaker, not 2
+ // This causes the 170+ "Unknown #X" speakers issue
+ assert_eq!(
+ speakers_in_original.len(),
+ 1,
+ "BUG CONFIRMED: Original only has 1 speaker, clone's additions were lost"
+ );
+
+ // What we WANT is for original to have 2 speakers after the clones added one
+ // This test documents the current buggy behavior
+ }
+
+ /// Test that shows what the CORRECT behavior should be with Arc<Mutex<>>
+ #[test]
+ fn test_embedding_manager_shared_state_with_arc_mutex() {
+ use std::sync::{Arc, Mutex as StdMutex};
+
+ let shared = Arc::new(StdMutex::new(EmbeddingManager::new(100)));
+
+ // Create embeddings with different DIRECTIONS (cosine similarity measures angle)
+ let mut embedding1 = vec![0.0; 512];
+ for i in 0..256 {
+ embedding1[i] = 1.0;
+ }
+
+ let mut embedding2 = vec![0.0; 512];
+ for i in 256..512 {
+ embedding2[i] = 1.0;
+ }
+
+ // Simulate: first audio chunk creates speaker 1
+ {
+ let mut manager = shared.lock().unwrap();
+ let speaker1 = manager.search_speaker(embedding1.clone(), 0.5);
+ assert_eq!(speaker1, Some(1));
+ }
+
+ // Simulate: second audio chunk (different "clone" but same Arc)
+ {
+ let mut manager = shared.lock().unwrap();
+ let speaker2 = manager.search_speaker(embedding2.clone(), 0.5);
+ assert_eq!(speaker2, Some(2));
+ }
+
+ // Simulate: third audio chunk - same voice as embedding2 should match
+ {
+ let mut manager = shared.lock().unwrap();
+ let speaker2_again = manager.search_speaker(embedding2.clone(), 0.5);
+ assert_eq!(speaker2_again, Some(2), "Same embedding should return same speaker");
+ }
+
+ // Verify: shared state has both speakers
+ let manager = shared.lock().unwrap();
+ assert_eq!(
+ manager.get_all_speakers().len(),
+ 2,
+ "Shared manager should have both speakers"
+ );
+ }
+
fn setup() {
// Initialize the logger with an info level filter
env_logger::builder()