YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(sync): complete encrypted cloud sync implementation (Phases 1-5) (#2131)
Louis Beaumont7df0bc3c18a2
diff --git a/Cargo.lock b/Cargo.lockindex 19f92afb0..eb0fe93a9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -53,6 +53,16 @@ version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"+[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common",+ "generic-array",+]+[[package]]name = "aes"version = "0.8.4"@@ -236,6 +246,18 @@ dependencies = ["syn 2.0.100",]+[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures",+ "password-hash 0.5.0",+]+[[package]]name = "arrayvec"version = "0.7.6"@@ -628,7 +650,7 @@ dependencies = ["bitflags 2.9.0","cexpr","clang-sys",- "itertools 0.10.5",+ "itertools 0.12.1","lazy_static","lazycell","log",@@ -651,7 +673,7 @@ dependencies = ["bitflags 2.9.0","cexpr","clang-sys",- "itertools 0.10.5",+ "itertools 0.13.0","proc-macro2","quote","regex",@@ -669,7 +691,7 @@ dependencies = ["bitflags 2.9.0","cexpr","clang-sys",- "itertools 0.10.5",+ "itertools 0.13.0","log","prettyplease","proc-macro2",@@ -733,6 +755,15 @@ version = "2.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2"+[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest",+]+[[package]]name = "block"version = "0.1.6"@@ -1078,6 +1109,30 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "chacha20"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"+dependencies = [+ "cfg-if",+ "cipher",+ "cpufeatures",+]++[[package]]+name = "chacha20poly1305"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"+dependencies = [+ "aead",+ "chacha20",+ "cipher",+ "poly1305",+ "zeroize",+]+[[package]]name = "chrono"version = "0.4.40"@@ -1145,6 +1200,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = ["crypto-common","inout",+ "zeroize",][[package]]@@ -1281,7 +1337,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"dependencies = ["lazy_static",- "windows-sys 0.48.0",+ "windows-sys 0.59.0",][[package]]@@ -1669,6 +1725,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"dependencies = ["generic-array",+ "rand_core 0.6.4","typenum",]@@ -3908,7 +3965,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"dependencies = ["cfg-if",- "windows-targets 0.48.5",+ "windows-targets 0.52.6",][[package]]@@ -5166,6 +5223,12 @@ version = "11.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"+[[package]]+name = "opaque-debug"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"+[[package]]name = "openapiv3-extended"version = "6.0.0"@@ -5330,6 +5393,17 @@ dependencies = ["subtle",]+[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "paste"version = "1.0.15"@@ -5344,7 +5418,7 @@ checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917"dependencies = ["digest","hmac",- "password-hash",+ "password-hash 0.4.2","sha2",]@@ -5527,6 +5601,17 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "poly1305"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"+dependencies = [+ "cpufeatures",+ "opaque-debug",+ "universal-hash",+]+[[package]]name = "port_check"version = "0.2.1"@@ -6558,9 +6643,13 @@ dependencies = ["accessibility","accessibility-sys","anyhow",+ "argon2",+ "async-trait",+ "base64 0.22.1","candle-core","candle-nn","candle-transformers",+ "chacha20poly1305","chrono","clap","core-foundation 0.10.0",@@ -6568,7 +6657,9 @@ dependencies = ["cron","dirs","ffmpeg-sidecar",+ "hex","hf-hub",+ "hmac","http-cache-reqwest","lazy_static","log",@@ -6582,7 +6673,9 @@ dependencies = ["sentry","serde","serde_json",+ "sha2","tempfile",+ "thiserror 1.0.69","tokenizers","tokio","tracing",@@ -6590,6 +6683,7 @@ dependencies = ["uiautomation","url","which 6.0.3",+ "zeroize","zip 0.6.6",]@@ -6655,6 +6749,7 @@ name = "screenpipe-server"version = "0.3.5"dependencies = ["anyhow",+ "async-trait","axum","base64 0.22.1","bincode",@@ -8659,6 +8754,16 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"+[[package]]+name = "universal-hash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"+dependencies = [+ "crypto-common",+ "subtle",+]+[[package]]name = "unsafe-libyaml"version = "0.2.11"@@ -9150,7 +9255,7 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.59.0",][[package]]diff --git a/packages/sync/README.md b/packages/sync/README.mdindex 9a0709008..9dbc1fd7c 100644--- a/packages/sync/README.md+++ b/packages/sync/README.md@@ -1,25 +1,23 @@-# screenpipe-sync+# @screenpipe/sync**Sync your Screenpipe data to remote AI agents.**-One-liner to permanently sync your screen memory to a remote server (e.g., [Clawdbot](https://github.com/moltinginstar/moltbot), any SSH server). Your AI agent can then query your full history via SQLite.--Also extracts structured daily summaries: todos, goals, decisions, and AI insights.+One-liner to sync daily summaries to a remote server (e.g., [Clawdbot](https://github.com/clawdbot/clawdbot)). Uses Claude Code CLI for AI-powered extraction.## Quick Start```bash-# One-liner - AI summary to stdout+# AI summary to stdoutbunx @screenpipe/sync# Save daily summaries locallybunx @screenpipe/sync --output ~/Documents/brain/context --git-# Sync raw SQLite database to remote (full history!)-bunx @screenpipe/sync --db --remote user@host:~/.screenpipe/+# Sync summaries to remote server+bunx @screenpipe/sync --output /tmp/summaries --remote user@host:~/screenpipe-pkm-# Full sync: DB + daily summary-bunx @screenpipe/sync --db -r clawdbot:~/.screenpipe && bunx @screenpipe/sync -o ~/context -g+# Persistent daemon (survives reboot)+bunx @screenpipe/sync --daemon --output /tmp/summaries --remote user@host:~/clawd/screenpipe-pkm```## What It Extracts@@ -37,28 +35,27 @@ bunx @screenpipe/sync --db -r clawdbot:~/.screenpipe && bunx @screenpipe/sync -o## Example Output```markdown-# Daily Context - 2026-01-29+# Daily Context - 2026-01-31> Analyzed 480 minutes of screen activity-## π± Apps Used+## Apps Used- **VS Code**: ~180 min- **Chrome**: ~120 min- **Slack**: ~60 min-## β Todos Extracted+## Todos Extracted- Fix authentication bug in login.ts- Review PR #234 for payment integration- Send weekly update to investors-## π― Goals Mentioned+## Goals Mentioned- Ship v2.9 by Friday- Reach 50% activation rate-## π‘ AI Insights-- Heavy context switching between Slack and VS Code (17 switches/hour)+## AI Insights+- Heavy context switching between Slack and VS Code- Deep focus block from 2-4pm on auth refactor-- Late session (after 10pm) - consider sleep impact```## Options@@ -69,79 +66,83 @@ bunx @screenpipe/sync --db -r clawdbot:~/.screenpipe && bunx @screenpipe/sync -o| `-h, --hours <n>` | Hours to analyze | 12 || `-g, --git` | Auto commit & push | false || `-r, --remote <host>` | Sync via SSH | - |+| `-d, --daemon` | Install persistent sync | false |+| `--interval <secs>` | Daemon interval | 3600 |+| `--stop` | Stop daemon | - || `--json` | JSON output | markdown || `-v, --verbose` | Debug output | false |-## Environment Variables+## AI Summarization++Uses [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) if available:```bash-# AI Provider (uses first available)-export ANTHROPIC_API_KEY="sk-..." # Claude (recommended)-export OPENAI_API_KEY="sk-..." # OpenAI fallback-export OLLAMA_URL="http://localhost:11434" # Local Ollama-export OLLAMA_MODEL="llama3.2" # Ollama model--# Screenpipe-export SCREENPIPE_URL="http://localhost:3030" # Default+# Install Claude Code CLI+npm install -g @anthropic-ai/claude-code++# Verify it works+claude --version```-**AI Priority:** Claude β OpenAI β Ollama β No AI (basic summary)+Falls back to structured extraction (no AI) if CLI not found.-## Use Cases+## Clawdbot Integration-### Daily Journaling+For daily digests via Telegram:++1. **Local Mac** syncs summaries hourly:```bash-# Run at end of day-bunx @screenpipe/sync --output ~/journal --hours 16+bunx @screenpipe/sync --daemon --output /tmp/summaries --remote clawdbot:~/clawd/screenpipe-pkm+```++2. **Clawdbot** has native cron that reads files and sends digest:+```bash+# Already configured - runs at 9pm PT+sudo docker exec moltbot-gateway node dist/index.js cron list```-### Sync to Remote AI Assistant+## Use Cases++### Daily Journaling```bash-# Sync context to Clawdbot/Moltbot instance-bunx @screenpipe/sync --output ~/brain/context --git-# Remote pulls via cron+bunx @screenpipe/sync --output ~/journal --hours 16```### Weekly Review Prep```bash-# Get full weekbunx @screenpipe/sync --hours 168 --json > week.json```-### Automated Daily Sync (cron)+### Daemon Mode (Recommended)```bash-# Add to crontab-0 22 * * * ANTHROPIC_API_KEY=sk-... bunx @screenpipe/sync -o ~/context -g+# Install persistent sync - survives reboot+bunx @screenpipe/sync --daemon -r user@host:~/screenpipe-pkm++# Check status+# macOS: cat /tmp/screenpipe-sync.log+# Linux: systemctl --user status screenpipe-sync.timer++# Stop daemon+bunx @screenpipe/sync --stop```## How It Works-### Summary Mode (default)1. **Query** - Fetches OCR data from local Screenpipe API2. **Dedupe** - Removes duplicate/similar screen captures-3. **Extract** - Claude analyzes content for structured data+3. **Extract** - Claude Code CLI analyzes for structured data4. **Format** - Outputs markdown or JSON-5. **Sync** - Optionally git pushes or SCPs to remote--### DB Sync Mode (`--db`)-1. **Copy** - Copies `~/.screenpipe/db.sqlite` (your full history)-2. **Sync** - Uses rsync/scp to transfer to remote-3. **Query** - Remote can query SQLite directly--```bash-# On remote, query your full history:-sqlite3 ~/.screenpipe/db.sqlite "SELECT text FROM ocr_text WHERE text LIKE '%meeting%' LIMIT 10;"-```+5. **Sync** - SCPs to remote server## Requirements- [Screenpipe](https://github.com/mediar-ai/screenpipe) running locally- [Bun](https://bun.sh) runtime-- Anthropic API key for AI extraction (optional but recommended)+- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) (optional, for AI extraction)## Privacy-All processing happens locally. Screen data never leaves your machine unless you explicitly sync to a remote.+All processing happens locally. Screen data never leaves your machine unless you explicitly sync summaries to a remote.## Licensediff --git a/packages/sync/src/index.ts b/packages/sync/src/index.tsindex f88e33ae3..4439fc7b0 100644--- a/packages/sync/src/index.ts+++ b/packages/sync/src/index.ts@@ -330,7 +330,7 @@ async function extractWithAI(const tmpFile = path.join(os.tmpdir(), `screenpipe-prompt-${Date.now()}.txt`);await fs.writeFile(tmpFile, prompt);- const result = execSync(`cat "${tmpFile}" | claude --print`, {+ const result = execSync(`claude --print < "${tmpFile}"`, {encoding: "utf-8",maxBuffer: 10 * 1024 * 1024,timeout: 120000, // 2 min timeoutdiff --git a/screenpipe-app-tauri/components/settings/sync-settings.tsx b/screenpipe-app-tauri/components/settings/sync-settings.tsxnew file mode 100644index 000000000..0d6ee13ea--- /dev/null+++ b/screenpipe-app-tauri/components/settings/sync-settings.tsx@@ -0,0 +1,631 @@+"use client";++import React, { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import { Card } from "@/components/ui/card";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Progress } from "@/components/ui/progress";+import { Separator } from "@/components/ui/separator";+import { Badge } from "@/components/ui/badge";+import {+ Cloud,+ CloudOff,+ RefreshCw,+ Laptop,+ Trash2,+ Lock,+ Unlock,+ HardDrive,+ Clock,+ AlertCircle,+ CheckCircle2,+ Loader2,+} from "lucide-react";+import { toast } from "@/components/ui/use-toast";+import { invoke } from "@tauri-apps/api/core";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Input } from "@/components/ui/input";++interface SyncStatus {+ enabled: boolean;+ isSyncing: boolean;+ lastSync: string | null;+ lastError: string | null;+ storageUsed: number | null;+ storageLimit: number | null;+ deviceCount: number | null;+ deviceLimit: number | null;+ syncTier: string | null;+}++interface SyncDevice {+ id: string;+ deviceId: string;+ deviceName: string | null;+ deviceOs: string;+ lastSyncAt: string | null;+ createdAt: string;+ isCurrent: boolean;+}++interface SyncConfig {+ enabled: boolean;+ syncIntervalMinutes: number;+ syncTranscripts: boolean;+ syncOcr: boolean;+ syncAudio: boolean;+ syncFrames: boolean;+}++function formatBytes(bytes: number): string {+ if (bytes === 0) return "0 B";+ const k = 1024;+ const sizes = ["B", "KB", "MB", "GB", "TB"];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];+}++function formatRelativeTime(dateString: string): string {+ const date = new Date(dateString);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMins = Math.floor(diffMs / 60000);+ const diffHours = Math.floor(diffMs / 3600000);+ const diffDays = Math.floor(diffMs / 86400000);++ if (diffMins < 1) return "just now";+ if (diffMins < 60) return `${diffMins}m ago`;+ if (diffHours < 24) return `${diffHours}h ago`;+ return `${diffDays}d ago`;+}++export function SyncSettings() {+ const [status, setStatus] = useState<SyncStatus | null>(null);+ const [devices, setDevices] = useState<SyncDevice[]>([]);+ const [config, setConfig] = useState<SyncConfig | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const [isSyncing, setIsSyncing] = useState(false);+ const [showPasswordDialog, setShowPasswordDialog] = useState(false);+ const [password, setPassword] = useState("");+ const [isInitializing, setIsInitializing] = useState(false);++ useEffect(() => {+ loadSyncData();+ }, []);++ const loadSyncData = async () => {+ try {+ setIsLoading(true);+ const [statusResult, configResult, devicesResult] = await Promise.all([+ invoke<SyncStatus>("get_sync_status"),+ invoke<SyncConfig>("get_sync_config"),+ invoke<SyncDevice[]>("get_sync_devices"),+ ]);+ setStatus(statusResult);+ setConfig(configResult);+ setDevices(devicesResult);+ } catch (error) {+ console.error("failed to load sync data:", error);+ toast({+ title: "failed to load sync settings",+ description: String(error),+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ }+ };++ const handleToggleSync = async (enabled: boolean) => {+ if (enabled && !status?.enabled) {+ // Need to initialize sync+ setShowPasswordDialog(true);+ return;+ }++ try {+ await invoke("set_sync_enabled", { enabled });+ setStatus((prev) => (prev ? { ...prev, enabled } : null));+ toast({+ title: enabled ? "sync enabled" : "sync disabled",+ description: enabled+ ? "your data will now sync to the cloud"+ : "sync has been paused",+ });+ } catch (error) {+ toast({+ title: "failed to update sync",+ description: String(error),+ variant: "destructive",+ });+ }+ };++ const handleInitSync = async () => {+ if (!password) {+ toast({+ title: "password required",+ description: "please enter a password to encrypt your data",+ variant: "destructive",+ });+ return;+ }++ try {+ setIsInitializing(true);+ const isNewUser = await invoke<boolean>("init_sync", { password });+ setShowPasswordDialog(false);+ setPassword("");++ toast({+ title: isNewUser ? "sync initialized" : "sync connected",+ description: isNewUser+ ? "your encryption keys have been generated"+ : "connected to your existing sync data",+ });++ await loadSyncData();+ } catch (error) {+ toast({+ title: "failed to initialize sync",+ description: String(error),+ variant: "destructive",+ });+ } finally {+ setIsInitializing(false);+ }+ };++ const handleTriggerSync = async () => {+ try {+ setIsSyncing(true);+ await invoke("trigger_sync");+ toast({+ title: "sync started",+ description: "syncing your data to the cloud",+ });++ // Poll for completion+ const checkSync = async () => {+ const newStatus = await invoke<SyncStatus>("get_sync_status");+ setStatus(newStatus);+ if (newStatus.isSyncing) {+ setTimeout(checkSync, 1000);+ } else {+ setIsSyncing(false);+ toast({+ title: "sync complete",+ description: "your data has been synced",+ });+ }+ };+ setTimeout(checkSync, 1000);+ } catch (error) {+ setIsSyncing(false);+ toast({+ title: "sync failed",+ description: String(error),+ variant: "destructive",+ });+ }+ };++ const handleUpdateConfig = async (updates: Partial<SyncConfig>) => {+ if (!config) return;++ const newConfig = { ...config, ...updates };+ try {+ await invoke("update_sync_config", { config: newConfig });+ setConfig(newConfig);+ } catch (error) {+ toast({+ title: "failed to update settings",+ description: String(error),+ variant: "destructive",+ });+ }+ };++ const handleRemoveDevice = async (deviceId: string) => {+ try {+ await invoke("remove_sync_device", { deviceId });+ setDevices((prev) => prev.filter((d) => d.deviceId !== deviceId));+ toast({+ title: "device removed",+ description: "the device has been unlinked from your sync",+ });+ } catch (error) {+ toast({+ title: "failed to remove device",+ description: String(error),+ variant: "destructive",+ });+ }+ };++ const handleDeleteCloudData = async () => {+ try {+ await invoke("delete_cloud_data");+ toast({+ title: "cloud data deleted",+ description: "all your cloud data has been permanently deleted",+ });+ await loadSyncData();+ } catch (error) {+ toast({+ title: "failed to delete data",+ description: String(error),+ variant: "destructive",+ });+ }+ };++ if (isLoading) {+ return (+ <div className="flex items-center justify-center p-8">+ <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />+ </div>+ );+ }++ const storagePercent =+ status?.storageUsed && status?.storageLimit+ ? (status.storageUsed / status.storageLimit) * 100+ : 0;++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ {status?.enabled ? (+ <Cloud className="h-5 w-5 text-primary" />+ ) : (+ <CloudOff className="h-5 w-5 text-muted-foreground" />+ )}+ <div>+ <h3 className="text-lg font-medium">cloud sync</h3>+ <p className="text-sm text-muted-foreground">+ sync your data across devices with end-to-end encryption+ </p>+ </div>+ </div>+ <Switch+ checked={status?.enabled ?? false}+ onCheckedChange={handleToggleSync}+ />+ </div>++ {status?.enabled && (+ <>+ <Separator />++ {/* Status Card */}+ <Card className="p-4 space-y-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ {status.isSyncing || isSyncing ? (+ <>+ <Loader2 className="h-4 w-4 animate-spin text-primary" />+ <span className="text-sm">syncing...</span>+ </>+ ) : status.lastError ? (+ <>+ <AlertCircle className="h-4 w-4 text-destructive" />+ <span className="text-sm text-destructive">+ {status.lastError}+ </span>+ </>+ ) : (+ <>+ <CheckCircle2 className="h-4 w-4 text-green-500" />+ <span className="text-sm text-muted-foreground">+ {status.lastSync+ ? `last synced ${formatRelativeTime(status.lastSync)}`+ : "never synced"}+ </span>+ </>+ )}+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={handleTriggerSync}+ disabled={isSyncing || status.isSyncing}+ >+ <RefreshCw+ className={`h-4 w-4 mr-2 ${+ isSyncing || status.isSyncing ? "animate-spin" : ""+ }`}+ />+ sync now+ </Button>+ </div>++ {/* Storage Usage */}+ {status.storageLimit && (+ <div className="space-y-2">+ <div className="flex items-center justify-between text-sm">+ <div className="flex items-center gap-2">+ <HardDrive className="h-4 w-4 text-muted-foreground" />+ <span>storage</span>+ </div>+ <span className="text-muted-foreground">+ {formatBytes(status.storageUsed ?? 0)} /{" "}+ {formatBytes(status.storageLimit)}+ </span>+ </div>+ <Progress value={storagePercent} className="h-2" />+ </div>+ )}++ {/* Tier Badge */}+ {status.syncTier && (+ <div className="flex items-center gap-2">+ <Badge variant="secondary">{status.syncTier}</Badge>+ <span className="text-sm text-muted-foreground">+ {status.deviceCount}/{status.deviceLimit} devices+ </span>+ </div>+ )}+ </Card>++ {/* Sync Options */}+ {config && (+ <>+ <Separator />+ <div className="space-y-4">+ <h4 className="text-sm font-medium">sync options</h4>++ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <Label htmlFor="sync-transcripts" className="text-sm">+ transcripts+ </Label>+ <Switch+ id="sync-transcripts"+ checked={config.syncTranscripts}+ onCheckedChange={(checked) =>+ handleUpdateConfig({ syncTranscripts: checked })+ }+ />+ </div>++ <div className="flex items-center justify-between">+ <Label htmlFor="sync-ocr" className="text-sm">+ OCR text+ </Label>+ <Switch+ id="sync-ocr"+ checked={config.syncOcr}+ onCheckedChange={(checked) =>+ handleUpdateConfig({ syncOcr: checked })+ }+ />+ </div>++ <div className="flex items-center justify-between">+ <Label htmlFor="sync-audio" className="text-sm">+ audio recordings+ </Label>+ <Switch+ id="sync-audio"+ checked={config.syncAudio}+ onCheckedChange={(checked) =>+ handleUpdateConfig({ syncAudio: checked })+ }+ />+ </div>++ <div className="flex items-center justify-between">+ <Label htmlFor="sync-frames" className="text-sm">+ screen frames+ </Label>+ <Switch+ id="sync-frames"+ checked={config.syncFrames}+ onCheckedChange={(checked) =>+ handleUpdateConfig({ syncFrames: checked })+ }+ />+ </div>+ </div>++ <div className="flex items-center justify-between">+ <Label htmlFor="sync-interval" className="text-sm">+ sync frequency+ </Label>+ <Select+ value={String(config.syncIntervalMinutes)}+ onValueChange={(value) =>+ handleUpdateConfig({ syncIntervalMinutes: parseInt(value) })+ }+ >+ <SelectTrigger className="w-32">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="1">1 minute</SelectItem>+ <SelectItem value="5">5 minutes</SelectItem>+ <SelectItem value="15">15 minutes</SelectItem>+ <SelectItem value="30">30 minutes</SelectItem>+ <SelectItem value="60">1 hour</SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>+ </>+ )}++ {/* Devices */}+ {devices.length > 0 && (+ <>+ <Separator />+ <div className="space-y-4">+ <h4 className="text-sm font-medium">connected devices</h4>+ <div className="space-y-2">+ {devices.map((device) => (+ <Card+ key={device.deviceId}+ className="p-3 flex items-center justify-between"+ >+ <div className="flex items-center gap-3">+ <Laptop className="h-4 w-4 text-muted-foreground" />+ <div>+ <p className="text-sm font-medium">+ {device.deviceName || device.deviceId}+ {device.isCurrent && (+ <Badge variant="outline" className="ml-2 text-xs">+ this device+ </Badge>+ )}+ </p>+ <p className="text-xs text-muted-foreground">+ {device.deviceOs}+ {device.lastSyncAt &&+ ` β’ last synced ${formatRelativeTime(device.lastSyncAt)}`}+ </p>+ </div>+ </div>+ {!device.isCurrent && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleRemoveDevice(device.deviceId)}+ >+ <Trash2 className="h-4 w-4 text-muted-foreground" />+ </Button>+ )}+ </Card>+ ))}+ </div>+ </div>+ </>+ )}++ {/* Danger Zone */}+ <Separator />+ <div className="space-y-4">+ <h4 className="text-sm font-medium text-destructive">danger zone</h4>+ <div className="flex gap-2">+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="outline" size="sm">+ <Lock className="h-4 w-4 mr-2" />+ lock sync+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>lock sync?</AlertDialogTitle>+ <AlertDialogDescription>+ this will clear your encryption keys from memory. you'll+ need to enter your password again to access synced data.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={async () => {+ await invoke("lock_sync");+ await loadSyncData();+ }}+ >+ lock+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="destructive" size="sm">+ <Trash2 className="h-4 w-4 mr-2" />+ delete cloud data+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>delete all cloud data?</AlertDialogTitle>+ <AlertDialogDescription>+ this will permanently delete all your synced data from the+ cloud. this action cannot be undone. your local data will+ not be affected.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={handleDeleteCloudData}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ delete forever+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ </div>+ </>+ )}++ {/* Password Dialog */}+ <AlertDialog open={showPasswordDialog} onOpenChange={setShowPasswordDialog}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>set up cloud sync</AlertDialogTitle>+ <AlertDialogDescription>+ enter a password to encrypt your data. this password is used to+ derive encryption keys - we never see your password or your data.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <div className="py-4">+ <Input+ type="password"+ placeholder="enter encryption password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleInitSync();+ }}+ />+ <p className="text-xs text-muted-foreground mt-2">+ β οΈ if you forget this password, your cloud data cannot be recovered+ </p>+ </div>+ <AlertDialogFooter>+ <AlertDialogCancel onClick={() => setPassword("")}>+ cancel+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleInitSync} disabled={isInitializing}>+ {isInitializing ? (+ <Loader2 className="h-4 w-4 animate-spin mr-2" />+ ) : (+ <Unlock className="h-4 w-4 mr-2" />+ )}+ {isInitializing ? "initializing..." : "enable sync"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 341bab95e..fa3d4230f 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -8,6 +8,27 @@ version = "0.11.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"+[[package]]+name = "accessibility"+version = "0.3.0"+source = "git+https://github.com/eiz/accessibility.git?branch=master#173e898d4a52ee0afe0224ecb458d324057856e7"+dependencies = [+ "accessibility-sys",+ "cocoa 0.26.0",+ "core-foundation 0.10.1",+ "core-graphics-types 0.2.0",+ "objc",+ "thiserror 1.0.69",+]++[[package]]+name = "accessibility-sys"+version = "0.2.0"+source = "git+https://github.com/eiz/accessibility.git?branch=master#173e898d4a52ee0afe0224ecb458d324057856e7"+dependencies = [+ "core-foundation-sys 0.8.7",+]+[[package]]name = "addr2line"version = "0.22.0"@@ -29,6 +50,41 @@ version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"+[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common",+ "generic-array",+]++[[package]]+name = "aes"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"+dependencies = [+ "cfg-if 1.0.0",+ "cipher",+ "cpufeatures",+]++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if 1.0.0",+ "getrandom 0.3.4",+ "once_cell",+ "serde",+ "version_check",+ "zerocopy",+]+[[package]]name = "aho-corasick"version = "1.1.3"@@ -125,9 +181,9 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.86"+version = "1.0.100"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da"+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"[[package]]name = "arbitrary"@@ -146,7 +202,19 @@ checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",+]++[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures",+ "password-hash 0.5.0",][[package]]@@ -343,7 +411,7 @@ checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -409,7 +477,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -420,13 +488,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"[[package]]name = "async-trait"-version = "0.1.81"+version = "0.1.89"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -562,6 +630,12 @@ dependencies = ["rustc-demangle",]+[[package]]+name = "base64"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"+[[package]]name = "base64"version = "0.21.7"@@ -574,6 +648,36 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"++[[package]]+name = "bincode"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"+dependencies = [+ "serde",+]++[[package]]+name = "bit-set"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"+[[package]]name = "bit_field"version = "0.10.2"@@ -601,6 +705,15 @@ version = "2.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2"+[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest",+]+[[package]]name = "block"version = "0.1.6"@@ -675,7 +788,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab"dependencies = ["memchr",- "regex-automata 0.4.7",+ "regex-automata","serde",]@@ -687,15 +800,29 @@ checksum = "c360505aed52b7ec96a3636c3f039d99103c37d1d9b4f7a8c743d3ea9ffcd03b"[[package]]name = "bumpalo"-version = "3.16.0"+version = "3.19.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"[[package]]name = "bytemuck"version = "1.16.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+][[package]]name = "byteorder"@@ -718,6 +845,53 @@ dependencies = ["serde",]+[[package]]+name = "bzip2"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"+dependencies = [+ "bzip2-sys",+ "libc",+]++[[package]]+name = "bzip2-sys"+version = "0.1.13+1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"+dependencies = [+ "cc",+ "pkg-config",+]++[[package]]+name = "cacache"+version = "13.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c5063741c7b2e260bbede781cf4679632dd90e2718e99f7715e46824b65670b"+dependencies = [+ "digest",+ "either",+ "futures",+ "hex",+ "libc",+ "memmap2 0.5.10",+ "miette",+ "reflink-copy",+ "serde",+ "serde_derive",+ "serde_json",+ "sha1",+ "sha2",+ "ssri",+ "tempfile",+ "thiserror 1.0.69",+ "tokio",+ "tokio-stream",+ "walkdir",+]+[[package]]name = "cairo-rs"version = "0.18.5"@@ -752,6 +926,59 @@ dependencies = ["serde",]+[[package]]+name = "candle-core"+version = "0.8.3"+source = "git+https://github.com/huggingface/candle.git?rev=c930ab7e1a234f02a0f49350bf38f03f45e53757#c930ab7e1a234f02a0f49350bf38f03f45e53757"+dependencies = [+ "byteorder",+ "gemm 0.17.1",+ "half",+ "memmap2 0.9.5",+ "num-traits",+ "num_cpus",+ "rand 0.9.2",+ "rand_distr",+ "rayon",+ "safetensors",+ "thiserror 1.0.69",+ "ug",+ "yoke",+ "zip 1.1.4",+]++[[package]]+name = "candle-nn"+version = "0.8.3"+source = "git+https://github.com/huggingface/candle.git?rev=c930ab7e1a234f02a0f49350bf38f03f45e53757#c930ab7e1a234f02a0f49350bf38f03f45e53757"+dependencies = [+ "candle-core",+ "half",+ "num-traits",+ "rayon",+ "safetensors",+ "serde",+ "thiserror 1.0.69",+]++[[package]]+name = "candle-transformers"+version = "0.8.3"+source = "git+https://github.com/huggingface/candle.git?rev=c930ab7e1a234f02a0f49350bf38f03f45e53757#c930ab7e1a234f02a0f49350bf38f03f45e53757"+dependencies = [+ "byteorder",+ "candle-core",+ "candle-nn",+ "fancy-regex",+ "num-traits",+ "rand 0.9.2",+ "rayon",+ "serde",+ "serde_json",+ "serde_plain",+ "tracing",+]+[[package]]name = "cargo-platform"version = "0.1.8"@@ -785,6 +1012,15 @@ dependencies = ["toml 0.9.11+spec-1.1.0",]+[[package]]+name = "castaway"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"+dependencies = [+ "rustversion",+]+[[package]]name = "cc"version = "1.2.53"@@ -848,6 +1084,30 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "chacha20"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"+dependencies = [+ "cfg-if 1.0.0",+ "cipher",+ "cpufeatures",+]++[[package]]+name = "chacha20poly1305"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"+dependencies = [+ "aead",+ "chacha20",+ "cipher",+ "poly1305",+ "zeroize",+]+[[package]]name = "chrono"version = "0.4.39"@@ -863,6 +1123,17 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common",+ "inout",+ "zeroize",+]+[[package]]name = "clap"version = "4.5.23"@@ -870,6 +1141,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84"dependencies = ["clap_builder",+ "clap_derive",][[package]]@@ -884,6 +1156,18 @@ dependencies = ["strsim",]+[[package]]+name = "clap_derive"+version = "4.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "clap_lex"version = "0.7.4"@@ -914,7 +1198,7 @@ dependencies = ["bitflags 2.8.0","block","cocoa-foundation 0.2.0",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","core-graphics 0.24.0","foreign-types 0.5.0","libc",@@ -943,7 +1227,7 @@ checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d"dependencies = ["bitflags 2.8.0","block",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","core-graphics-types 0.2.0","libc","objc",@@ -971,6 +1255,21 @@ dependencies = ["memchr",]+[[package]]+name = "compact_str"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fdb1325a1cece981e8a296ab8f0f9b63ae357bd0784a9faaf548cc7b480707a"+dependencies = [+ "castaway",+ "cfg-if 1.0.0",+ "itoa",+ "rustversion",+ "ryu",+ "serde",+ "static_assertions",+]+[[package]]name = "concurrent-queue"version = "2.5.0"@@ -986,6 +1285,19 @@ version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fe1d7dcda7d1da79e444bdfba1465f2f849a58b07774e1df473ee77030cb47a7"+[[package]]+name = "console"+version = "0.15.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"+dependencies = [+ "encode_unicode",+ "libc",+ "once_cell",+ "unicode-width 0.2.2",+ "windows-sys 0.59.0",+]+[[package]]name = "const-random"version = "0.1.18"@@ -1006,6 +1318,12 @@ dependencies = ["tiny-keccak",]+[[package]]+name = "constant_time_eq"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"+[[package]]name = "convert_case"version = "0.4.0"@@ -1031,7 +1349,7 @@ checksum = "2eac901828f88a5241ee0600950ab981148a18f2f756900ffba1b125ca6a3ef9"dependencies = ["cookie","document-features",- "idna 1.0.3",+ "idna","log","publicsuffix","serde",@@ -1063,9 +1381,9 @@ dependencies = [[[package]]name = "core-foundation"-version = "0.10.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"dependencies = ["core-foundation-sys 0.8.7","libc",@@ -1115,7 +1433,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"dependencies = ["bitflags 2.8.0",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","core-graphics-types 0.2.0","foreign-types 0.5.0","libc",@@ -1152,7 +1470,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = ["bitflags 2.8.0",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","libc",]@@ -1232,6 +1550,17 @@ dependencies = ["cfg-if 1.0.0",]+[[package]]+name = "cron"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eee8b2b4516038bc0f1d3c9934bcb4a13dd316e04abbc63c96757a6d75978532"+dependencies = [+ "chrono",+ "nom",+ "once_cell",+]+[[package]]name = "crossbeam-channel"version = "0.5.13"@@ -1279,6 +1608,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"dependencies = ["generic-array",+ "rand_core 0.6.4","typenum",]@@ -1306,7 +1636,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"dependencies = ["quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1316,7 +1646,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "edb49164822f3ee45b17acd4a208cfc1251410cf0cad9a833234c9890774dd9f"dependencies = ["quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1354,7 +1684,7 @@ dependencies = ["proc-macro2","quote","strsim",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1365,7 +1695,16 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"dependencies = ["darling_core","quote",- "syn 2.0.90",+ "syn 2.0.114",+]++[[package]]+name = "dary_heap"+version = "0.3.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06d2e3287df1c007e74221c49ca10a95d557349e54b3a75dc2fb14712c751f04"+dependencies = [+ "serde",][[package]]@@ -1413,7 +1752,38 @@ checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",+]++[[package]]+name = "derive_builder"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"+dependencies = [+ "derive_builder_macro",+]++[[package]]+name = "derive_builder_core"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "derive_builder_macro"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"+dependencies = [+ "derive_builder_core",+ "syn 2.0.114",][[package]]@@ -1426,7 +1796,7 @@ dependencies = ["proc-macro2","quote","rustc_version",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1437,6 +1807,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer","crypto-common",+ "subtle",][[package]]@@ -1508,7 +1879,7 @@ dependencies = ["libc","option-ext","redox_users 0.5.2",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -1546,7 +1917,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1578,7 +1949,7 @@ checksum = "f2b99bf03862d7f545ebc28ddd33a665b50865f4dfd84031a393823879bd4c54"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1641,6 +2012,32 @@ version = "1.0.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125"+[[package]]+name = "dyn-stack"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56e53799688f5632f364f8fb387488dd05db9fe45db7011be066fc20e7027f8b"+dependencies = [+ "bytemuck",+ "reborrow",+]++[[package]]+name = "dyn-stack"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8"+dependencies = [+ "bytemuck",+ "dyn-stack-macros",+]++[[package]]+name = "dyn-stack-macros"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9"+[[package]]name = "either"version = "1.13.0"@@ -1667,6 +2064,12 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "encode_unicode"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"+[[package]]name = "encoding_rs"version = "0.8.34"@@ -1682,6 +2085,18 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a3d8a32ae18130a3c84dd492d4215c3d913c3b07c6b63c2eb3eb7ff1101ab7bf"+[[package]]+name = "enum-as-inner"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "enumflags2"version = "0.7.10"@@ -1700,7 +2115,7 @@ checksum = "de0d48a183585823424a4ce1aa132d174a6a81bd540895822eb4c8373a8e49e8"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -1726,7 +2141,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",+]++[[package]]+name = "esaxx-rs"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"+dependencies = [+ "cc",][[package]]@@ -1774,12 +2198,23 @@ dependencies = ["bit_field","half","lebe",- "miniz_oxide 0.8.0",+ "miniz_oxide 0.8.9","rayon-core","smallvec","zune-inflate",]+[[package]]+name = "fancy-regex"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "531e46835a22af56d1e3b66f04844bed63158bc094a628bec1d321d9b4c44bf2"+dependencies = [+ "bit-set",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "fastrand"version = "2.1.0"@@ -1795,6 +2230,18 @@ dependencies = ["simd-adler32",]+[[package]]+name = "ffmpeg-sidecar"+version = "2.3.0"+source = "git+https://github.com/nathanbabcock/ffmpeg-sidecar?branch=main#a4d189d46aba70c22cf18ad49276caaf6c7a0e58"+dependencies = [+ "anyhow",+ "tar",+ "ureq 3.1.4",+ "xz2",+ "zip 4.6.1",+]+[[package]]name = "field-offset"version = "0.3.6"@@ -1846,12 +2293,13 @@ dependencies = [[[package]]name = "flate2"-version = "1.0.30"+version = "1.1.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae"+checksum = "b375d6465b98090a5f25b1c7703f3859783755aa9a80433b36e0379a3ec2f369"dependencies = ["crc32fast",- "miniz_oxide 0.7.4",+ "miniz_oxide 0.8.9",+ "zlib-rs",][[package]]@@ -1896,7 +2344,7 @@ checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"dependencies = ["fontconfig-parser","log",- "memmap2",+ "memmap2 0.9.5","slotmap","tinyvec","ttf-parser",@@ -1929,7 +2377,7 @@ checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -2067,7 +2515,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -2168,44 +2616,281 @@ dependencies = [][[package]]-name = "gdkwayland-sys"-version = "0.18.0"+name = "gdkwayland-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a90fbf5c033c65d93792192a49a8efb5bb1e640c419682a58bb96f5ae77f3d4a"+dependencies = [+ "gdk-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pkg-config",+ "system-deps",+]++[[package]]+name = "gdkx11"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db2ea8a4909d530f79921290389cbd7c34cb9d623bfe970eaae65ca5f9cd9cce"+dependencies = [+ "gdk",+ "gdkx11-sys",+ "gio",+ "glib",+ "libc",+ "x11",+]++[[package]]+name = "gdkx11-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fee8f00f4ee46cad2939b8990f5c70c94ff882c3028f3cc5abf950fa4ab53043"+dependencies = [+ "gdk-sys",+ "glib-sys",+ "libc",+ "system-deps",+ "x11",+]++[[package]]+name = "gemm"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ab24cc62135b40090e31a76a9b2766a501979f3070fa27f689c27ec04377d32"+dependencies = [+ "dyn-stack 0.10.0",+ "gemm-c32 0.17.1",+ "gemm-c64 0.17.1",+ "gemm-common 0.17.1",+ "gemm-f16 0.17.1",+ "gemm-f32 0.17.1",+ "gemm-f64 0.17.1",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 10.7.0",+ "seq-macro",+]++[[package]]+name = "gemm"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab96b703d31950f1aeddded248bc95543c9efc7ac9c4a21fda8703a83ee35451"+dependencies = [+ "dyn-stack 0.13.2",+ "gemm-c32 0.18.2",+ "gemm-c64 0.18.2",+ "gemm-common 0.18.2",+ "gemm-f16 0.18.2",+ "gemm-f32 0.18.2",+ "gemm-f64 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 11.6.0",+ "seq-macro",+]++[[package]]+name = "gemm-c32"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9c030d0b983d1e34a546b86e08f600c11696fde16199f971cd46c12e67512c0"+dependencies = [+ "dyn-stack 0.10.0",+ "gemm-common 0.17.1",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 10.7.0",+ "seq-macro",+]++[[package]]+name = "gemm-c32"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6db9fd9f40421d00eea9dd0770045a5603b8d684654816637732463f4073847"+dependencies = [+ "dyn-stack 0.13.2",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 11.6.0",+ "seq-macro",+]++[[package]]+name = "gemm-c64"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fbb5f2e79fefb9693d18e1066a557b4546cd334b226beadc68b11a8f9431852a"+dependencies = [+ "dyn-stack 0.10.0",+ "gemm-common 0.17.1",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 10.7.0",+ "seq-macro",+]++[[package]]+name = "gemm-c64"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfcad8a3d35a43758330b635d02edad980c1e143dc2f21e6fd25f9e4eada8edf"+dependencies = [+ "dyn-stack 0.13.2",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 11.6.0",+ "seq-macro",+]++[[package]]+name = "gemm-common"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2e7ea062c987abcd8db95db917b4ffb4ecdfd0668471d8dc54734fdff2354e8"+dependencies = [+ "bytemuck",+ "dyn-stack 0.10.0",+ "half",+ "num-complex",+ "num-traits",+ "once_cell",+ "paste",+ "pulp 0.18.22",+ "raw-cpuid 10.7.0",+ "rayon",+ "seq-macro",+ "sysctl 0.5.5",+]++[[package]]+name = "gemm-common"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a352d4a69cbe938b9e2a9cb7a3a63b7e72f9349174a2752a558a8a563510d0f3"+dependencies = [+ "bytemuck",+ "dyn-stack 0.13.2",+ "half",+ "libm",+ "num-complex",+ "num-traits",+ "once_cell",+ "paste",+ "pulp 0.21.5",+ "raw-cpuid 11.6.0",+ "rayon",+ "seq-macro",+ "sysctl 0.6.0",+]++[[package]]+name = "gemm-f16"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ca4c06b9b11952071d317604acb332e924e817bd891bec8dfb494168c7cedd4"+dependencies = [+ "dyn-stack 0.10.0",+ "gemm-common 0.17.1",+ "gemm-f32 0.17.1",+ "half",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 10.7.0",+ "rayon",+ "seq-macro",+]++[[package]]+name = "gemm-f16"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cff95ae3259432f3c3410eaa919033cd03791d81cebd18018393dc147952e109"+dependencies = [+ "dyn-stack 0.13.2",+ "gemm-common 0.18.2",+ "gemm-f32 0.18.2",+ "half",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 11.6.0",+ "rayon",+ "seq-macro",+]++[[package]]+name = "gemm-f32"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9a69f51aaefbd9cf12d18faf273d3e982d9d711f60775645ed5c8047b4ae113"+dependencies = [+ "dyn-stack 0.10.0",+ "gemm-common 0.17.1",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 10.7.0",+ "seq-macro",+]++[[package]]+name = "gemm-f32"+version = "0.18.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a90fbf5c033c65d93792192a49a8efb5bb1e640c419682a58bb96f5ae77f3d4a"+checksum = "bc8d3d4385393304f407392f754cd2dc4b315d05063f62cf09f47b58de276864"dependencies = [- "gdk-sys",- "glib-sys",- "gobject-sys",- "libc",- "pkg-config",- "system-deps",+ "dyn-stack 0.13.2",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 11.6.0",+ "seq-macro",][[package]]-name = "gdkx11"-version = "0.18.0"+name = "gemm-f64"+version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "db2ea8a4909d530f79921290389cbd7c34cb9d623bfe970eaae65ca5f9cd9cce"+checksum = "aa397a48544fadf0b81ec8741e5c0fba0043008113f71f2034def1935645d2b0"dependencies = [- "gdk",- "gdkx11-sys",- "gio",- "glib",- "libc",- "x11",+ "dyn-stack 0.10.0",+ "gemm-common 0.17.1",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 10.7.0",+ "seq-macro",][[package]]-name = "gdkx11-sys"-version = "0.18.0"+name = "gemm-f64"+version = "0.18.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fee8f00f4ee46cad2939b8990f5c70c94ff882c3028f3cc5abf950fa4ab53043"+checksum = "35b2a4f76ce4b8b16eadc11ccf2e083252d8237c1b589558a49b0183545015bd"dependencies = [- "gdk-sys",- "glib-sys",- "libc",- "system-deps",- "x11",+ "dyn-stack 0.13.2",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid 11.6.0",+ "seq-macro",][[package]]@@ -2366,7 +3051,7 @@ dependencies = ["proc-macro-error","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -2485,7 +3170,7 @@ dependencies = ["proc-macro-error","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -2499,7 +3184,7 @@ dependencies = ["fnv","futures-core","futures-sink",- "http 1.1.0",+ "http 1.4.0","indexmap 2.13.0","slab","tokio",@@ -2509,12 +3194,17 @@ dependencies = [[[package]]name = "half"-version = "2.4.1"+version = "2.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"dependencies = [+ "bytemuck","cfg-if 1.0.0","crunchy",+ "num-traits",+ "rand 0.9.2",+ "rand_distr",+ "zerocopy",][[package]]@@ -2565,6 +3255,45 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hf-hub"+version = "0.3.2"+source = "git+https://github.com/neo773/hf-hub#437dcf4049233f4a0e0cfc4e1c1dbf5ed2c57760"+dependencies = [+ "dirs 5.0.1",+ "futures",+ "http 1.4.0",+ "indicatif",+ "log",+ "native-tls",+ "num_cpus",+ "rand 0.8.5",+ "reqwest",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+ "tokio",+ "ureq 2.12.1",+]++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest",+]++[[package]]+name = "home"+version = "0.5.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"+dependencies = [+ "windows-sys 0.61.2",+]+[[package]]name = "hostname"version = "0.4.0"@@ -2601,12 +3330,11 @@ dependencies = [[[package]]name = "http"-version = "1.1.0"+version = "1.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258"+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"dependencies = ["bytes",- "fnv","itoa",]@@ -2628,7 +3356,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"dependencies = ["bytes",- "http 1.1.0",+ "http 1.4.0",][[package]]@@ -2639,11 +3367,56 @@ checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f"dependencies = ["bytes","futures-util",- "http 1.1.0",+ "http 1.4.0","http-body 1.0.1","pin-project-lite",]+[[package]]+name = "http-cache"+version = "0.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e883defacf53960c7717d9e928dc8667be9501d9f54e6a8b7703d7a30320e9c"+dependencies = [+ "async-trait",+ "bincode",+ "cacache",+ "http 1.4.0",+ "http-cache-semantics",+ "httpdate",+ "serde",+ "url",+]++[[package]]+name = "http-cache-reqwest"+version = "0.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e076afd9d376f09073b515ce95071b29393687d98ed521948edb899195595ddf"+dependencies = [+ "anyhow",+ "async-trait",+ "http 1.4.0",+ "http-cache",+ "http-cache-semantics",+ "reqwest",+ "reqwest-middleware",+ "serde",+ "url",+]++[[package]]+name = "http-cache-semantics"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92baf25cf0b8c9246baecf3a444546360a97b569168fdf92563ee6a47829920c"+dependencies = [+ "http 1.4.0",+ "http-serde",+ "serde",+ "time",+]+[[package]]name = "http-range"version = "0.1.5"@@ -2656,6 +3429,16 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f"+[[package]]+name = "http-serde"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f056c8559e3757392c8d091e796416e4649d8e49e88b8d76df6c002f05027fd"+dependencies = [+ "http 1.4.0",+ "serde",+]+[[package]]name = "httparse"version = "1.9.4"@@ -2701,7 +3484,7 @@ dependencies = ["futures-channel","futures-util","h2",- "http 1.1.0",+ "http 1.4.0","http-body 1.0.1","httparse","itoa",@@ -2718,7 +3501,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155"dependencies = ["futures-util",- "http 1.1.0",+ "http 1.4.0","hyper 1.4.1","hyper-util","rustls",@@ -2726,7 +3509,7 @@ dependencies = ["tokio","tokio-rustls","tower-service",- "webpki-roots",+ "webpki-roots 0.26.3",][[package]]@@ -2754,7 +3537,7 @@ dependencies = ["bytes","futures-channel","futures-util",- "http 1.1.0",+ "http 1.4.0","http-body 1.0.1","hyper 1.4.1","pin-project-lite",@@ -2912,7 +3695,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -2921,16 +3704,6 @@ version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"-[[package]]-name = "idna"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6"-dependencies = [- "unicode-bidi",- "unicode-normalization",-]-[[package]]name = "idna"version = "1.0.3"@@ -3032,6 +3805,19 @@ dependencies = ["serde_core",]+[[package]]+name = "indicatif"+version = "0.17.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235"+dependencies = [+ "console",+ "number_prefix",+ "portable-atomic",+ "unicode-width 0.2.2",+ "web-time",+]+[[package]]name = "infer"version = "0.19.0"@@ -3070,6 +3856,15 @@ dependencies = ["libc",]+[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "generic-array",+]+[[package]]name = "interpolate_name"version = "0.2.4"@@ -3078,7 +3873,7 @@ checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -3121,6 +3916,15 @@ dependencies = ["either",]+[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]+[[package]]name = "itoa"version = "1.0.11"@@ -3418,9 +4222,9 @@ dependencies = [[[package]]name = "log"-version = "0.4.22"+version = "0.4.29"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"dependencies = ["value-bag",]@@ -3434,6 +4238,17 @@ dependencies = ["imgref",]+[[package]]+name = "lzma-sys"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+]+[[package]]name = "mac"version = "0.1.1"@@ -3462,6 +4277,22 @@ dependencies = ["libc",]+[[package]]+name = "macro_rules_attribute"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520"+dependencies = [+ "macro_rules_attribute-proc_macro",+ "paste",+]++[[package]]+name = "macro_rules_attribute-proc_macro"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"+[[package]]name = "malloc_buf"version = "0.0.6"@@ -3493,16 +4324,16 @@ checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]name = "matchers"-version = "0.1.0"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"dependencies = [- "regex-automata 0.1.10",+ "regex-automata",][[package]]@@ -3527,12 +4358,27 @@ dependencies = ["rayon",]+[[package]]+name = "md5"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"+[[package]]name = "memchr"version = "2.7.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"+[[package]]+name = "memmap2"+version = "0.5.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327"+dependencies = [+ "libc",+]+[[package]]name = "memmap2"version = "0.9.5"@@ -3540,6 +4386,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd3f7eed9d3848f8b98834af67102b720745c4ec028fcd0aa0239277e7de374f"dependencies = ["libc",+ "stable_deref_trait",][[package]]@@ -3566,6 +4413,29 @@ dependencies = ["objc",]+[[package]]+name = "miette"+version = "5.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59bb584eaeeab6bd0226ccf3509a69d7936d148cf3d036ad350abe35e8c6856e"+dependencies = [+ "miette-derive",+ "once_cell",+ "thiserror 1.0.69",+ "unicode-width 0.1.14",+]++[[package]]+name = "miette-derive"+version = "5.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49e7bc1560b95a3c4a25d03de42fe76ca718ab92d1a22a55b9b4cf67b3ae635c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "mime"version = "0.3.17"@@ -3611,7 +4481,7 @@ dependencies = ["libc","log","mach2",- "memmap2",+ "memmap2 0.9.5","memoffset","minidump-common","nix 0.28.0",@@ -3675,11 +4545,12 @@ dependencies = [[[package]]name = "miniz_oxide"-version = "0.8.0"+version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"dependencies = ["adler2",+ "simd-adler32",][[package]]@@ -3705,6 +4576,28 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "monostate"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"+dependencies = [+ "monostate-impl",+ "serde",+ "serde_core",+]++[[package]]+name = "monostate-impl"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "muda"version = "0.17.1"@@ -3908,12 +4801,25 @@ dependencies = [[[package]]name = "nu-ansi-term"-version = "0.46.0"+version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "overload",- "winapi",+ "windows-sys 0.61.2",+]++[[package]]+name = "num"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"+dependencies = [+ "num-bigint",+ "num-complex",+ "num-integer",+ "num-iter",+ "num-rational",+ "num-traits",][[package]]@@ -3926,6 +4832,16 @@ dependencies = ["num-traits",]+[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "bytemuck",+ "num-traits",+]+[[package]]name = "num-conv"version = "0.1.0"@@ -3940,7 +4856,7 @@ checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -3952,6 +4868,17 @@ dependencies = ["num-traits",]+[[package]]+name = "num-iter"+version = "0.1.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"+dependencies = [+ "autocfg",+ "num-integer",+ "num-traits",+]+[[package]]name = "num-rational"version = "0.4.2"@@ -3970,6 +4897,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = ["autocfg",+ "libm",][[package]]@@ -4000,9 +4928,15 @@ dependencies = ["proc-macro-crate 3.2.0","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",]+[[package]]+name = "number_prefix"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"+[[package]]name = "objc"version = "0.2.7"@@ -4374,6 +5308,34 @@ version = "1.20.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"+[[package]]+name = "onig"+version = "6.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "336b9c63443aceef14bea841b899035ae3abe89b7c486aaf4c5bd8aafedac3f0"+dependencies = [+ "bitflags 2.8.0",+ "libc",+ "once_cell",+ "onig_sys",+]++[[package]]+name = "onig_sys"+version = "69.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f86c6eef3d6df15f23bcfb6af487cbd2fed4e5581d58d5bf1f5f8b7f6727dc"+dependencies = [+ "cc",+ "pkg-config",+]++[[package]]+name = "opaque-debug"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"+[[package]]name = "open"version = "5.3.0"@@ -4408,7 +5370,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -4490,12 +5452,6 @@ dependencies = ["thiserror 2.0.5",]-[[package]]-name = "overload"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"-[[package]]name = "pango"version = "0.18.3"@@ -4550,6 +5506,28 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "password-hash"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]++[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "paste"version = "1.0.15"@@ -4562,6 +5540,18 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"+[[package]]+name = "pbkdf2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917"+dependencies = [+ "digest",+ "hmac",+ "password-hash 0.4.2",+ "sha2",+]+[[package]]name = "percent-encoding"version = "2.3.1"@@ -4672,7 +5662,7 @@ dependencies = ["phf_shared 0.11.2","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -4725,7 +5715,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -4804,6 +5794,23 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "poly1305"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"+dependencies = [+ "cpufeatures",+ "opaque-debug",+ "universal-hash",+]++[[package]]+name = "portable-atomic"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f89776e4d69bb58bc6993e99ffa1d11f228b839984854c7daeb5d37f87cbe950"+[[package]]name = "powerfmt"version = "0.2.0"@@ -4882,9 +5889,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"[[package]]name = "proc-macro2"-version = "1.0.92"+version = "1.0.106"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"dependencies = ["unicode-ident",]@@ -4915,7 +5922,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a65f2e60fbf1063868558d69c6beacf412dc755f9fc020f514b7955fc914fe30"dependencies = ["quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -4930,10 +5937,36 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf"dependencies = [- "idna 1.0.3",+ "idna","psl-types",]+[[package]]+name = "pulp"+version = "0.18.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0a01a0dc67cf4558d279f0c25b0962bd08fc6dec0137699eae304103e882fe6"+dependencies = [+ "bytemuck",+ "libm",+ "num-complex",+ "reborrow",+]++[[package]]+name = "pulp"+version = "0.21.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96b86df24f0a7ddd5e4b95c94fc9ed8a98f1ca94d3b01bdce2824097e7835907"+dependencies = [+ "bytemuck",+ "cfg-if 1.0.0",+ "libm",+ "num-complex",+ "reborrow",+ "version_check",+]+[[package]]name = "qoi"version = "0.4.1"@@ -5024,9 +6057,9 @@ dependencies = [[[package]]name = "quote"-version = "1.0.36"+version = "1.0.44"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"dependencies = ["proc-macro2",]@@ -5129,6 +6162,16 @@ dependencies = ["getrandom 0.3.4",]+[[package]]+name = "rand_distr"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"+dependencies = [+ "num-traits",+ "rand 0.9.2",+]+[[package]]name = "rand_hc"version = "0.2.0"@@ -5170,7 +6213,7 @@ dependencies = ["built","cfg-if 1.0.0","interpolate_name",- "itertools",+ "itertools 0.12.1","libc","libfuzzer-sys","log",@@ -5206,6 +6249,24 @@ dependencies = ["rgb",]+[[package]]+name = "raw-cpuid"+version = "10.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c297679cb867470fa8c9f67dbba74a78d78e3e98d7cf2b08d6d71540f797332"+dependencies = [+ "bitflags 1.3.2",+]++[[package]]+name = "raw-cpuid"+version = "11.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"+dependencies = [+ "bitflags 2.8.0",+]+[[package]]name = "raw-window-handle"version = "0.6.2"@@ -5222,6 +6283,17 @@ dependencies = ["rayon-core",]+[[package]]+name = "rayon-cond"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"+dependencies = [+ "either",+ "itertools 0.14.0",+ "rayon",+]+[[package]]name = "rayon-core"version = "1.12.1"@@ -5232,6 +6304,12 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "reborrow"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"+[[package]]name = "redox_syscall"version = "0.4.1"@@ -5273,24 +6351,27 @@ dependencies = [][[package]]-name = "regex"-version = "1.10.6"+name = "reflink-copy"+version = "0.1.28"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619"+checksum = "23bbed272e39c47a095a5242218a67412a220006842558b03fe2935e8f3d7b92"dependencies = [- "aho-corasick",- "memchr",- "regex-automata 0.4.7",- "regex-syntax 0.8.4",+ "cfg-if 1.0.0",+ "libc",+ "rustix 1.1.3",+ "windows 0.61.3",][[package]]-name = "regex-automata"-version = "0.1.10"+name = "regex"+version = "1.10.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"+checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619"dependencies = [- "regex-syntax 0.6.29",+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",][[package]]@@ -5301,15 +6382,9 @@ checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"dependencies = ["aho-corasick","memchr",- "regex-syntax 0.8.4",+ "regex-syntax",]-[[package]]-name = "regex-syntax"-version = "0.6.29"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"-[[package]]name = "regex-syntax"version = "0.8.4"@@ -5331,7 +6406,7 @@ dependencies = ["futures-core","futures-util","h2",- "http 1.1.0",+ "http 1.4.0","http-body 1.0.1","http-body-util","hyper 1.4.1",@@ -5367,10 +6442,25 @@ dependencies = ["wasm-bindgen-futures","wasm-streams","web-sys",- "webpki-roots",+ "webpki-roots 0.26.3","windows-registry 0.2.0",]+[[package]]+name = "reqwest-middleware"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57f17d28a6e6acfe1733fe24bcd30774d13bffa4b8a22535b4c8c98423088d4e"+dependencies = [+ "anyhow",+ "async-trait",+ "http 1.4.0",+ "reqwest",+ "serde",+ "thiserror 1.0.69",+ "tower-service",+]+[[package]]name = "resvg"version = "0.45.1"@@ -5496,15 +6586,16 @@ dependencies = ["errno","libc","linux-raw-sys 0.11.0",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]name = "rustls"-version = "0.23.11"+version = "0.23.36"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4828ea528154ae444e5a642dbb7d5623354030dc9822b83fd9bb79683c7399d0"+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"dependencies = [+ "log","once_cell","ring","rustls-pki-types",@@ -5525,15 +6616,18 @@ dependencies = [[[package]]name = "rustls-pki-types"-version = "1.7.0"+version = "1.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d"+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"+dependencies = [+ "zeroize",+][[package]]name = "rustls-webpki"-version = "0.102.5"+version = "0.103.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78"+checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"dependencies = ["ring","rustls-pki-types",@@ -5570,6 +6664,16 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"+[[package]]+name = "safetensors"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44560c11236a6130a46ce36c836a62936dc81ebf8c36a37947423571be0e55b6"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "same-file"version = "1.0.6"@@ -5612,7 +6716,7 @@ dependencies = ["proc-macro2","quote","serde_derive_internals",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -5638,7 +6742,7 @@ dependencies = ["block","chrono","cocoa 0.26.0",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","core-graphics-helmer-fork","dark-light","dirs 5.0.1",@@ -5648,12 +6752,14 @@ dependencies = ["futures","futures-channel","gtk",+ "hostname","http 0.2.12","image 0.25.5","ini","lazy_static","libc","log",+ "md5","nokhwa-bindings-macos","notify","objc",@@ -5661,6 +6767,7 @@ dependencies = ["raw-window-handle","reqwest","resvg",+ "screenpipe-core","serde","serde_derive","serde_json",@@ -5700,6 +6807,57 @@ dependencies = ["xdg 2.5.2",]+[[package]]+name = "screenpipe-core"+version = "0.3.5"+dependencies = [+ "accessibility",+ "accessibility-sys",+ "anyhow",+ "argon2",+ "async-trait",+ "base64 0.22.1",+ "candle-core",+ "candle-nn",+ "candle-transformers",+ "chacha20poly1305",+ "chrono",+ "clap",+ "core-foundation 0.10.1",+ "core-graphics 0.24.0",+ "cron",+ "dirs 5.0.1",+ "ffmpeg-sidecar",+ "hex",+ "hf-hub",+ "hmac",+ "http-cache-reqwest",+ "lazy_static",+ "log",+ "objc",+ "objc-foundation",+ "once_cell",+ "rand 0.8.5",+ "regex",+ "reqwest",+ "reqwest-middleware",+ "sentry",+ "serde",+ "serde_json",+ "sha2",+ "tempfile",+ "thiserror 1.0.69",+ "tokenizers",+ "tokio",+ "tracing",+ "tracing-subscriber",+ "uiautomation",+ "url",+ "which",+ "zeroize",+ "zip 0.6.6",+]+[[package]]name = "scroll"version = "0.12.0"@@ -5717,7 +6875,7 @@ checksum = "7f81c2fde025af7e69b1d1420531c8a8811ca898919db177141a85313b1cb932"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -5786,7 +6944,7 @@ dependencies = ["sentry-panic","sentry-tracing","tokio",- "ureq",+ "ureq 2.12.1",][[package]]@@ -5889,6 +7047,12 @@ dependencies = ["uuid",]+[[package]]+name = "seq-macro"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"+[[package]]name = "serde"version = "1.0.228"@@ -5927,7 +7091,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -5938,7 +7102,7 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -5962,6 +7126,15 @@ dependencies = ["serde",]+[[package]]+name = "serde_plain"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"+dependencies = [+ "serde",+]+[[package]]name = "serde_repr"version = "0.1.19"@@ -5970,7 +7143,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -6030,7 +7203,7 @@ dependencies = ["darling","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -6052,7 +7225,7 @@ checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -6065,6 +7238,17 @@ dependencies = ["stable_deref_trait",]+[[package]]+name = "sha-1"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c"+dependencies = [+ "cfg-if 1.0.0",+ "cpufeatures",+ "digest",+]+[[package]]name = "sha1"version = "0.10.6"@@ -6189,7 +7373,7 @@ checksum = "0eb01866308440fc64d6c44d9e86c5cc17adfe33c4d6eed55da9145044d0ffc1"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -6202,6 +7386,17 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "socks"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b"+dependencies = [+ "byteorder",+ "libc",+ "winapi",+]+[[package]]name = "softbuffer"version = "0.4.5"@@ -6273,7 +7468,7 @@ dependencies = ["Inflector","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -6306,6 +7501,35 @@ dependencies = ["lock_api",]+[[package]]+name = "spm_precompiled"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"+dependencies = [+ "base64 0.13.1",+ "nom",+ "serde",+ "unicode-segmentation",+]++[[package]]+name = "ssri"+version = "9.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7a2b3c2bc9693bcb40870c4e9b5bf0d79f9cb46273321bf855ec513e919082"+dependencies = [+ "base64 0.21.7",+ "digest",+ "hex",+ "miette",+ "serde",+ "sha-1",+ "sha2",+ "thiserror 1.0.69",+ "xxhash-rust",+]+[[package]]name = "stable_deref_trait"version = "1.2.0"@@ -6408,9 +7632,9 @@ dependencies = [[[package]]name = "syn"-version = "2.0.90"+version = "2.0.114"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31"+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"dependencies = ["proc-macro2","quote",@@ -6440,7 +7664,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -6452,6 +7676,34 @@ dependencies = ["libc",]+[[package]]+name = "sysctl"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec7dddc5f0fee506baf8b9fdb989e242f17e4b11c61dfbb0635b705217199eea"+dependencies = [+ "bitflags 2.8.0",+ "byteorder",+ "enum-as-inner",+ "libc",+ "thiserror 1.0.69",+ "walkdir",+]++[[package]]+name = "sysctl"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc"+dependencies = [+ "bitflags 2.8.0",+ "byteorder",+ "enum-as-inner",+ "libc",+ "thiserror 1.0.69",+ "walkdir",+]+[[package]]name = "sysinfo"version = "0.29.0"@@ -6509,7 +7761,7 @@ checksum = "f3a753bdc39c07b192151523a3f77cd0394aa75413802c883a0f6f6a0e5ee2e7"dependencies = ["bitflags 2.8.0","block2 0.6.2",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","core-graphics 0.24.0","crossbeam-channel","dispatch",@@ -6554,9 +7806,9 @@ dependencies = [[[package]]name = "tar"-version = "0.4.41"+version = "0.4.44"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb797dad5fb5b76fcf519e702f4a589483b5ef06567f160c392832c1f5e44909"+checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"dependencies = ["filetime","libc",@@ -6585,7 +7837,7 @@ dependencies = ["glob","gtk","heck 0.5.0",- "http 1.1.0",+ "http 1.4.0","http-range","image 0.25.5","jni",@@ -6664,7 +7916,7 @@ dependencies = ["serde","serde_json","sha2",- "syn 2.0.90",+ "syn 2.0.114","tauri-utils","thiserror 2.0.5","time",@@ -6682,7 +7934,7 @@ dependencies = ["heck 0.5.0","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","tauri-codegen","tauri-utils",]@@ -6695,7 +7947,7 @@ dependencies = ["bitflags 2.8.0","block","cocoa 0.26.0",- "core-foundation 0.10.0",+ "core-foundation 0.10.1","core-graphics 0.24.0","objc","objc-foundation",@@ -6832,7 +8084,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e62a9bde54d6a0218b63f5a248f02056ad4316ba6ad81dfb9e4f73715df5deb1"dependencies = ["data-url",- "http 1.1.0",+ "http 1.4.0","regex","reqwest","schemars",@@ -6995,7 +8247,7 @@ dependencies = ["dirs 6.0.0","flate2","futures-util",- "http 1.1.0",+ "http 1.4.0","infer","log","minisign-verify",@@ -7014,7 +8266,7 @@ dependencies = ["tokio","url","windows-sys 0.60.2",- "zip",+ "zip 4.6.1",][[package]]@@ -7026,7 +8278,7 @@ dependencies = ["cookie","dpi","gtk",- "http 1.1.0",+ "http 1.4.0","jni","objc2 0.6.3","objc2-ui-kit",@@ -7049,7 +8301,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c1fe9d48bd122ff002064e88cfcd7027090d789c4302714e68fcccba0f4b7807"dependencies = ["gtk",- "http 1.1.0",+ "http 1.4.0","jni","log","objc2 0.6.3",@@ -7094,7 +8346,7 @@ dependencies = ["heck 0.5.0","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -7110,7 +8362,7 @@ dependencies = ["dunce","glob","html5ever",- "http 1.1.0",+ "http 1.4.0","infer","json-patch","kuchikiki",@@ -7212,7 +8464,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -7223,7 +8475,7 @@ checksum = "995d0bbc9995d1f19d28b7215a9352b0fc3cd3a2d2ec95c2cadc485cdedbcdde"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -7338,12 +8590,46 @@ dependencies = ["tinyvec_macros",]-[[package]]-name = "tinyvec_macros"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"-+[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "tokenizers"+version = "0.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a620b996116a59e184c2fa2dfd8251ea34a36d0a514758c6f966386bd2e03476"+dependencies = [+ "ahash",+ "aho-corasick",+ "compact_str",+ "dary_heap",+ "derive_builder",+ "esaxx-rs",+ "getrandom 0.3.4",+ "indicatif",+ "itertools 0.14.0",+ "log",+ "macro_rules_attribute",+ "monostate",+ "onig",+ "paste",+ "rand 0.9.2",+ "rayon",+ "rayon-cond",+ "regex",+ "regex-syntax",+ "serde",+ "serde_json",+ "spm_precompiled",+ "thiserror 2.0.5",+ "unicode-normalization-alignments",+ "unicode-segmentation",+ "unicode_categories",+]+[[package]]name = "tokio"version = "1.38.1"@@ -7372,7 +8658,7 @@ checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -7396,6 +8682,17 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "tokio-util"version = "0.7.11"@@ -7568,9 +8865,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"[[package]]name = "tracing"-version = "0.1.40"+version = "0.1.44"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"dependencies = ["log","pin-project-lite",@@ -7592,20 +8889,20 @@ dependencies = [[[package]]name = "tracing-attributes"-version = "0.1.27"+version = "0.1.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]name = "tracing-core"-version = "0.1.32"+version = "0.1.36"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"dependencies = ["once_cell","valuable",@@ -7624,14 +8921,15 @@ dependencies = [[[package]]name = "tracing-subscriber"-version = "0.3.18"+version = "0.3.22"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b"+checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"dependencies = [+ "chrono","matchers","nu-ansi-term","once_cell",- "regex",+ "regex-automata","sharded-slab","smallvec","thread_local",@@ -7715,6 +9013,50 @@ dependencies = ["winapi",]+[[package]]+name = "ug"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03719c61a91b51541f076dfdba45caacf750b230cefaa4b32d6f5411c3f7f437"+dependencies = [+ "gemm 0.18.2",+ "half",+ "libloading 0.8.6",+ "memmap2 0.9.5",+ "num",+ "num-traits",+ "num_cpus",+ "rayon",+ "safetensors",+ "serde",+ "thiserror 1.0.69",+ "tracing",+ "yoke",+]++[[package]]+name = "uiautomation"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "451078b8ebbaeae100a83e89edd398dec2d7ca3feeb3a0623a1602bc0ec1dfba"+dependencies = [+ "chrono",+ "uiautomation_derive",+ "windows 0.59.0",+ "windows-core 0.59.0",+]++[[package]]+name = "uiautomation_derive"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d8cb8422f478d832e705e023c632fcf8b09b11a9b92c3f7f1db91425d8a2750"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "uname"version = "0.1.1"@@ -7796,12 +9138,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"[[package]]-name = "unicode-normalization"-version = "0.1.23"+name = "unicode-normalization-alignments"+version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5"+checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"dependencies = [- "tinyvec",+ "smallvec",][[package]]@@ -7828,6 +9170,34 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"+[[package]]+name = "unicode-width"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"++[[package]]+name = "unicode_categories"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"++[[package]]+name = "universal-hash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"+dependencies = [+ "crypto-common",+ "subtle",+]+[[package]]name = "untrusted"version = "0.9.0"@@ -7841,20 +9211,56 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"dependencies = ["base64 0.22.1",+ "flate2","log","native-tls","once_cell",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "socks","url",+ "webpki-roots 0.26.3",+]++[[package]]+name = "ureq"+version = "3.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d39cb1dbab692d82a977c0392ffac19e188bd9186a9f32806f0aaa859d75585a"+dependencies = [+ "base64 0.22.1",+ "flate2",+ "log",+ "percent-encoding",+ "rustls",+ "rustls-pki-types",+ "ureq-proto",+ "utf-8",+ "webpki-roots 1.0.5",+]++[[package]]+name = "ureq-proto"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d81f9efa9df032be5934a46a068815a10a042b494b6a58cb0a1a97bb5467ed6f"+dependencies = [+ "base64 0.22.1",+ "http 1.4.0",+ "httparse",+ "log",][[package]]name = "url"-version = "2.5.2"+version = "2.5.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c"+checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60"dependencies = ["form_urlencoded",- "idna 0.5.0",+ "idna","percent-encoding","serde",]@@ -7951,9 +9357,9 @@ checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d"[[package]]name = "value-bag"-version = "1.10.0"+version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2"+checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"[[package]]name = "vcpkg"@@ -7969,9 +9375,9 @@ checksum = "852e951cb7832cb45cb1169900d19760cfa39b82bc0ea9c0e5a14ae88411c98b"[[package]]name = "version_check"-version = "0.9.4"+version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"[[package]]name = "vswhom"@@ -8074,7 +9480,7 @@ dependencies = ["once_cell","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","wasm-bindgen-shared",]@@ -8108,7 +9514,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","wasm-bindgen-backend","wasm-bindgen-shared",]@@ -8202,6 +9608,16 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]+[[package]]name = "webkit2gtk"version = "2.0.1"@@ -8255,6 +9671,15 @@ dependencies = ["rustls-pki-types",]+[[package]]+name = "webpki-roots"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "webview2-com"version = "0.38.2"@@ -8277,7 +9702,7 @@ checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -8297,6 +9722,18 @@ version = "0.1.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "53a85b86a771b1c87058196170769dd264f66c0782acf1ae6cc51bfd64b39082"+[[package]]+name = "which"+version = "6.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"+dependencies = [+ "either",+ "home",+ "rustix 0.38.34",+ "winsafe",+]+[[package]]name = "winapi"version = "0.3.9"@@ -8373,6 +9810,16 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f919aee0a93304be7f62e8e5027811bbba96bcb1de84d6618be56e43f8a32a1"+dependencies = [+ "windows-core 0.59.0",+ "windows-targets 0.53.5",+]+[[package]]name = "windows"version = "0.61.3"@@ -8429,6 +9876,19 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows-core"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "810ce18ed2112484b0d4e15d022e5f598113e220c53e373fb31e67e21670c1ce"+dependencies = [+ "windows-implement 0.59.0",+ "windows-interface 0.59.3",+ "windows-result 0.3.4",+ "windows-strings 0.3.1",+ "windows-targets 0.53.5",+]+[[package]]name = "windows-core"version = "0.61.2"@@ -8474,7 +9934,7 @@ checksum = "f6fc35f58ecd95a9b71c4f2329b911016e6bec66b3f2e6a4aad86bd2e99e2f9b"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -8485,7 +9945,18 @@ checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",+]++[[package]]+name = "windows-implement"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",][[package]]@@ -8496,7 +9967,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -8507,7 +9978,7 @@ checksum = "08990546bf4edef8f431fa6326e032865f27138718c587dc21bc0265bbcb57cc"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -8518,7 +9989,7 @@ checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -8529,7 +10000,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",][[package]]@@ -8613,6 +10084,15 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows-strings"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319"+dependencies = [+ "windows-link 0.1.3",+]+[[package]]name = "windows-strings"version = "0.4.2"@@ -8984,6 +10464,12 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "winsafe"+version = "0.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"+[[package]]name = "wit-bindgen"version = "0.51.0"@@ -9018,7 +10504,7 @@ dependencies = ["gdkx11","gtk","html5ever",- "http 1.1.0",+ "http 1.4.0","javascriptcore-rs","jni","kuchikiki",@@ -9107,6 +10593,21 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"+[[package]]+name = "xxhash-rust"+version = "0.8.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3"++[[package]]+name = "xz2"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2"+dependencies = [+ "lzma-sys",+]+[[package]]name = "yoke"version = "0.7.5"@@ -9127,7 +10628,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","synstructure",]@@ -9229,7 +10730,7 @@ dependencies = ["proc-macro-crate 3.2.0","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","zbus_names 4.3.1","zvariant 5.9.2","zvariant_utils 3.3.0",@@ -9257,6 +10758,26 @@ dependencies = ["zvariant 5.9.2",]+[[package]]+name = "zerocopy"+version = "0.8.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7456cf00f0685ad319c5b1693f291a650eaf345e941d082fc4e03df8a03996ac"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1328722bbf2115db7e19d69ebcc15e795719e2d66b60827c6a69a117365e37a0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "zerofrom"version = "0.1.5"@@ -9274,7 +10795,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","synstructure",]@@ -9283,6 +10804,20 @@ name = "zeroize"version = "1.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+][[package]]name = "zerovec"@@ -9303,7 +10838,42 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6"dependencies = ["proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114",+]++[[package]]+name = "zip"+version = "0.6.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"+dependencies = [+ "aes",+ "byteorder",+ "bzip2",+ "constant_time_eq",+ "crc32fast",+ "crossbeam-utils",+ "flate2",+ "hmac",+ "pbkdf2",+ "sha1",+ "time",+ "zstd",+]++[[package]]+name = "zip"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cc23c04387f4da0374be4533ad1208cbb091d5c11d070dfef13676ad6497164"+dependencies = [+ "arbitrary",+ "crc32fast",+ "crossbeam-utils",+ "displaydoc",+ "indexmap 2.13.0",+ "num_enum",+ "thiserror 1.0.69",][[package]]@@ -9314,8 +10884,57 @@ checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"dependencies = ["arbitrary","crc32fast",+ "flate2","indexmap 2.13.0","memchr",+ "zopfli",+]++[[package]]+name = "zlib-rs"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40990edd51aae2c2b6907af74ffb635029d5788228222c4bb811e9351c0caad3"++[[package]]+name = "zopfli"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edfc5ee405f504cd4984ecc6f14d02d55cfda60fa4b689434ef4102aae150cd7"+dependencies = [+ "bumpalo",+ "crc32fast",+ "log",+ "simd-adler32",+]++[[package]]+name = "zstd"+version = "0.11.2+zstd.1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4"+dependencies = [+ "zstd-safe",+]++[[package]]+name = "zstd-safe"+version = "5.0.2+zstd.1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db"+dependencies = [+ "libc",+ "zstd-sys",+]++[[package]]+name = "zstd-sys"+version = "2.0.16+zstd.1.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"+dependencies = [+ "cc",+ "pkg-config",][[package]]@@ -9393,7 +11012,7 @@ dependencies = ["proc-macro-crate 3.2.0","proc-macro2","quote",- "syn 2.0.90",+ "syn 2.0.114","zvariant_utils 3.3.0",]@@ -9417,6 +11036,6 @@ dependencies = ["proc-macro2","quote","serde",- "syn 2.0.90",+ "syn 2.0.114","winnow 0.7.14",]diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 88c21e90c..0ee5347a7 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -97,6 +97,13 @@ chrono = "0.4.39"tauri-plugin-opener = "2.5.0"uuid = { version = "1.0", features = ["v4"] }+# Cloud sync utilities+hostname = "0.4"+md5 = "0.7"++# Screenpipe core (for sync)+screenpipe-core = { path = "../../screenpipe-core", features = ["cloud-sync"] }+[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]tauri-plugin-cli = "2.4.0"tauri-plugin-global-shortcut = "2"@@ -106,7 +113,7 @@ tauri-plugin-single-instance = { version = "2.3.3", features = ["deep-link"] }tauri-plugin-updater = "2.9.0"[target.'cfg(target_os = "macos")'.dependencies]-core-foundation = "=0.10.0"+core-foundation = "0.10"libc = "0.2.152"cocoa = "0.26.0"objc = "0.2.7"diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex 9df0fae36..132b5de66 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -51,6 +51,7 @@ mod window_api;mod windows_overlay;#[cfg(target_os = "macos")]mod space_monitor;+mod sync;pub use server::*;@@ -791,6 +792,17 @@ async fn main() {// Commands from tray.rsset_tray_unhealth_icon,set_tray_health_icon,+ // Commands from sync.rs+ sync::get_sync_status,+ sync::set_sync_enabled,+ sync::trigger_sync,+ sync::get_sync_config,+ sync::update_sync_config,+ sync::get_sync_devices,+ sync::remove_sync_device,+ sync::init_sync,+ sync::lock_sync,+ sync::delete_cloud_data,// OpenCode commandsopencode::opencode_info,opencode::opencode_start,@@ -799,7 +811,10 @@ async fn main() {opencode::opencode_install,]).typ::<SettingsStore>()- .typ::<OnboardingStore>();+ .typ::<OnboardingStore>()+ .typ::<sync::SyncStatusResponse>()+ .typ::<sync::SyncDeviceInfo>()+ .typ::<sync::SyncConfig>();builder.export(@@ -908,6 +923,17 @@ async fn main() {suspend_global_shortcuts,resume_global_shortcuts,get_env,+ // Sync commands+ sync::get_sync_status,+ sync::set_sync_enabled,+ sync::trigger_sync,+ sync::get_sync_config,+ sync::update_sync_config,+ sync::get_sync_devices,+ sync::remove_sync_device,+ sync::init_sync,+ sync::lock_sync,+ sync::delete_cloud_data,// OpenCode commandsopencode::opencode_info,opencode::opencode_start,@@ -1040,6 +1066,9 @@ async fn main() {});app.manage(store.clone());+ // Initialize sync state+ app.manage(sync::SyncState::default());+// Initialize onboarding storelet onboarding_store = store::init_onboarding_store(&app.handle()).unwrap_or_else(|e| {error!("Failed to init onboarding store, using defaults: {}", e);diff --git a/screenpipe-app-tauri/src-tauri/src/sync.rs b/screenpipe-app-tauri/src-tauri/src/sync.rsnew file mode 100644index 000000000..d03489c94--- /dev/null+++ b/screenpipe-app-tauri/src-tauri/src/sync.rs@@ -0,0 +1,348 @@+//! Tauri commands for cloud sync operations.++use crate::store::SettingsStore;+use chrono::Utc;+use screenpipe_core::sync::{SyncClientConfig, SyncManager};+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tauri::{AppHandle, State};+use tokio::sync::RwLock;+use tracing::{debug, info};+use uuid::Uuid;++/// Sync state managed by Tauri.+pub struct SyncState {+ /// Whether sync is enabled+ pub enabled: Arc<RwLock<bool>>,+ /// Whether currently syncing+ 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>>>,+ /// Sync manager (initialized after password entry)+ pub manager: Arc<RwLock<Option<Arc<SyncManager>>>>,+ /// Machine ID for this device+ pub machine_id: String,+}++impl Default for SyncState {+ fn default() -> Self {+ // Generate or load machine ID+ let machine_id = get_or_create_machine_id();++ Self {+ enabled: Arc::new(RwLock::new(false)),+ is_syncing: Arc::new(RwLock::new(false)),+ last_sync: Arc::new(RwLock::new(None)),+ last_error: Arc::new(RwLock::new(None)),+ manager: Arc::new(RwLock::new(None)),+ machine_id,+ }+ }+}++/// Get or create a persistent machine ID+fn get_or_create_machine_id() -> String {+ // In a real implementation, this would be stored persistently+ // For now, use a hash of the hostname+ if let Ok(hostname) = hostname::get() {+ let hostname_str = hostname.to_string_lossy();+ format!("{:x}", md5::compute(hostname_str.as_bytes()))+ } else {+ Uuid::new_v4().to_string()+ }+}++/// Sync status response.+#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)]+#[serde(rename_all = "camelCase")]+pub struct SyncStatusResponse {+ pub enabled: bool,+ pub is_syncing: bool,+ pub last_sync: Option<String>,+ pub last_error: Option<String>,+ pub storage_used: Option<u64>,+ pub storage_limit: Option<u64>,+ pub device_count: Option<u32>,+ pub device_limit: Option<u32>,+ pub sync_tier: Option<String>,+ pub machine_id: String,+}++/// Device information.+#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)]+#[serde(rename_all = "camelCase")]+pub struct SyncDeviceInfo {+ pub id: String,+ pub device_id: String,+ pub device_name: Option<String>,+ pub device_os: String,+ pub last_sync_at: Option<String>,+ pub created_at: String,+ pub is_current: bool,+}++/// Sync configuration.+#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)]+#[serde(rename_all = "camelCase")]+pub struct SyncConfig {+ pub enabled: bool,+ pub sync_interval_minutes: u32,+ pub sync_transcripts: bool,+ pub sync_ocr: bool,+ pub sync_audio: bool,+ pub sync_frames: bool,+}++impl Default for SyncConfig {+ fn default() -> Self {+ Self {+ enabled: false,+ sync_interval_minutes: 5,+ sync_transcripts: true,+ sync_ocr: true,+ sync_audio: false,+ sync_frames: false,+ }+ }+}++/// Get current sync status.+#[tauri::command]+#[specta::specta]+pub async fn get_sync_status(+ state: State<'_, SyncState>,+ _settings: State<'_, SettingsStore>,+) -> Result<SyncStatusResponse, String> {+ let enabled = *state.enabled.read().await;+ let is_syncing = *state.is_syncing.read().await;+ let last_sync = state.last_sync.read().await.clone();+ let last_error = state.last_error.read().await.clone();++ // Try to get real status from API if we have a manager+ let manager_guard = state.manager.read().await;+ if let Some(manager) = manager_guard.as_ref() {+ match manager.get_status().await {+ Ok(status) => {+ return Ok(SyncStatusResponse {+ enabled,+ is_syncing,+ last_sync,+ last_error,+ storage_used: Some(status.quota.storage_used),+ storage_limit: Some(status.quota.storage_limit),+ device_count: Some(status.quota.device_count),+ device_limit: Some(status.quota.device_limit),+ sync_tier: status.quota.sync_tier,+ machine_id: state.machine_id.clone(),+ });+ }+ Err(e) => {+ debug!("failed to get sync status from API: {}", e);+ }+ }+ }++ Ok(SyncStatusResponse {+ enabled,+ is_syncing,+ last_sync,+ last_error,+ storage_used: None,+ storage_limit: None,+ device_count: None,+ device_limit: None,+ sync_tier: None,+ machine_id: state.machine_id.clone(),+ })+}++/// Enable or disable sync.+#[tauri::command]+#[specta::specta]+pub async fn set_sync_enabled(state: State<'_, SyncState>, enabled: bool) -> Result<(), String> {+ *state.enabled.write().await = enabled;++ if !enabled {+ // Lock the manager when disabling+ let manager_guard = state.manager.read().await;+ if let Some(manager) = manager_guard.as_ref() {+ manager.lock().await;+ }+ }++ Ok(())+}++/// Trigger an immediate sync.+#[tauri::command]+#[specta::specta]+pub async fn trigger_sync(state: State<'_, SyncState>) -> Result<(), String> {+ let enabled = *state.enabled.read().await;+ if !enabled {+ return Err("sync is not enabled".to_string());+ }++ let is_syncing = *state.is_syncing.read().await;+ if is_syncing {+ return Err("sync already in progress".to_string());+ }++ let manager_guard = state.manager.read().await;+ if manager_guard.is_none() {+ return Err("sync not initialized - enter password first".to_string());+ }++ // Mark as syncing+ *state.is_syncing.write().await = true;++ // TODO: Trigger actual sync via SyncService+ // For now, simulate completion+ let is_syncing = state.is_syncing.clone();+ let last_sync = state.last_sync.clone();+ tokio::spawn(async move {+ tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;+ *is_syncing.write().await = false;+ *last_sync.write().await = Some(Utc::now().to_rfc3339());+ });++ Ok(())+}++/// Get sync configuration.+#[tauri::command]+#[specta::specta]+pub async fn get_sync_config() -> Result<SyncConfig, String> {+ // TODO: Read from persistent storage+ Ok(SyncConfig::default())+}++/// Update sync configuration.+#[tauri::command]+#[specta::specta]+pub async fn update_sync_config(state: State<'_, SyncState>, config: SyncConfig) -> Result<(), String> {+ *state.enabled.write().await = config.enabled;+ // TODO: Persist config and update sync service+ Ok(())+}++/// Get list of registered devices.+#[tauri::command]+#[specta::specta]+pub async fn get_sync_devices(state: State<'_, SyncState>) -> Result<Vec<SyncDeviceInfo>, String> {+ let manager_guard = state.manager.read().await;+ if let Some(manager) = manager_guard.as_ref() {+ match manager.get_devices().await {+ Ok(devices) => {+ return Ok(devices+ .into_iter()+ .map(|d| SyncDeviceInfo {+ id: d.id,+ device_id: d.device_id.clone(),+ device_name: d.device_name,+ device_os: d.device_os,+ last_sync_at: d.last_sync_at,+ created_at: d.created_at,+ is_current: d.device_id == state.machine_id,+ })+ .collect());+ }+ Err(e) => {+ return Err(format!("failed to get devices: {}", e));+ }+ }+ }++ Ok(vec![])+}++/// Remove a device from sync.+#[tauri::command]+#[specta::specta]+pub async fn remove_sync_device(+ state: State<'_, SyncState>,+ device_id: String,+) -> Result<(), String> {+ let manager_guard = state.manager.read().await;+ if let Some(manager) = manager_guard.as_ref() {+ manager+ .remove_device(&device_id)+ .await+ .map_err(|e| format!("failed to remove device: {}", e))?;+ }+ Ok(())+}++/// Initialize sync with password.+#[tauri::command]+#[specta::specta]+pub async fn init_sync(+ _app: AppHandle,+ state: State<'_, SyncState>,+ settings: State<'_, SettingsStore>,+ password: String,+) -> Result<bool, String> {+ // Get auth token from settings+ let token = settings+ .user+ .token+ .clone()+ .ok_or_else(|| "not logged in - please log in first".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 client config+ let config = SyncClientConfig::new(token, state.machine_id.clone(), device_name, device_os);++ // Create 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)+ let is_new_user = manager+ .initialize(&password)+ .await+ .map_err(|e| format!("failed to initialize sync: {}", e))?;++ // Store the manager+ *state.manager.write().await = Some(Arc::new(manager));+ *state.enabled.write().await = true;++ info!(+ "sync initialized for {} user",+ if is_new_user { "new" } else { "existing" }+ );++ Ok(is_new_user)+}++/// Lock sync (clear keys from memory).+#[tauri::command]+#[specta::specta]+pub async fn lock_sync(state: State<'_, SyncState>) -> Result<(), String> {+ let manager_guard = state.manager.read().await;+ if let Some(manager) = manager_guard.as_ref() {+ manager.lock().await;+ }+ *state.enabled.write().await = false;+ Ok(())+}++/// Delete all cloud data.+#[tauri::command]+#[specta::specta]+pub async fn delete_cloud_data(state: State<'_, SyncState>) -> Result<(), String> {+ let manager_guard = state.manager.read().await;+ if let Some(manager) = manager_guard.as_ref() {+ manager+ .delete_all_data()+ .await+ .map_err(|e| format!("failed to delete cloud data: {}", e))?;+ }+ Ok(())+}diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex 47cbf22dd..9f84e8de4 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -41,6 +41,18 @@ clap = { version = "4.5.20", features = ["derive"] }# randomrand = "0.8.5"+# Cloud sync encryption+argon2 = { version = "0.5", optional = true }+chacha20poly1305 = { version = "0.10", optional = true }+hmac = { version = "0.12", optional = true }+sha2 = { version = "0.10", optional = true }+base64 = { version = "0.22", optional = true }+zeroize = { version = "1.8", features = ["derive"], optional = true }+thiserror = { version = "1.0", optional = true }+reqwest = { workspace = true, optional = true }+hex = { version = "0.4", optional = true }+async-trait = { version = "0.1", optional = true }+once_cell = "1.19.0"cron = "0.13.0"@@ -58,6 +70,18 @@ metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]llm = []+cloud-sync = [+ "dep:argon2",+ "dep:chacha20poly1305",+ "dep:hmac",+ "dep:sha2",+ "dep:base64",+ "dep:zeroize",+ "dep:thiserror",+ "dep:reqwest",+ "dep:hex",+ "dep:async-trait",+][target.'cfg(target_os = "macos")'.dependencies]# accessibility-sys = "0.1.3"@@ -67,7 +91,7 @@ accessibility = { git = "https://github.com/eiz/accessibility.git", branch = "maobjc = "0.2.7"objc-foundation = "0.1.1"-core-foundation = "=0.10.0"+core-foundation = "0.10"core-graphics = { version = "0.24.0", features = ["highsierra"] }[target.'cfg(target_os = "windows")'.dependencies]diff --git a/screenpipe-core/src/lib.rs b/screenpipe-core/src/lib.rsindex 4926a33dc..8cc332b89 100644--- a/screenpipe-core/src/lib.rs+++ b/screenpipe-core/src/lib.rs@@ -38,3 +38,8 @@ pub use network::*;pub use language::{Language, TESSERACT_LANGUAGES};pub mod embedding;pub use embedding::*;++#[cfg(feature = "cloud-sync")]+pub mod sync;+#[cfg(feature = "cloud-sync")]+pub use sync::*;diff --git a/screenpipe-core/src/sync/blob.rs b/screenpipe-core/src/sync/blob.rsnew file mode 100644index 000000000..dc5ed4c09--- /dev/null+++ b/screenpipe-core/src/sync/blob.rs@@ -0,0 +1,302 @@+//! Encrypted blob handling for cloud sync.+//!+//! This module handles packaging, encrypting, and decrypting data blobs+//! that are stored in the cloud.++use base64::{engine::general_purpose::STANDARD as BASE64, Engine};+use serde::{Deserialize, Serialize};++use super::crypto::{+ compute_checksum, decrypt, encrypt, generate_nonce, generate_search_tokens_from_text,+ HMAC_SIZE, NONCE_SIZE,+};+use super::error::{SyncError, SyncResult};+use super::keys::SyncKeys;++/// Types of data blobs that can be synced.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum BlobType {+ /// Screen capture frames (images)+ Frames,+ /// Audio recordings+ Audio,+ /// Transcriptions of audio+ Transcripts,+ /// OCR text from screen captures+ Ocr,+}++impl BlobType {+ pub fn as_str(&self) -> &'static str {+ match self {+ BlobType::Frames => "frames",+ BlobType::Audio => "audio",+ BlobType::Transcripts => "transcripts",+ BlobType::Ocr => "ocr",+ }+ }+}++impl std::fmt::Display for BlobType {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.as_str())+ }+}++/// An encrypted blob ready for upload.+#[derive(Debug)]+pub struct EncryptedBlob {+ /// The encrypted data (ciphertext + auth tag)+ pub ciphertext: Vec<u8>,+ /// The nonce used for encryption (must be stored for decryption)+ pub nonce: [u8; NONCE_SIZE],+ /// SHA-256 checksum of the plaintext (for integrity verification)+ pub checksum: String,+ /// The type of data in this blob+ pub blob_type: BlobType,+ /// Size of the original plaintext in bytes+ pub plaintext_size: usize,+ /// Search tokens extracted from the content (for text-based blobs)+ pub search_tokens: Vec<[u8; HMAC_SIZE]>,+}++impl EncryptedBlob {+ /// Get the nonce as base64.+ pub fn nonce_base64(&self) -> String {+ BASE64.encode(self.nonce)+ }++ /// Get search tokens as base64 strings.+ pub fn search_tokens_base64(&self) -> Vec<String> {+ self.search_tokens.iter().map(|t| BASE64.encode(t)).collect()+ }+}++/// A decrypted blob.+#[derive(Debug)]+pub struct DecryptedBlob {+ /// The decrypted plaintext data+ pub data: Vec<u8>,+ /// The type of data+ pub blob_type: BlobType,+}++/// Encrypt data into a blob for upload.+///+/// # Arguments+/// * `data` - The plaintext data to encrypt+/// * `blob_type` - The type of data+/// * `keys` - The sync keys for encryption+/// * `text_content` - Optional text content for search token generation+///+/// # Returns+/// An encrypted blob ready for upload+pub fn encrypt_blob(+ data: &[u8],+ blob_type: BlobType,+ keys: &SyncKeys,+ text_content: Option<&str>,+) -> SyncResult<EncryptedBlob> {+ // Generate unique nonce+ let nonce = generate_nonce();++ // Compute checksum of plaintext+ let checksum = compute_checksum(data);++ // Encrypt the data+ let ciphertext = encrypt(data, keys.data_key(), &nonce)?;++ // Generate search tokens if text content is provided+ let search_tokens = if let Some(text) = text_content {+ generate_search_tokens_from_text(text, keys.search_key())?+ } else {+ Vec::new()+ };++ Ok(EncryptedBlob {+ ciphertext,+ nonce,+ checksum,+ blob_type,+ plaintext_size: data.len(),+ search_tokens,+ })+}++/// Decrypt a blob downloaded from the cloud.+///+/// # Arguments+/// * `ciphertext` - The encrypted data+/// * `nonce` - The nonce used during encryption (base64)+/// * `expected_checksum` - The expected SHA-256 checksum (optional, for verification)+/// * `blob_type` - The type of data+/// * `keys` - The sync keys for decryption+///+/// # Returns+/// The decrypted blob data+pub fn decrypt_blob(+ ciphertext: &[u8],+ nonce: &str,+ expected_checksum: Option<&str>,+ blob_type: BlobType,+ keys: &SyncKeys,+) -> SyncResult<DecryptedBlob> {+ // Decode nonce+ let nonce_bytes = BASE64.decode(nonce)?;+ if nonce_bytes.len() != NONCE_SIZE {+ return Err(SyncError::DataCorruption(format!(+ "invalid nonce length: expected {}, got {}",+ NONCE_SIZE,+ nonce_bytes.len()+ )));+ }++ let mut nonce_array = [0u8; NONCE_SIZE];+ nonce_array.copy_from_slice(&nonce_bytes);++ // Decrypt+ let data = decrypt(ciphertext, keys.data_key(), &nonce_array)?;++ // Verify checksum if provided+ if let Some(expected) = expected_checksum {+ let actual = compute_checksum(&data);+ if actual != expected {+ return Err(SyncError::DataCorruption(format!(+ "checksum mismatch: expected {}, got {}",+ expected, actual+ )));+ }+ }++ Ok(DecryptedBlob { data, blob_type })+}++/// Metadata for an encrypted blob (used for API requests).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BlobMetadata {+ /// Unique blob ID (assigned by server)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub blob_id: Option<String>,+ /// Type of blob+ pub blob_type: BlobType,+ /// Start of time range covered by this blob+ pub time_start: String, // ISO 8601+ /// End of time range covered by this blob+ pub time_end: String, // ISO 8601+ /// Size in bytes+ pub size_bytes: u64,+ /// SHA-256 checksum of plaintext+ pub checksum: String,+ /// Encryption nonce (base64)+ pub encryption_nonce: String,+ /// Key version used for encryption+ pub key_version: u32,+ /// Search tokens (base64 encoded)+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub search_tokens: Vec<String>,+}++impl BlobMetadata {+ /// Create metadata from an encrypted blob.+ pub fn from_encrypted_blob(+ blob: &EncryptedBlob,+ time_start: &str,+ time_end: &str,+ key_version: u32,+ ) -> Self {+ Self {+ blob_id: None,+ blob_type: blob.blob_type,+ time_start: time_start.to_string(),+ time_end: time_end.to_string(),+ size_bytes: blob.ciphertext.len() as u64,+ checksum: blob.checksum.clone(),+ encryption_nonce: blob.nonce_base64(),+ key_version,+ search_tokens: blob.search_tokens_base64(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sync::keys::NewUserKeyData;++ fn test_keys() -> SyncKeys {+ let (_key_data, keys) = NewUserKeyData::generate("test-password").unwrap();+ keys+ }++ #[test]+ fn test_encrypt_decrypt_blob() {+ let keys = test_keys();+ let data = b"Hello, World! This is test data for the blob.";++ let encrypted = encrypt_blob(data, BlobType::Ocr, &keys, Some("Hello World test")).unwrap();++ assert_ne!(encrypted.ciphertext, data);+ assert!(!encrypted.checksum.is_empty());+ assert!(!encrypted.search_tokens.is_empty());++ let decrypted = decrypt_blob(+ &encrypted.ciphertext,+ &encrypted.nonce_base64(),+ Some(&encrypted.checksum),+ BlobType::Ocr,+ &keys,+ )+ .unwrap();++ assert_eq!(decrypted.data, data);+ assert_eq!(decrypted.blob_type, BlobType::Ocr);+ }++ #[test]+ fn test_checksum_verification() {+ let keys = test_keys();+ let data = b"Some important data";++ let encrypted = encrypt_blob(data, BlobType::Transcripts, &keys, None).unwrap();++ // Correct checksum should work+ let result = decrypt_blob(+ &encrypted.ciphertext,+ &encrypted.nonce_base64(),+ Some(&encrypted.checksum),+ BlobType::Transcripts,+ &keys,+ );+ assert!(result.is_ok());++ // Wrong checksum should fail+ let result = decrypt_blob(+ &encrypted.ciphertext,+ &encrypted.nonce_base64(),+ Some("wrong-checksum"),+ BlobType::Transcripts,+ &keys,+ );+ assert!(result.is_err());+ }++ #[test]+ fn test_blob_metadata() {+ let keys = test_keys();+ let data = b"Test data";++ let encrypted = encrypt_blob(data, BlobType::Audio, &keys, None).unwrap();++ let metadata = BlobMetadata::from_encrypted_blob(+ &encrypted,+ "2024-01-01T00:00:00Z",+ "2024-01-01T01:00:00Z",+ 1,+ );++ assert_eq!(metadata.blob_type, BlobType::Audio);+ assert_eq!(metadata.checksum, encrypted.checksum);+ assert_eq!(metadata.key_version, 1);+ }+}diff --git a/screenpipe-core/src/sync/client.rs b/screenpipe-core/src/sync/client.rsnew file mode 100644index 000000000..d06f26eb9--- /dev/null+++ b/screenpipe-core/src/sync/client.rs@@ -0,0 +1,898 @@+//! Sync API client for cloud sync operations.+//!+//! This module provides the HTTP client for communicating with the+//! Screenpipe cloud sync API.++use reqwest::{Client, StatusCode};+use serde::{Deserialize, Serialize};++use super::blob::{BlobMetadata, BlobType};+use super::error::{SyncError, SyncResult};+use super::keys::{ExistingUserKeyData, NewUserKeyData, SyncKeys};++/// Default API base URL+const DEFAULT_API_URL: &str = "https://screenpi.pe/api/sync";++/// Configuration for the sync client.+#[derive(Debug, Clone)]+pub struct SyncClientConfig {+ /// Base URL for the sync API+ pub api_url: String,+ /// Authentication token (Clerk JWT)+ pub auth_token: String,+ /// Device ID (unique identifier for this device)+ pub device_id: String,+ /// Device name (user-friendly name)+ pub device_name: String,+ /// Device OS+ pub device_os: String,+ /// App version+ pub app_version: Option<String>,+}++impl SyncClientConfig {+ /// Create a new config with default API URL.+ pub fn new(+ auth_token: String,+ device_id: String,+ device_name: String,+ device_os: String,+ ) -> Self {+ Self {+ api_url: DEFAULT_API_URL.to_string(),+ auth_token,+ device_id,+ device_name,+ device_os,+ app_version: None,+ }+ }++ /// Set the API URL.+ pub fn with_api_url(mut self, url: String) -> Self {+ self.api_url = url;+ self+ }++ /// Set the app version.+ pub fn with_app_version(mut self, version: String) -> Self {+ self.app_version = Some(version);+ self+ }+}++/// Client for sync API operations.+pub struct SyncClient {+ config: SyncClientConfig,+ http: Client,+}++impl SyncClient {+ /// Create a new sync client.+ pub fn new(config: SyncClientConfig) -> SyncResult<Self> {+ let http = Client::builder()+ .timeout(std::time::Duration::from_secs(30))+ .build()+ .map_err(|e| SyncError::Network(format!("failed to create HTTP client: {}", e)))?;++ Ok(Self { config, http })+ }++ /// Get the device ID.+ pub fn device_id(&self) -> &str {+ &self.config.device_id+ }++ // =========================================================================+ // Init / Key Management+ // =========================================================================++ /// Initialize sync for a new user.+ ///+ /// This generates new encryption keys and registers them with the server.+ pub async fn init_new_user(&self, password: &str) -> SyncResult<SyncKeys> {+ let (key_data, keys) = NewUserKeyData::generate(password)?;++ let request = InitRequest {+ device_id: self.config.device_id.clone(),+ device_name: self.config.device_name.clone(),+ device_os: self.config.device_os.clone(),+ device_os_version: None,+ app_version: self.config.app_version.clone(),+ encrypted_master_key: Some(key_data.encrypted_master_key),+ master_key_nonce: Some(key_data.master_key_nonce),+ salt: Some(key_data.salt),+ };++ let response: InitResponse = self.post("/init", &request).await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "init failed".to_string()),+ ));+ }++ Ok(keys)+ }++ /// Initialize sync for an existing user.+ ///+ /// This fetches the encrypted master key and derives the sync keys.+ pub async fn init_existing_user(&self, password: &str) -> SyncResult<SyncKeys> {+ let request = InitRequest {+ device_id: self.config.device_id.clone(),+ device_name: self.config.device_name.clone(),+ device_os: self.config.device_os.clone(),+ device_os_version: None,+ app_version: self.config.app_version.clone(),+ encrypted_master_key: None,+ master_key_nonce: None,+ salt: None,+ };++ let response: InitResponse = self.post("/init", &request).await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "init failed".to_string()),+ ));+ }++ // For existing users, server returns the key data+ let key_data = ExistingUserKeyData {+ salt: response.salt.ok_or_else(|| SyncError::Key("missing salt".to_string()))?,+ encrypted_master_key: response+ .encrypted_master_key+ .ok_or_else(|| SyncError::Key("missing encrypted_master_key".to_string()))?,+ master_key_nonce: response+ .master_key_nonce+ .ok_or_else(|| SyncError::Key("missing master_key_nonce".to_string()))?,+ kdf_algorithm: response.kdf_algorithm.unwrap_or_else(|| "argon2id".to_string()),+ kdf_iterations: response.kdf_iterations.unwrap_or(3),+ kdf_memory: response.kdf_memory.unwrap_or(65536),+ key_version: response.key_version.unwrap_or(1),+ };++ key_data.derive_keys(password)+ }++ /// Initialize sync - automatically detects new vs existing user.+ pub async fn init(&self, password: &str) -> SyncResult<(SyncKeys, bool)> {+ // Try as existing user first+ let request = InitRequest {+ device_id: self.config.device_id.clone(),+ device_name: self.config.device_name.clone(),+ device_os: self.config.device_os.clone(),+ device_os_version: None,+ app_version: self.config.app_version.clone(),+ encrypted_master_key: None,+ master_key_nonce: None,+ salt: None,+ };++ let response: InitResponse = self.post("/init", &request).await?;++ if !response.success {+ let code = response.code.as_deref();+ if code == Some("NO_SUBSCRIPTION") {+ return Err(SyncError::NoSubscription);+ }+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "init failed".to_string()),+ ));+ }++ let is_new_user = response.is_new_user.unwrap_or(false);++ if is_new_user {+ // New user - generate and upload keys+ let keys = self.init_new_user(password).await?;+ Ok((keys, true))+ } else {+ // Existing user - derive keys from server response+ let key_data = ExistingUserKeyData {+ salt: response.salt.ok_or_else(|| SyncError::Key("missing salt".to_string()))?,+ encrypted_master_key: response+ .encrypted_master_key+ .ok_or_else(|| SyncError::Key("missing encrypted_master_key".to_string()))?,+ master_key_nonce: response+ .master_key_nonce+ .ok_or_else(|| SyncError::Key("missing master_key_nonce".to_string()))?,+ kdf_algorithm: response.kdf_algorithm.unwrap_or_else(|| "argon2id".to_string()),+ kdf_iterations: response.kdf_iterations.unwrap_or(3),+ kdf_memory: response.kdf_memory.unwrap_or(65536),+ key_version: response.key_version.unwrap_or(1),+ };++ let keys = key_data.derive_keys(password)?;+ Ok((keys, false))+ }+ }++ // =========================================================================+ // Upload+ // =========================================================================++ /// Request a presigned URL for uploading a blob.+ pub async fn request_upload(+ &self,+ metadata: &BlobMetadata,+ ) -> SyncResult<UploadUrlResponse> {+ let request = UploadRequest {+ blob_type: metadata.blob_type,+ time_start: metadata.time_start.clone(),+ time_end: metadata.time_end.clone(),+ size_bytes: metadata.size_bytes,+ checksum: metadata.checksum.clone(),+ device_id: self.config.device_id.clone(),+ key_version: metadata.key_version,+ encryption_nonce: metadata.encryption_nonce.clone(),+ search_tokens: if metadata.search_tokens.is_empty() {+ None+ } else {+ Some(metadata.search_tokens.clone())+ },+ };++ let response: UploadResponse = self.post("/upload", &request).await?;++ if !response.success {+ let code = response.code.as_deref();+ if code == Some("QUOTA_EXCEEDED") {+ return Err(SyncError::QuotaExceeded(+ response.error.unwrap_or_else(|| "quota exceeded".to_string()),+ ));+ }+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "upload request failed".to_string()),+ ));+ }++ Ok(UploadUrlResponse {+ blob_id: response.blob_id.ok_or_else(|| SyncError::Server("missing blob_id".to_string()))?,+ upload_url: response.upload_url.ok_or_else(|| SyncError::Server("missing upload_url".to_string()))?,+ expires_in: response.expires_in.unwrap_or(300),+ })+ }++ /// Upload encrypted data to S3 using a presigned URL.+ pub async fn upload_to_s3(&self, upload_url: &str, data: &[u8]) -> SyncResult<()> {+ let response = self+ .http+ .put(upload_url)+ .header("Content-Type", "application/octet-stream")+ .body(data.to_vec())+ .send()+ .await?;++ if !response.status().is_success() {+ return Err(SyncError::Server(format!(+ "S3 upload failed with status: {}",+ response.status()+ )));+ }++ Ok(())+ }++ /// Mark an upload as completed.+ pub async fn complete_upload(&self, blob_id: &str) -> SyncResult<UploadCompleteResponse> {+ let request = UploadCompleteRequest {+ blob_id: blob_id.to_string(),+ };++ let response: UploadCompleteApiResponse = self.post("/upload/complete", &request).await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "complete upload failed".to_string()),+ ));+ }++ Ok(UploadCompleteResponse {+ storage_used: response.storage_used.unwrap_or(0),+ storage_limit: response.storage_limit.unwrap_or(0),+ })+ }++ // =========================================================================+ // Download+ // =========================================================================++ /// Get presigned download URLs for blobs.+ pub async fn get_download_urls(&self, request: DownloadRequest) -> SyncResult<Vec<DownloadBlob>> {+ let response: DownloadResponse = self.post("/download", &request).await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "download request failed".to_string()),+ ));+ }++ Ok(response.blobs)+ }++ /// Download encrypted data from S3.+ pub async fn download_from_s3(&self, download_url: &str) -> SyncResult<Vec<u8>> {+ let response = self.http.get(download_url).send().await?;++ if !response.status().is_success() {+ return Err(SyncError::Server(format!(+ "S3 download failed with status: {}",+ response.status()+ )));+ }++ let bytes = response.bytes().await?;+ Ok(bytes.to_vec())+ }++ // =========================================================================+ // Search+ // =========================================================================++ /// Search for blobs by tokens.+ pub async fn search(&self, request: SearchRequest) -> SyncResult<SearchResponse> {+ let response: SearchApiResponse = self.post("/search", &request).await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "search failed".to_string()),+ ));+ }++ Ok(SearchResponse {+ matches: response.matches,+ total_matches: response.total_matches.unwrap_or(0),+ })+ }++ // =========================================================================+ // Status+ // =========================================================================++ /// Get sync status and quota information.+ pub async fn get_status(&self) -> SyncResult<SyncStatus> {+ let response: StatusResponse = self.get("/status").await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "status request failed".to_string()),+ ));+ }++ Ok(SyncStatus {+ quota: response.quota.ok_or_else(|| SyncError::Server("missing quota".to_string()))?,+ stats: response.stats.ok_or_else(|| SyncError::Server("missing stats".to_string()))?,+ storage_breakdown: response.storage_breakdown,+ })+ }++ // =========================================================================+ // Devices+ // =========================================================================++ /// List registered devices.+ pub async fn list_devices(&self) -> SyncResult<Vec<SyncDevice>> {+ let response: DevicesResponse = self.get("/devices").await?;++ if !response.success {+ return Err(SyncError::Server(+ response.error.unwrap_or_else(|| "list devices failed".to_string()),+ ));+ }++ Ok(response.devices)+ }++ /// Remove a device.+ pub async fn remove_device(&self, device_id: &str) -> SyncResult<()> {+ let url = format!("{}/devices?device_id={}", self.config.api_url, device_id);++ let response = self+ .http+ .delete(&url)+ .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .send()+ .await?;++ if !response.status().is_success() {+ let error_body: ApiError = response.json().await.unwrap_or(ApiError {+ success: false,+ error: Some("unknown error".to_string()),+ code: None,+ });+ return Err(SyncError::Server(+ error_body.error.unwrap_or_else(|| "remove device failed".to_string()),+ ));+ }++ Ok(())+ }++ // =========================================================================+ // Data Management+ // =========================================================================++ /// Delete all cloud data for this user.+ pub async fn delete_all_data(&self) -> SyncResult<()> {+ let url = format!("{}/data", self.config.api_url);++ let response = self+ .http+ .delete(&url)+ .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .send()+ .await?;++ if !response.status().is_success() {+ let error_body: ApiError = response.json().await.unwrap_or(ApiError {+ success: false,+ error: Some("unknown error".to_string()),+ code: None,+ });+ return Err(SyncError::Server(+ error_body.error.unwrap_or_else(|| "delete all data failed".to_string()),+ ));+ }++ Ok(())+ }++ // =========================================================================+ // HTTP Helpers+ // =========================================================================++ async fn post<T: Serialize, R: for<'de> Deserialize<'de>>(+ &self,+ path: &str,+ body: &T,+ ) -> SyncResult<R> {+ let url = format!("{}{}", self.config.api_url, path);++ let response = self+ .http+ .post(&url)+ .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .header("X-Device-Id", &self.config.device_id)+ .json(body)+ .send()+ .await?;++ self.handle_response(response).await+ }++ async fn get<R: for<'de> Deserialize<'de>>(&self, path: &str) -> SyncResult<R> {+ let url = format!("{}{}", self.config.api_url, path);++ let response = self+ .http+ .get(&url)+ .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .header("X-Device-Id", &self.config.device_id)+ .send()+ .await?;++ self.handle_response(response).await+ }++ async fn handle_response<R: for<'de> Deserialize<'de>>(+ &self,+ response: reqwest::Response,+ ) -> SyncResult<R> {+ let status = response.status();++ if status == StatusCode::UNAUTHORIZED {+ return Err(SyncError::Auth("unauthorized".to_string()));+ }++ if status == StatusCode::FORBIDDEN {+ // Could be quota or subscription issue+ let error_body: ApiError = response.json().await.unwrap_or(ApiError {+ success: false,+ error: Some("forbidden".to_string()),+ code: None,+ });++ if error_body.code.as_deref() == Some("NO_SUBSCRIPTION") {+ return Err(SyncError::NoSubscription);+ }+ if error_body.code.as_deref() == Some("QUOTA_EXCEEDED") {+ return Err(SyncError::QuotaExceeded(+ error_body.error.unwrap_or_else(|| "quota exceeded".to_string()),+ ));+ }+ if error_body.code.as_deref() == Some("DEVICE_LIMIT_EXCEEDED") {+ return Err(SyncError::DeviceLimitExceeded);+ }++ return Err(SyncError::Server(+ error_body.error.unwrap_or_else(|| "forbidden".to_string()),+ ));+ }++ let body = response.text().await?;++ serde_json::from_str(&body).map_err(|e| {+ SyncError::Serialization(format!("failed to parse response: {} - body: {}", e, body))+ })+ }+}++// =============================================================================+// API Types+// =============================================================================++#[derive(Debug, Serialize)]+struct InitRequest {+ device_id: String,+ device_name: String,+ device_os: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ device_os_version: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ app_version: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ encrypted_master_key: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ master_key_nonce: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ salt: Option<String>,+}++#[derive(Debug, Deserialize)]+struct InitResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ code: Option<String>,+ #[serde(default)]+ is_new_user: Option<bool>,+ #[serde(default)]+ salt: Option<String>,+ #[serde(default)]+ encrypted_master_key: Option<String>,+ #[serde(default)]+ master_key_nonce: Option<String>,+ #[serde(default)]+ kdf_algorithm: Option<String>,+ #[serde(default)]+ kdf_iterations: Option<u32>,+ #[serde(default)]+ kdf_memory: Option<u32>,+ #[serde(default)]+ key_version: Option<u32>,+}++#[derive(Debug, Serialize)]+struct UploadRequest {+ blob_type: BlobType,+ time_start: String,+ time_end: String,+ size_bytes: u64,+ checksum: String,+ device_id: String,+ key_version: u32,+ encryption_nonce: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ search_tokens: Option<Vec<String>>,+}++#[derive(Debug, Deserialize)]+struct UploadResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ code: Option<String>,+ #[serde(default)]+ blob_id: Option<String>,+ #[serde(default)]+ upload_url: Option<String>,+ #[serde(default)]+ expires_in: Option<u32>,+}++/// Response from upload URL request.+#[derive(Debug)]+pub struct UploadUrlResponse {+ /// The blob ID assigned by the server+ pub blob_id: String,+ /// Presigned S3 upload URL+ pub upload_url: String,+ /// Seconds until URL expires+ pub expires_in: u32,+}++#[derive(Debug, Serialize)]+struct UploadCompleteRequest {+ blob_id: String,+}++#[derive(Debug, Deserialize)]+struct UploadCompleteApiResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ storage_used: Option<u64>,+ #[serde(default)]+ storage_limit: Option<u64>,+}++/// Response from completing an upload.+#[derive(Debug)]+pub struct UploadCompleteResponse {+ /// Current storage used in bytes+ pub storage_used: u64,+ /// Storage limit in bytes+ pub storage_limit: u64,+}++/// Request for downloading blobs.+#[derive(Debug, Clone, Serialize)]+pub struct DownloadRequest {+ /// Specific blob IDs to download+ #[serde(skip_serializing_if = "Option::is_none")]+ pub blob_ids: Option<Vec<String>>,+ /// Time range filter+ #[serde(skip_serializing_if = "Option::is_none")]+ pub time_range: Option<TimeRange>,+ /// Blob types to include+ #[serde(skip_serializing_if = "Option::is_none")]+ pub blob_types: Option<Vec<BlobType>>,+ /// Maximum number of blobs to return+ #[serde(skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++/// Time range for filtering.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TimeRange {+ /// Start of time range (ISO 8601)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub start: Option<String>,+ /// End of time range (ISO 8601)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub end: Option<String>,+}++#[derive(Debug, Deserialize)]+struct DownloadResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ blobs: Vec<DownloadBlob>,+}++/// Information about a blob available for download.+#[derive(Debug, Clone, Deserialize)]+pub struct DownloadBlob {+ /// Blob ID+ pub blob_id: String,+ /// Blob type+ pub blob_type: BlobType,+ /// Presigned download URL+ pub download_url: String,+ /// Encryption nonce (base64)+ pub encryption_nonce: String,+ /// Key version used for encryption+ pub key_version: u32,+ /// Size in bytes+ pub size_bytes: u64,+ /// Checksum for verification+ pub checksum: String,+ /// Start of time range+ pub time_start: String,+ /// End of time range+ pub time_end: String,+}++/// Request for searching blobs.+#[derive(Debug, Clone, Serialize)]+pub struct SearchRequest {+ /// Search tokens (base64 encoded HMAC tokens)+ pub search_tokens: Vec<String>,+ /// Optional time range filter+ #[serde(skip_serializing_if = "Option::is_none")]+ pub time_range: Option<TimeRange>,+ /// Optional blob type filter+ #[serde(skip_serializing_if = "Option::is_none")]+ pub blob_types: Option<Vec<BlobType>>,+ /// Maximum results+ #[serde(skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++#[derive(Debug, Deserialize)]+struct SearchApiResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ matches: Vec<SearchMatch>,+ #[serde(default)]+ total_matches: Option<u32>,+}++/// Search response.+#[derive(Debug)]+pub struct SearchResponse {+ /// Matching blobs+ pub matches: Vec<SearchMatch>,+ /// Total number of matches+ pub total_matches: u32,+}++/// A search result match.+#[derive(Debug, Clone, Deserialize)]+pub struct SearchMatch {+ /// Blob ID+ pub blob_id: String,+ /// Blob type+ pub blob_type: BlobType,+ /// Start of time range+ pub time_start: String,+ /// End of time range+ pub time_end: String,+ /// Number of matching tokens+ pub match_count: u32,+}++#[derive(Debug, Deserialize)]+struct StatusResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ quota: Option<SyncQuota>,+ #[serde(default)]+ stats: Option<SyncStats>,+ #[serde(default)]+ storage_breakdown: Option<StorageBreakdown>,+}++/// Sync status response.+#[derive(Debug)]+pub struct SyncStatus {+ /// Quota information+ pub quota: SyncQuota,+ /// Sync statistics+ pub stats: SyncStats,+ /// Storage breakdown by type+ pub storage_breakdown: Option<StorageBreakdown>,+}++/// Quota information.+#[derive(Debug, Clone, Deserialize)]+pub struct SyncQuota {+ /// Storage used in bytes+ pub storage_used: u64,+ /// Storage limit in bytes+ pub storage_limit: u64,+ /// Number of registered devices+ pub device_count: u32,+ /// Maximum allowed devices+ pub device_limit: u32,+ /// Whether sync is allowed+ pub can_sync: bool,+ /// Current sync tier+ pub sync_tier: Option<String>,+}++/// Sync statistics.+#[derive(Debug, Clone, Deserialize)]+pub struct SyncStats {+ /// Total number of blobs+ pub total_blobs: u32,+ /// Total bytes stored+ pub total_bytes: u64,+ /// Last sync timestamp+ pub last_sync_at: Option<String>,+ /// Oldest data timestamp+ pub oldest_data: Option<String>,+ /// Newest data timestamp+ pub newest_data: Option<String>,+}++/// Storage breakdown by blob type.+#[derive(Debug, Clone, Deserialize)]+pub struct StorageBreakdown {+ /// Bytes used by frames+ pub frames_bytes: u64,+ /// Bytes used by audio+ pub audio_bytes: u64,+ /// Bytes used by transcripts+ pub transcripts_bytes: u64,+ /// Bytes used by OCR+ pub ocr_bytes: u64,+}++#[derive(Debug, Deserialize)]+struct DevicesResponse {+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ devices: Vec<SyncDevice>,+}++/// A registered sync device.+#[derive(Debug, Clone, Deserialize)]+pub struct SyncDevice {+ /// Database ID+ pub id: String,+ /// Device ID+ pub device_id: String,+ /// User-friendly name+ pub device_name: Option<String>,+ /// Operating system+ pub device_os: String,+ /// Last sync timestamp+ pub last_sync_at: Option<String>,+ /// Created timestamp+ pub created_at: String,+}++#[derive(Debug, Deserialize)]+struct ApiError {+ #[allow(dead_code)]+ success: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ code: Option<String>,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_config_builder() {+ let config = SyncClientConfig::new(+ "token".to_string(),+ "device-123".to_string(),+ "My MacBook".to_string(),+ "macos".to_string(),+ )+ .with_api_url("https://custom.api.com".to_string())+ .with_app_version("1.0.0".to_string());++ assert_eq!(config.api_url, "https://custom.api.com");+ assert_eq!(config.app_version, Some("1.0.0".to_string()));+ }++ #[test]+ fn test_download_request_serialization() {+ let request = DownloadRequest {+ blob_ids: Some(vec!["blob-1".to_string()]),+ time_range: Some(TimeRange {+ start: Some("2024-01-01T00:00:00Z".to_string()),+ end: None,+ }),+ blob_types: Some(vec![BlobType::Ocr, BlobType::Transcripts]),+ limit: Some(100),+ };++ let json = serde_json::to_string(&request).unwrap();+ assert!(json.contains("blob-1"));+ assert!(json.contains("ocr"));+ }++ #[test]+ fn test_search_request_serialization() {+ let request = SearchRequest {+ search_tokens: vec!["dG9rZW4x".to_string(), "dG9rZW4y".to_string()],+ time_range: None,+ blob_types: None,+ limit: Some(50),+ };++ let json = serde_json::to_string(&request).unwrap();+ assert!(json.contains("search_tokens"));+ assert!(json.contains("dG9rZW4x"));+ }+}diff --git a/screenpipe-core/src/sync/crypto.rs b/screenpipe-core/src/sync/crypto.rsnew file mode 100644index 000000000..3216f0cc6--- /dev/null+++ b/screenpipe-core/src/sync/crypto.rs@@ -0,0 +1,302 @@+//! Cryptographic primitives for cloud sync encryption.+//!+//! This module provides the core encryption functions:+//! - Argon2id for password-based key derivation+//! - ChaCha20-Poly1305 for authenticated encryption+//! - HMAC-SHA256 for searchable encryption tokens++use argon2::{Argon2, Params, Version};+use chacha20poly1305::{+ aead::{Aead, KeyInit as AeadKeyInit},+ ChaCha20Poly1305, Nonce,+};+use hmac::{Hmac, Mac};+use rand::RngCore;+use sha2::Sha256;+use zeroize::Zeroizing;++type HmacSha256 = Hmac<Sha256>;++use super::error::{SyncError, SyncResult};++/// Size of encryption keys in bytes (256 bits)+pub const KEY_SIZE: usize = 32;++/// Size of nonces for ChaCha20-Poly1305 (96 bits)+pub const NONCE_SIZE: usize = 12;++/// Size of salt for Argon2id (128 bits recommended minimum)+pub const SALT_SIZE: usize = 32;++/// Size of HMAC-SHA256 output+pub const HMAC_SIZE: usize = 32;++/// Argon2id parameters (OWASP recommended for password hashing)+/// - Memory: 64 MB+/// - Iterations: 3+/// - Parallelism: 4+const ARGON2_MEMORY_KB: u32 = 65536; // 64 MB+const ARGON2_ITERATIONS: u32 = 3;+const ARGON2_PARALLELISM: u32 = 4;++/// Generate a cryptographically secure random salt+pub fn generate_salt() -> [u8; SALT_SIZE] {+ let mut salt = [0u8; SALT_SIZE];+ rand::thread_rng().fill_bytes(&mut salt);+ salt+}++/// Generate a cryptographically secure random nonce+pub fn generate_nonce() -> [u8; NONCE_SIZE] {+ let mut nonce = [0u8; NONCE_SIZE];+ rand::thread_rng().fill_bytes(&mut nonce);+ nonce+}++/// Generate a cryptographically secure random key+pub fn generate_key() -> Zeroizing<[u8; KEY_SIZE]> {+ let mut key = Zeroizing::new([0u8; KEY_SIZE]);+ rand::thread_rng().fill_bytes(key.as_mut());+ key+}++/// Derive a key from a password using Argon2id.+///+/// This is used to derive a key from the user's password, which then+/// decrypts the master key stored on the server.+///+/// # Arguments+/// * `password` - The user's password+/// * `salt` - A unique salt for this user (stored on server)+///+/// # Returns+/// A 256-bit derived key+pub fn derive_key_from_password(password: &str, salt: &[u8; SALT_SIZE]) -> SyncResult<Zeroizing<[u8; KEY_SIZE]>> {+ let params = Params::new(+ ARGON2_MEMORY_KB,+ ARGON2_ITERATIONS,+ ARGON2_PARALLELISM,+ Some(KEY_SIZE),+ )+ .map_err(|e| SyncError::Crypto(format!("invalid argon2 params: {}", e)))?;++ let argon2 = Argon2::new(argon2::Algorithm::Argon2id, Version::V0x13, params);++ let mut derived_key = Zeroizing::new([0u8; KEY_SIZE]);+ argon2+ .hash_password_into(password.as_bytes(), salt, derived_key.as_mut())+ .map_err(|e| SyncError::Crypto(format!("key derivation failed: {}", e)))?;++ Ok(derived_key)+}++/// Encrypt data using ChaCha20-Poly1305.+///+/// This provides authenticated encryption - the ciphertext cannot be+/// modified without detection.+///+/// # Arguments+/// * `plaintext` - The data to encrypt+/// * `key` - A 256-bit encryption key+/// * `nonce` - A unique 96-bit nonce (MUST never be reused with the same key)+///+/// # Returns+/// The ciphertext with authentication tag appended+pub fn encrypt(plaintext: &[u8], key: &[u8; KEY_SIZE], nonce: &[u8; NONCE_SIZE]) -> SyncResult<Vec<u8>> {+ let cipher = ChaCha20Poly1305::new_from_slice(key)+ .map_err(|e| SyncError::Crypto(format!("invalid key: {}", e)))?;++ let nonce = Nonce::from_slice(nonce);++ cipher+ .encrypt(nonce, plaintext)+ .map_err(|e| SyncError::Crypto(format!("encryption failed: {}", e)))+}++/// Decrypt data using ChaCha20-Poly1305.+///+/// This verifies the authentication tag and rejects tampered ciphertext.+///+/// # Arguments+/// * `ciphertext` - The encrypted data with authentication tag+/// * `key` - The 256-bit encryption key used for encryption+/// * `nonce` - The nonce used during encryption+///+/// # Returns+/// The decrypted plaintext, or an error if authentication fails+pub fn decrypt(ciphertext: &[u8], key: &[u8; KEY_SIZE], nonce: &[u8; NONCE_SIZE]) -> SyncResult<Vec<u8>> {+ let cipher = ChaCha20Poly1305::new_from_slice(key)+ .map_err(|e| SyncError::Crypto(format!("invalid key: {}", e)))?;++ let nonce = Nonce::from_slice(nonce);++ cipher+ .decrypt(nonce, ciphertext)+ .map_err(|e| SyncError::Crypto(format!("decryption failed (authentication error): {}", e)))+}++/// Generate an HMAC-SHA256 token for searchable encryption.+///+/// This creates a deterministic, one-way token from a keyword. The same+/// keyword with the same key always produces the same token, enabling+/// server-side search without revealing the keyword.+///+/// # Arguments+/// * `keyword` - The keyword to tokenize (will be normalized to lowercase)+/// * `key` - The search key (derived from master key)+///+/// # Returns+/// A 256-bit HMAC token+pub fn generate_search_token(keyword: &str, key: &[u8; KEY_SIZE]) -> SyncResult<[u8; HMAC_SIZE]> {+ // Normalize: lowercase and trim+ let normalized = keyword.to_lowercase().trim().to_string();++ let mut mac = <HmacSha256 as Mac>::new_from_slice(key)+ .map_err(|e| SyncError::Crypto(format!("invalid hmac key: {}", e)))?;++ mac.update(normalized.as_bytes());++ let result = mac.finalize();+ let bytes = result.into_bytes();++ let mut token = [0u8; HMAC_SIZE];+ token.copy_from_slice(&bytes);++ Ok(token)+}++/// Generate search tokens from text by extracting and tokenizing keywords.+///+/// This extracts unique words from the text and generates HMAC tokens for each.+/// Used when uploading data to build the searchable index.+///+/// # Arguments+/// * `text` - The text to extract keywords from+/// * `key` - The search key+///+/// # Returns+/// A list of unique HMAC tokens+pub fn generate_search_tokens_from_text(text: &str, key: &[u8; KEY_SIZE]) -> SyncResult<Vec<[u8; HMAC_SIZE]>> {+ let keywords = extract_keywords(text);+ let mut tokens = Vec::with_capacity(keywords.len());++ for keyword in keywords {+ tokens.push(generate_search_token(&keyword, key)?);+ }++ Ok(tokens)+}++/// Extract searchable keywords from text.+///+/// This performs basic tokenization:+/// - Split on whitespace and punctuation+/// - Normalize to lowercase+/// - Filter out very short words (< 3 chars)+/// - Deduplicate+fn extract_keywords(text: &str) -> Vec<String> {+ let mut keywords: Vec<String> = text+ .split(|c: char| c.is_whitespace() || c.is_ascii_punctuation())+ .map(|s| s.to_lowercase())+ .filter(|s| s.len() >= 3) // Skip very short words+ .collect();++ keywords.sort();+ keywords.dedup();+ keywords+}++/// Compute SHA-256 checksum of data.+///+/// Used to verify data integrity after decryption.+pub fn compute_checksum(data: &[u8]) -> String {+ use sha2::{Digest, Sha256};+ let mut hasher = Sha256::new();+ hasher.update(data);+ let result = hasher.finalize();+ hex::encode(result)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_key_derivation() {+ let password = "test-password-123";+ let salt = generate_salt();++ let key1 = derive_key_from_password(password, &salt).unwrap();+ let key2 = derive_key_from_password(password, &salt).unwrap();++ // Same password + salt should produce same key+ assert_eq!(key1.as_ref(), key2.as_ref());++ // Different salt should produce different key+ let different_salt = generate_salt();+ let key3 = derive_key_from_password(password, &different_salt).unwrap();+ assert_ne!(key1.as_ref(), key3.as_ref());+ }++ #[test]+ fn test_encrypt_decrypt() {+ let key = generate_key();+ let nonce = generate_nonce();+ let plaintext = b"Hello, World! This is a test message.";++ let ciphertext = encrypt(plaintext, &key, &nonce).unwrap();+ assert_ne!(ciphertext, plaintext);++ let decrypted = decrypt(&ciphertext, &key, &nonce).unwrap();+ assert_eq!(decrypted, plaintext);+ }++ #[test]+ fn test_tampered_ciphertext_fails() {+ let key = generate_key();+ let nonce = generate_nonce();+ let plaintext = b"Secret message";++ let mut ciphertext = encrypt(plaintext, &key, &nonce).unwrap();++ // Tamper with the ciphertext+ ciphertext[0] ^= 0xFF;++ // Decryption should fail+ let result = decrypt(&ciphertext, &key, &nonce);+ assert!(result.is_err());+ }++ #[test]+ fn test_search_tokens() {+ let key = generate_key();++ // Same keyword produces same token+ let token1 = generate_search_token("meeting", &key).unwrap();+ let token2 = generate_search_token("meeting", &key).unwrap();+ assert_eq!(token1, token2);++ // Case insensitive+ let token3 = generate_search_token("MEETING", &key).unwrap();+ assert_eq!(token1, token3);++ // Different keyword produces different token+ let token4 = generate_search_token("project", &key).unwrap();+ assert_ne!(token1, token4);+ }++ #[test]+ fn test_extract_keywords() {+ let text = "Hello World! This is a test. Testing, one, two, three.";+ let keywords = extract_keywords(text);++ assert!(keywords.contains(&"hello".to_string()));+ assert!(keywords.contains(&"world".to_string()));+ assert!(keywords.contains(&"test".to_string()));+ assert!(keywords.contains(&"testing".to_string()));++ // Short words should be filtered+ assert!(!keywords.contains(&"is".to_string()));+ assert!(!keywords.contains(&"a".to_string()));+ }+}diff --git a/screenpipe-core/src/sync/error.rs b/screenpipe-core/src/sync/error.rsnew file mode 100644index 000000000..28137b606--- /dev/null+++ b/screenpipe-core/src/sync/error.rs@@ -0,0 +1,80 @@+//! Error types for cloud sync operations.++use thiserror::Error;++/// Result type for sync operations.+pub type SyncResult<T> = Result<T, SyncError>;++/// Errors that can occur during sync operations.+#[derive(Error, Debug)]+pub enum SyncError {+ /// Cryptographic operation failed+ #[error("crypto error: {0}")]+ Crypto(String),++ /// Key management error+ #[error("key error: {0}")]+ Key(String),++ /// Network/API error+ #[error("network error: {0}")]+ Network(String),++ /// Authentication failed+ #[error("authentication failed: {0}")]+ Auth(String),++ /// Server returned an error+ #[error("server error: {0}")]+ Server(String),++ /// Data serialization/deserialization error+ #[error("serialization error: {0}")]+ Serialization(String),++ /// Invalid or corrupted data+ #[error("data corruption: {0}")]+ DataCorruption(String),++ /// Quota exceeded+ #[error("quota exceeded: {0}")]+ QuotaExceeded(String),++ /// Device limit exceeded+ #[error("device limit exceeded")]+ DeviceLimitExceeded,++ /// No active subscription+ #[error("no active sync subscription")]+ NoSubscription,++ /// Blob not found+ #[error("blob not found: {0}")]+ NotFound(String),++ /// IO error+ #[error("io error: {0}")]+ Io(#[from] std::io::Error),++ /// Database/storage error+ #[error("database error: {0}")]+ Database(String),+}++impl From<reqwest::Error> for SyncError {+ fn from(err: reqwest::Error) -> Self {+ SyncError::Network(err.to_string())+ }+}++impl From<serde_json::Error> for SyncError {+ fn from(err: serde_json::Error) -> Self {+ SyncError::Serialization(err.to_string())+ }+}++impl From<base64::DecodeError> for SyncError {+ fn from(err: base64::DecodeError) -> Self {+ SyncError::Serialization(format!("base64 decode error: {}", err))+ }+}diff --git a/screenpipe-core/src/sync/keys.rs b/screenpipe-core/src/sync/keys.rsnew file mode 100644index 000000000..f1f66ded1--- /dev/null+++ b/screenpipe-core/src/sync/keys.rs@@ -0,0 +1,299 @@+//! Key management for cloud sync encryption.+//!+//! This module handles the key hierarchy:+//! - Master Key: The root key, encrypted with password-derived key+//! - Data Key: Derived from master key, used to encrypt blobs+//! - Search Key: Derived from master key, used for HMAC search tokens++use base64::{engine::general_purpose::STANDARD as BASE64, Engine};+use serde::{Deserialize, Serialize};+use zeroize::Zeroize;++use super::crypto::{+ decrypt, derive_key_from_password, encrypt, generate_key, generate_nonce, generate_salt,+ KEY_SIZE, NONCE_SIZE, SALT_SIZE,+};+use super::error::{SyncError, SyncResult};++/// Domain separation constants for key derivation+const DATA_KEY_DOMAIN: &[u8] = b"screenpipe-sync-data-key-v1";+const SEARCH_KEY_DOMAIN: &[u8] = b"screenpipe-sync-search-key-v1";++/// The complete set of keys needed for sync operations.+///+/// These keys are derived from the master key and held in memory+/// during sync operations. They are zeroized when dropped.+#[derive(Zeroize)]+#[zeroize(drop)]+pub struct SyncKeys {+ /// The decrypted master key (never leaves the device)+ master_key: [u8; KEY_SIZE],+ /// Key for encrypting/decrypting data blobs+ data_key: [u8; KEY_SIZE],+ /// Key for generating HMAC search tokens+ search_key: [u8; KEY_SIZE],+ /// Current key version (for rotation support)+ key_version: u32,+}++impl SyncKeys {+ /// Derive sub-keys from the master key.+ fn derive_subkeys(master_key: &[u8; KEY_SIZE]) -> ([u8; KEY_SIZE], [u8; KEY_SIZE]) {+ use hmac::{Hmac, Mac};+ use sha2::Sha256;++ type HmacSha256 = Hmac<Sha256>;++ // Derive data key+ let mut mac = <HmacSha256 as Mac>::new_from_slice(master_key).unwrap();+ mac.update(DATA_KEY_DOMAIN);+ let data_key_bytes = mac.finalize().into_bytes();+ let mut data_key = [0u8; KEY_SIZE];+ data_key.copy_from_slice(&data_key_bytes);++ // Derive search key+ let mut mac = <HmacSha256 as Mac>::new_from_slice(master_key).unwrap();+ mac.update(SEARCH_KEY_DOMAIN);+ let search_key_bytes = mac.finalize().into_bytes();+ let mut search_key = [0u8; KEY_SIZE];+ search_key.copy_from_slice(&search_key_bytes);++ (data_key, search_key)+ }++ /// Create SyncKeys from a decrypted master key.+ pub fn from_master_key(master_key: [u8; KEY_SIZE], key_version: u32) -> Self {+ let (data_key, search_key) = Self::derive_subkeys(&master_key);++ Self {+ master_key,+ data_key,+ search_key,+ key_version,+ }+ }++ /// Decrypt master key from server response and derive all keys.+ ///+ /// # Arguments+ /// * `password` - The user's password+ /// * `encrypted_master_key` - The encrypted master key from the server+ /// * `salt` - The salt used for password derivation+ /// * `nonce` - The nonce used for master key encryption+ /// * `key_version` - The key version number+ pub fn from_password(+ password: &str,+ encrypted_master_key: &[u8],+ salt: &[u8; SALT_SIZE],+ nonce: &[u8; NONCE_SIZE],+ key_version: u32,+ ) -> SyncResult<Self> {+ // Derive password key+ let password_key = derive_key_from_password(password, salt)?;++ // Decrypt master key+ let master_key_bytes = decrypt(encrypted_master_key, &password_key, nonce)?;++ if master_key_bytes.len() != KEY_SIZE {+ return Err(SyncError::Key(format!(+ "invalid master key length: expected {}, got {}",+ KEY_SIZE,+ master_key_bytes.len()+ )));+ }++ let mut master_key = [0u8; KEY_SIZE];+ master_key.copy_from_slice(&master_key_bytes);++ Ok(Self::from_master_key(master_key, key_version))+ }++ /// Get the data encryption key.+ pub fn data_key(&self) -> &[u8; KEY_SIZE] {+ &self.data_key+ }++ /// Get the search token key.+ pub fn search_key(&self) -> &[u8; KEY_SIZE] {+ &self.search_key+ }++ /// Get the current key version.+ pub fn key_version(&self) -> u32 {+ self.key_version+ }+}++/// Data needed to initialize sync for a new user.+///+/// This is generated on the client and sent to the server.+/// The server stores the encrypted master key but cannot decrypt it.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NewUserKeyData {+ /// Salt for password key derivation+ pub salt: String, // base64+ /// Encrypted master key (encrypted with password-derived key)+ pub encrypted_master_key: String, // base64+ /// Nonce used for master key encryption+ pub master_key_nonce: String, // base64+}++impl NewUserKeyData {+ /// Generate new key data for a new user.+ ///+ /// This creates a new random master key, encrypts it with a key+ /// derived from the user's password, and returns the data needed+ /// to store on the server.+ ///+ /// # Arguments+ /// * `password` - The user's chosen password+ ///+ /// # Returns+ /// A tuple of (NewUserKeyData, SyncKeys) - the data to send to server+ /// and the keys to use for encryption.+ pub fn generate(password: &str) -> SyncResult<(Self, SyncKeys)> {+ // Generate random salt and master key+ let salt = generate_salt();+ let master_key = generate_key();+ let nonce = generate_nonce();++ // Derive password key+ let password_key = derive_key_from_password(password, &salt)?;++ // Encrypt master key with password key+ let encrypted_master_key = encrypt(master_key.as_ref(), &password_key, &nonce)?;++ // Create the data to send to server+ let key_data = Self {+ salt: BASE64.encode(salt),+ encrypted_master_key: BASE64.encode(&encrypted_master_key),+ master_key_nonce: BASE64.encode(nonce),+ };++ // Create SyncKeys from the master key+ let mut master_key_array = [0u8; KEY_SIZE];+ master_key_array.copy_from_slice(master_key.as_ref());+ let sync_keys = SyncKeys::from_master_key(master_key_array, 1);++ Ok((key_data, sync_keys))+ }+}++/// Key data returned from the server for an existing user.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ExistingUserKeyData {+ /// Salt for password key derivation+ pub salt: String, // base64+ /// Encrypted master key+ pub encrypted_master_key: String, // base64+ /// Nonce used for master key encryption+ pub master_key_nonce: String, // base64+ /// Key derivation algorithm (should be "argon2id")+ pub kdf_algorithm: String,+ /// Key derivation iterations+ pub kdf_iterations: u32,+ /// Key derivation memory (KB)+ pub kdf_memory: u32,+ /// Current key version+ pub key_version: u32,+}++impl ExistingUserKeyData {+ /// Decrypt and derive keys from this key data.+ pub fn derive_keys(&self, password: &str) -> SyncResult<SyncKeys> {+ // Decode base64 fields+ let salt_bytes = BASE64.decode(&self.salt)?;+ let encrypted_master_key = BASE64.decode(&self.encrypted_master_key)?;+ let nonce_bytes = BASE64.decode(&self.master_key_nonce)?;++ // Validate sizes+ if salt_bytes.len() != SALT_SIZE {+ return Err(SyncError::Key(format!(+ "invalid salt length: expected {}, got {}",+ SALT_SIZE,+ salt_bytes.len()+ )));+ }+ if nonce_bytes.len() != NONCE_SIZE {+ return Err(SyncError::Key(format!(+ "invalid nonce length: expected {}, got {}",+ NONCE_SIZE,+ nonce_bytes.len()+ )));+ }++ let mut salt = [0u8; SALT_SIZE];+ salt.copy_from_slice(&salt_bytes);++ let mut nonce = [0u8; NONCE_SIZE];+ nonce.copy_from_slice(&nonce_bytes);++ SyncKeys::from_password(+ password,+ &encrypted_master_key,+ &salt,+ &nonce,+ self.key_version,+ )+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_new_user_key_generation() {+ let password = "test-password-123";++ let (key_data, keys) = NewUserKeyData::generate(password).unwrap();++ // Verify we can recover the keys with the same password+ let existing = ExistingUserKeyData {+ salt: key_data.salt.clone(),+ encrypted_master_key: key_data.encrypted_master_key.clone(),+ master_key_nonce: key_data.master_key_nonce.clone(),+ kdf_algorithm: "argon2id".to_string(),+ kdf_iterations: 3,+ kdf_memory: 65536,+ key_version: 1,+ };++ let recovered_keys = existing.derive_keys(password).unwrap();++ // Data keys should match+ assert_eq!(keys.data_key(), recovered_keys.data_key());+ assert_eq!(keys.search_key(), recovered_keys.search_key());+ }++ #[test]+ fn test_wrong_password_fails() {+ let password = "correct-password";+ let wrong_password = "wrong-password";++ let (key_data, _keys) = NewUserKeyData::generate(password).unwrap();++ let existing = ExistingUserKeyData {+ salt: key_data.salt,+ encrypted_master_key: key_data.encrypted_master_key,+ master_key_nonce: key_data.master_key_nonce,+ kdf_algorithm: "argon2id".to_string(),+ kdf_iterations: 3,+ kdf_memory: 65536,+ key_version: 1,+ };++ // Should fail with wrong password+ let result = existing.derive_keys(wrong_password);+ assert!(result.is_err());+ }++ #[test]+ fn test_subkeys_are_different() {+ let password = "test-password";+ let (_key_data, keys) = NewUserKeyData::generate(password).unwrap();++ // Data key and search key should be different+ assert_ne!(keys.data_key(), keys.search_key());+ }+}diff --git a/screenpipe-core/src/sync/manager.rs b/screenpipe-core/src/sync/manager.rsnew file mode 100644index 000000000..a0acbf113--- /dev/null+++ b/screenpipe-core/src/sync/manager.rs@@ -0,0 +1,358 @@+//! High-level sync manager for coordinating sync operations.+//!+//! This module provides a simple interface for common sync operations,+//! handling the encryption/decryption and API communication internally.++use std::sync::Arc;+use tokio::sync::RwLock;++use super::blob::{decrypt_blob, encrypt_blob, BlobMetadata, BlobType, DecryptedBlob};+use super::client::{+ DownloadBlob, DownloadRequest, SearchRequest, SyncClient, SyncClientConfig, SyncDevice,+ SyncStatus, TimeRange,+};+use super::crypto::generate_search_token;+use super::error::{SyncError, SyncResult};+use super::keys::SyncKeys;++/// High-level manager for sync operations.+///+/// This struct holds the sync client and encryption keys, providing+/// a simple interface for uploading, downloading, and searching data.+pub struct SyncManager {+ client: SyncClient,+ keys: Arc<RwLock<Option<SyncKeys>>>,+}++impl SyncManager {+ /// Create a new sync manager.+ pub fn new(config: SyncClientConfig) -> SyncResult<Self> {+ let client = SyncClient::new(config)?;+ Ok(Self {+ client,+ keys: Arc::new(RwLock::new(None)),+ })+ }++ /// Check if the manager is initialized (has keys).+ pub async fn is_initialized(&self) -> bool {+ self.keys.read().await.is_some()+ }++ /// Initialize sync with the user's password.+ ///+ /// This will either create new encryption keys (for new users) or+ /// derive keys from the server's stored encrypted master key.+ ///+ /// Returns true if this is a new user, false if existing.+ pub async fn initialize(&self, password: &str) -> SyncResult<bool> {+ let (keys, is_new) = self.client.init(password).await?;+ *self.keys.write().await = Some(keys);+ Ok(is_new)+ }++ /// Lock the manager (clear keys from memory).+ ///+ /// Call this when the user logs out or the app is locked.+ pub async fn lock(&self) {+ *self.keys.write().await = None;+ }++ /// Get a reference to the keys, or error if not initialized.+ async fn require_keys(&self) -> SyncResult<tokio::sync::RwLockReadGuard<'_, Option<SyncKeys>>> {+ let guard = self.keys.read().await;+ if guard.is_none() {+ return Err(SyncError::Key("sync not initialized".to_string()));+ }+ Ok(guard)+ }++ // =========================================================================+ // Upload Operations+ // =========================================================================++ /// Upload data to the cloud.+ ///+ /// This encrypts the data locally and uploads it to S3.+ ///+ /// # Arguments+ /// * `data` - The plaintext data to upload+ /// * `blob_type` - The type of data+ /// * `time_start` - Start of time range (ISO 8601)+ /// * `time_end` - End of time range (ISO 8601)+ /// * `text_content` - Optional text for search indexing+ ///+ /// # Returns+ /// The blob ID and updated storage usage+ pub async fn upload(+ &self,+ data: &[u8],+ blob_type: BlobType,+ time_start: &str,+ time_end: &str,+ text_content: Option<&str>,+ ) -> SyncResult<UploadResult> {+ let keys_guard = self.require_keys().await?;+ let keys = keys_guard.as_ref().unwrap();++ // Encrypt the data+ let encrypted = encrypt_blob(data, blob_type, keys, text_content)?;++ // Create metadata+ let metadata = BlobMetadata::from_encrypted_blob(+ &encrypted,+ time_start,+ time_end,+ keys.key_version(),+ );++ // Request upload URL+ let upload_info = self.client.request_upload(&metadata).await?;++ // Upload to S3+ self.client+ .upload_to_s3(&upload_info.upload_url, &encrypted.ciphertext)+ .await?;++ // Mark upload complete+ let complete = self.client.complete_upload(&upload_info.blob_id).await?;++ Ok(UploadResult {+ blob_id: upload_info.blob_id,+ storage_used: complete.storage_used,+ storage_limit: complete.storage_limit,+ })+ }++ // =========================================================================+ // Download Operations+ // =========================================================================++ /// Download and decrypt blobs by ID.+ pub async fn download_by_ids(&self, blob_ids: Vec<String>) -> SyncResult<Vec<DecryptedBlob>> {+ let keys_guard = self.require_keys().await?;+ let keys = keys_guard.as_ref().unwrap();++ let request = DownloadRequest {+ blob_ids: Some(blob_ids),+ time_range: None,+ blob_types: None,+ limit: None,+ };++ let blobs = self.client.get_download_urls(request).await?;+ self.download_and_decrypt_blobs(&blobs, keys).await+ }++ /// Download and decrypt blobs by time range.+ pub async fn download_by_time_range(+ &self,+ start: Option<String>,+ end: Option<String>,+ blob_types: Option<Vec<BlobType>>,+ limit: Option<u32>,+ ) -> SyncResult<Vec<DecryptedBlob>> {+ let keys_guard = self.require_keys().await?;+ let keys = keys_guard.as_ref().unwrap();++ let request = DownloadRequest {+ blob_ids: None,+ time_range: Some(TimeRange { start, end }),+ blob_types,+ limit,+ };++ let blobs = self.client.get_download_urls(request).await?;+ self.download_and_decrypt_blobs(&blobs, keys).await+ }++ async fn download_and_decrypt_blobs(+ &self,+ blobs: &[DownloadBlob],+ keys: &SyncKeys,+ ) -> SyncResult<Vec<DecryptedBlob>> {+ let mut results = Vec::with_capacity(blobs.len());++ for blob in blobs {+ // Download from S3+ let ciphertext = self.client.download_from_s3(&blob.download_url).await?;++ // Decrypt+ let decrypted = decrypt_blob(+ &ciphertext,+ &blob.encryption_nonce,+ Some(&blob.checksum),+ blob.blob_type,+ keys,+ )?;++ results.push(decrypted);+ }++ Ok(results)+ }++ // =========================================================================+ // Search Operations+ // =========================================================================++ /// Search for blobs containing the given keywords.+ ///+ /// This generates search tokens from the keywords and searches the+ /// encrypted index on the server.+ pub async fn search(+ &self,+ keywords: &[&str],+ time_range: Option<TimeRange>,+ blob_types: Option<Vec<BlobType>>,+ limit: Option<u32>,+ ) -> SyncResult<SearchResult> {+ let keys_guard = self.require_keys().await?;+ let keys = keys_guard.as_ref().unwrap();++ // Generate search tokens+ let mut tokens = Vec::with_capacity(keywords.len());+ for keyword in keywords {+ let token = generate_search_token(keyword, keys.search_key())?;+ tokens.push(base64::engine::general_purpose::STANDARD.encode(token));+ }++ use base64::Engine;++ let request = SearchRequest {+ search_tokens: tokens,+ time_range,+ blob_types,+ limit,+ };++ let response = self.client.search(request).await?;++ Ok(SearchResult {+ blob_ids: response.matches.iter().map(|m| m.blob_id.clone()).collect(),+ matches: response.matches.into_iter().map(|m| SearchMatchInfo {+ blob_id: m.blob_id,+ blob_type: m.blob_type,+ time_start: m.time_start,+ time_end: m.time_end,+ match_count: m.match_count,+ }).collect(),+ total: response.total_matches,+ })+ }++ /// Search and download matching blobs.+ ///+ /// Convenience method that combines search + download.+ pub async fn search_and_download(+ &self,+ keywords: &[&str],+ time_range: Option<TimeRange>,+ blob_types: Option<Vec<BlobType>>,+ limit: Option<u32>,+ ) -> SyncResult<Vec<DecryptedBlob>> {+ let search_result = self.search(keywords, time_range, blob_types, limit).await?;++ if search_result.blob_ids.is_empty() {+ return Ok(Vec::new());+ }++ self.download_by_ids(search_result.blob_ids).await+ }++ // =========================================================================+ // Status Operations+ // =========================================================================++ /// Get sync status and quota information.+ pub async fn get_status(&self) -> SyncResult<SyncStatus> {+ self.client.get_status().await+ }++ // =========================================================================+ // Device Operations+ // =========================================================================++ /// Get list of registered devices.+ pub async fn get_devices(&self) -> SyncResult<Vec<SyncDevice>> {+ self.client.list_devices().await+ }++ /// Remove a device from sync.+ pub async fn remove_device(&self, device_id: &str) -> SyncResult<()> {+ self.client.remove_device(device_id).await+ }++ /// Delete all cloud data for this user.+ pub async fn delete_all_data(&self) -> SyncResult<()> {+ self.client.delete_all_data().await+ }++ /// Get the client for advanced operations.+ pub fn client(&self) -> &SyncClient {+ &self.client+ }+}++/// Result of an upload operation.+#[derive(Debug)]+pub struct UploadResult {+ /// The blob ID assigned by the server+ pub blob_id: String,+ /// Current storage used in bytes+ pub storage_used: u64,+ /// Storage limit in bytes+ pub storage_limit: u64,+}++/// Result of a search operation.+#[derive(Debug)]+pub struct SearchResult {+ /// Matching blob IDs+ pub blob_ids: Vec<String>,+ /// Detailed match information+ pub matches: Vec<SearchMatchInfo>,+ /// Total number of matches+ pub total: u32,+}++/// Information about a search match.+#[derive(Debug)]+pub struct SearchMatchInfo {+ /// Blob ID+ pub blob_id: String,+ /// Blob type+ pub blob_type: BlobType,+ /// Start of time range+ pub time_start: String,+ /// End of time range+ pub time_end: String,+ /// Number of matching tokens+ pub match_count: u32,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_upload_result() {+ let result = UploadResult {+ blob_id: "blob-123".to_string(),+ storage_used: 1024,+ storage_limit: 1024 * 1024,+ };+ assert_eq!(result.blob_id, "blob-123");+ }++ #[test]+ fn test_search_result() {+ let result = SearchResult {+ blob_ids: vec!["blob-1".to_string(), "blob-2".to_string()],+ matches: vec![],+ total: 2,+ };+ assert_eq!(result.blob_ids.len(), 2);+ assert_eq!(result.total, 2);+ }+}diff --git a/screenpipe-core/src/sync/mod.rs b/screenpipe-core/src/sync/mod.rsnew file mode 100644index 000000000..6b6c22558--- /dev/null+++ b/screenpipe-core/src/sync/mod.rs@@ -0,0 +1,113 @@+//! Cloud sync module for Screenpipe.+//!+//! This module provides end-to-end encrypted cloud sync functionality:+//!+//! - **Zero-knowledge encryption**: All data is encrypted on-device before upload.+//! The server never sees plaintext data.+//!+//! - **Searchable encryption**: HMAC-based tokens enable server-side search+//! without revealing the search terms.+//!+//! - **Multi-device sync**: Encrypted data can be synced across multiple devices.+//!+//! ## Key Hierarchy+//!+//! ```text+//! Password + Salt β Argon2id β Password Key+//! β+//! Decrypts Encrypted Master Key+//! β+//! Master Key+//! βββββββββββββββ΄ββββββββββββββ+//! β β+//! Data Key Search Key+//! (ChaCha20-Poly1305) (HMAC-SHA256)+//! ```+//!+//! ## Usage+//!+//! ### New User Setup+//!+//! ```rust,ignore+//! use screenpipe_core::sync::{NewUserKeyData, SyncKeys};+//!+//! // Generate keys for a new user+//! let (key_data, keys) = NewUserKeyData::generate("user-password")?;+//!+//! // Send key_data to server (encrypted master key, salt, nonce)+//! // Server stores this but cannot decrypt the master key+//! ```+//!+//! ### Existing User Login+//!+//! ```rust,ignore+//! use screenpipe_core::sync::{ExistingUserKeyData, SyncKeys};+//!+//! // Receive key data from server+//! let key_data: ExistingUserKeyData = fetch_from_server();+//!+//! // Derive keys from password+//! let keys = key_data.derive_keys("user-password")?;+//! ```+//!+//! ### Encrypting Data+//!+//! ```rust,ignore+//! use screenpipe_core::sync::{encrypt_blob, BlobType};+//!+//! // Encrypt OCR text+//! let text = "Meeting notes from today...";+//! let blob = encrypt_blob(+//! text.as_bytes(),+//! BlobType::Ocr,+//! &keys,+//! Some(text), // Include text for search token generation+//! )?;+//!+//! // Upload blob.ciphertext to S3+//! // Store blob metadata (nonce, checksum, tokens) on server+//! ```+//!+//! ### Decrypting Data+//!+//! ```rust,ignore+//! use screenpipe_core::sync::decrypt_blob;+//!+//! // Download ciphertext from S3+//! let decrypted = decrypt_blob(+//! &ciphertext,+//! &nonce_base64,+//! Some(&checksum),+//! BlobType::Ocr,+//! &keys,+//! )?;+//!+//! let text = String::from_utf8(decrypted.data)?;+//! ```++pub mod blob;+pub mod client;+pub mod crypto;+pub mod error;+pub mod keys;+pub mod manager;+pub mod service;++// Re-exports for convenient access+pub use blob::{decrypt_blob, encrypt_blob, BlobMetadata, BlobType, DecryptedBlob, EncryptedBlob};+pub use client::{+ DownloadBlob, DownloadRequest, SearchMatch, SearchRequest, SearchResponse, StorageBreakdown,+ SyncClient, SyncClientConfig, SyncDevice, SyncQuota, SyncStats, SyncStatus, TimeRange,+ UploadCompleteResponse, UploadUrlResponse,+};+pub use crypto::{+ compute_checksum, generate_nonce, generate_salt, generate_search_token,+ generate_search_tokens_from_text, HMAC_SIZE, KEY_SIZE, NONCE_SIZE, SALT_SIZE,+};+pub use error::{SyncError, SyncResult};+pub use keys::{ExistingUserKeyData, NewUserKeyData, SyncKeys};+pub use manager::{SearchMatchInfo, SearchResult, SyncManager, UploadResult};+pub use service::{+ PendingBlob, SyncCommand, SyncDataProvider, SyncEvent, SyncReport, SyncService,+ SyncServiceConfig, SyncServiceHandle,+};diff --git a/screenpipe-core/src/sync/service.rs b/screenpipe-core/src/sync/service.rsnew file mode 100644index 000000000..3c9e055f4--- /dev/null+++ b/screenpipe-core/src/sync/service.rs@@ -0,0 +1,388 @@+//! Background sync service for automatic data synchronization.+//!+//! This module provides a background service that periodically syncs+//! local data to the cloud.++use std::sync::Arc;+use std::time::Duration;+use tokio::sync::{mpsc, RwLock};+use tokio::time::interval;++use super::blob::BlobType;+use super::error::{SyncError, SyncResult};+use super::manager::SyncManager;++/// Configuration for the sync service.+#[derive(Debug, Clone)]+pub struct SyncServiceConfig {+ /// Whether sync is enabled+ pub enabled: bool,+ /// Interval between sync attempts (in seconds)+ pub sync_interval_secs: u64,+ /// Types of data to sync+ pub sync_types: Vec<BlobType>,+ /// Maximum blobs to upload per sync cycle+ pub max_blobs_per_cycle: usize,+ /// Whether to sync on startup+ pub sync_on_startup: bool,+}++impl Default for SyncServiceConfig {+ fn default() -> Self {+ Self {+ enabled: true,+ sync_interval_secs: 300, // 5 minutes+ sync_types: vec![BlobType::Transcripts, BlobType::Ocr],+ max_blobs_per_cycle: 10,+ sync_on_startup: true,+ }+ }+}++/// Events emitted by the sync service.+#[derive(Debug, Clone)]+pub enum SyncEvent {+ /// Sync cycle started+ Started,+ /// Sync cycle completed successfully+ Completed(SyncReport),+ /// Sync cycle failed+ Failed(String),+ /// Upload progress+ Progress {+ uploaded: usize,+ total: usize,+ bytes_transferred: u64,+ },+ /// Service stopped+ Stopped,+}++/// Report of a completed sync cycle.+#[derive(Debug, Clone)]+pub struct SyncReport {+ /// Number of blobs uploaded+ pub blobs_uploaded: usize,+ /// Total bytes uploaded+ pub bytes_uploaded: u64,+ /// Number of blobs that failed+ pub blobs_failed: usize,+ /// Duration of the sync cycle+ pub duration_secs: f64,+ /// Current storage used+ pub storage_used: u64,+ /// Storage limit+ pub storage_limit: u64,+}++/// Commands for controlling the sync service.+#[derive(Debug)]+pub enum SyncCommand {+ /// Trigger an immediate sync+ SyncNow,+ /// Pause syncing+ Pause,+ /// Resume syncing+ Resume,+ /// Update configuration+ UpdateConfig(SyncServiceConfig),+ /// Stop the service+ Stop,+}++/// Handle for controlling a running sync service.+pub struct SyncServiceHandle {+ command_tx: mpsc::Sender<SyncCommand>,+}++impl SyncServiceHandle {+ /// Trigger an immediate sync.+ pub async fn sync_now(&self) -> SyncResult<()> {+ self.command_tx+ .send(SyncCommand::SyncNow)+ .await+ .map_err(|_| SyncError::Server("sync service not running".to_string()))+ }++ /// Pause syncing.+ pub async fn pause(&self) -> SyncResult<()> {+ self.command_tx+ .send(SyncCommand::Pause)+ .await+ .map_err(|_| SyncError::Server("sync service not running".to_string()))+ }++ /// Resume syncing.+ pub async fn resume(&self) -> SyncResult<()> {+ self.command_tx+ .send(SyncCommand::Resume)+ .await+ .map_err(|_| SyncError::Server("sync service not running".to_string()))+ }++ /// Update configuration.+ pub async fn update_config(&self, config: SyncServiceConfig) -> SyncResult<()> {+ self.command_tx+ .send(SyncCommand::UpdateConfig(config))+ .await+ .map_err(|_| SyncError::Server("sync service not running".to_string()))+ }++ /// Stop the service.+ pub async fn stop(&self) -> SyncResult<()> {+ self.command_tx+ .send(SyncCommand::Stop)+ .await+ .map_err(|_| SyncError::Server("sync service not running".to_string()))+ }+}++/// Trait for providing data to sync.+///+/// Implement this trait to provide data from your local database+/// that should be synced to the cloud.+#[async_trait::async_trait]+pub trait SyncDataProvider: Send + Sync {+ /// Get unsync'd data for the given blob type.+ ///+ /// Returns a list of (data, time_start, time_end, text_content) tuples.+ async fn get_pending_data(+ &self,+ blob_type: BlobType,+ limit: usize,+ ) -> SyncResult<Vec<PendingBlob>>;++ /// Mark data as synced.+ async fn mark_synced(&self, blob_type: BlobType, time_start: &str, time_end: &str, blob_id: &str) -> SyncResult<()>;+}++/// Data pending sync.+#[derive(Debug)]+pub struct PendingBlob {+ /// The data to upload+ pub data: Vec<u8>,+ /// Start of time range+ pub time_start: String,+ /// End of time range+ pub time_end: String,+ /// Optional text content for search indexing+ pub text_content: Option<String>,+}++/// The background sync service.+pub struct SyncService {+ manager: Arc<SyncManager>,+ config: Arc<RwLock<SyncServiceConfig>>,+ data_provider: Arc<dyn SyncDataProvider>,+ paused: Arc<RwLock<bool>>,+}++impl SyncService {+ /// Create a new sync service.+ pub fn new(+ manager: Arc<SyncManager>,+ config: SyncServiceConfig,+ data_provider: Arc<dyn SyncDataProvider>,+ ) -> Self {+ Self {+ manager,+ config: Arc::new(RwLock::new(config)),+ data_provider,+ paused: Arc::new(RwLock::new(false)),+ }+ }++ /// Start the background sync service.+ ///+ /// Returns a handle for controlling the service and a receiver for events.+ pub fn start(self) -> (SyncServiceHandle, mpsc::Receiver<SyncEvent>) {+ let (command_tx, command_rx) = mpsc::channel(16);+ let (event_tx, event_rx) = mpsc::channel(64);++ let handle = SyncServiceHandle { command_tx };++ // Spawn the background task+ tokio::spawn(self.run(command_rx, event_tx));++ (handle, event_rx)+ }++ async fn run(+ self,+ mut command_rx: mpsc::Receiver<SyncCommand>,+ event_tx: mpsc::Sender<SyncEvent>,+ ) {+ let config = self.config.read().await.clone();+ let mut sync_interval = interval(Duration::from_secs(config.sync_interval_secs));++ // Sync on startup if configured+ if config.sync_on_startup && config.enabled {+ if let Err(e) = self.run_sync_cycle(&event_tx).await {+ let _ = event_tx.send(SyncEvent::Failed(e.to_string())).await;+ }+ }++ loop {+ tokio::select! {+ _ = sync_interval.tick() => {+ let config = self.config.read().await;+ let paused = *self.paused.read().await;++ if config.enabled && !paused {+ drop(config); // Release lock before sync+ if let Err(e) = self.run_sync_cycle(&event_tx).await {+ let _ = event_tx.send(SyncEvent::Failed(e.to_string())).await;+ }+ }+ }++ Some(command) = command_rx.recv() => {+ match command {+ SyncCommand::SyncNow => {+ if let Err(e) = self.run_sync_cycle(&event_tx).await {+ let _ = event_tx.send(SyncEvent::Failed(e.to_string())).await;+ }+ }+ SyncCommand::Pause => {+ *self.paused.write().await = true;+ }+ SyncCommand::Resume => {+ *self.paused.write().await = false;+ }+ SyncCommand::UpdateConfig(new_config) => {+ // Update interval if changed+ let old_interval = self.config.read().await.sync_interval_secs;+ if new_config.sync_interval_secs != old_interval {+ sync_interval = interval(Duration::from_secs(new_config.sync_interval_secs));+ }+ *self.config.write().await = new_config;+ }+ SyncCommand::Stop => {+ let _ = event_tx.send(SyncEvent::Stopped).await;+ break;+ }+ }+ }+ }+ }+ }++ async fn run_sync_cycle(&self, event_tx: &mpsc::Sender<SyncEvent>) -> SyncResult<()> {+ let start_time = std::time::Instant::now();++ // Check if manager is initialized+ if !self.manager.is_initialized().await {+ return Err(SyncError::Key("sync not initialized".to_string()));+ }++ let _ = event_tx.send(SyncEvent::Started).await;++ let config = self.config.read().await.clone();+ let mut total_uploaded = 0usize;+ let mut total_bytes = 0u64;+ let mut total_failed = 0usize;+ let mut storage_used = 0u64;+ let mut storage_limit = 0u64;++ for blob_type in &config.sync_types {+ // Get pending data+ let pending = self+ .data_provider+ .get_pending_data(*blob_type, config.max_blobs_per_cycle)+ .await?;++ let total_for_type = pending.len();++ for (idx, blob) in pending.into_iter().enumerate() {+ match self+ .manager+ .upload(+ &blob.data,+ *blob_type,+ &blob.time_start,+ &blob.time_end,+ blob.text_content.as_deref(),+ )+ .await+ {+ Ok(result) => {+ total_uploaded += 1;+ total_bytes += blob.data.len() as u64;+ storage_used = result.storage_used;+ storage_limit = result.storage_limit;++ // Mark as synced+ if let Err(e) = self+ .data_provider+ .mark_synced(*blob_type, &blob.time_start, &blob.time_end, &result.blob_id)+ .await+ {+ tracing::error!("failed to mark blob as synced: {}", e);+ }++ // Send progress+ let _ = event_tx+ .send(SyncEvent::Progress {+ uploaded: idx + 1,+ total: total_for_type,+ bytes_transferred: total_bytes,+ })+ .await;+ }+ Err(e) => {+ tracing::error!("failed to upload blob: {}", e);+ total_failed += 1;++ // Check if it's a quota error - stop syncing+ if matches!(e, SyncError::QuotaExceeded(_)) {+ return Err(e);+ }+ }+ }+ }+ }++ let duration = start_time.elapsed();++ let report = SyncReport {+ blobs_uploaded: total_uploaded,+ bytes_uploaded: total_bytes,+ blobs_failed: total_failed,+ duration_secs: duration.as_secs_f64(),+ storage_used,+ storage_limit,+ };++ let _ = event_tx.send(SyncEvent::Completed(report)).await;++ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_default_config() {+ let config = SyncServiceConfig::default();+ assert!(config.enabled);+ assert_eq!(config.sync_interval_secs, 300);+ assert!(!config.sync_types.is_empty());+ }++ #[test]+ fn test_sync_report() {+ let report = SyncReport {+ blobs_uploaded: 5,+ bytes_uploaded: 1024 * 1024,+ blobs_failed: 0,+ duration_secs: 2.5,+ storage_used: 100 * 1024 * 1024,+ storage_limit: 1024 * 1024 * 1024,+ };++ assert_eq!(report.blobs_uploaded, 5);+ assert_eq!(report.bytes_uploaded, 1024 * 1024);+ }+}diff --git a/screenpipe-db/src/migrations/20250131000000_add_cloud_sync_columns.sql b/screenpipe-db/src/migrations/20250131000000_add_cloud_sync_columns.sqlnew file mode 100644index 000000000..6d05b2e91--- /dev/null+++ b/screenpipe-db/src/migrations/20250131000000_add_cloud_sync_columns.sql@@ -0,0 +1,45 @@+-- Cloud sync columns for multi-machine sync+-- sync_id: UUID for deduplication across machines+-- machine_id: identifies which computer the record came from+-- synced_at: when this record was uploaded to cloud (NULL = not synced yet)++-- Add sync columns to frames+ALTER TABLE frames ADD COLUMN sync_id TEXT;+ALTER TABLE frames ADD COLUMN machine_id TEXT;+ALTER TABLE frames ADD COLUMN synced_at DATETIME;++-- Add sync columns to ocr_text+ALTER TABLE ocr_text ADD COLUMN sync_id TEXT;+ALTER TABLE ocr_text ADD COLUMN synced_at DATETIME;++-- Add sync columns to audio_chunks+ALTER TABLE audio_chunks ADD COLUMN sync_id TEXT;+ALTER TABLE audio_chunks ADD COLUMN machine_id TEXT;+ALTER TABLE audio_chunks ADD COLUMN synced_at DATETIME;++-- Add sync columns to audio_transcriptions+ALTER TABLE audio_transcriptions ADD COLUMN sync_id TEXT;+ALTER TABLE audio_transcriptions ADD COLUMN synced_at DATETIME;++-- Add sync columns to video_chunks+ALTER TABLE video_chunks ADD COLUMN sync_id TEXT;+ALTER TABLE video_chunks ADD COLUMN machine_id TEXT;+ALTER TABLE video_chunks ADD COLUMN synced_at DATETIME;++-- Indexes for efficient sync queries+CREATE INDEX IF NOT EXISTS idx_frames_sync_id ON frames(sync_id);+CREATE INDEX IF NOT EXISTS idx_frames_synced_at ON frames(synced_at);+CREATE INDEX IF NOT EXISTS idx_frames_machine_id ON frames(machine_id);++CREATE INDEX IF NOT EXISTS idx_ocr_text_sync_id ON ocr_text(sync_id);+CREATE INDEX IF NOT EXISTS idx_ocr_text_synced_at ON ocr_text(synced_at);++CREATE INDEX IF NOT EXISTS idx_audio_chunks_sync_id ON audio_chunks(sync_id);+CREATE INDEX IF NOT EXISTS idx_audio_chunks_synced_at ON audio_chunks(synced_at);++CREATE INDEX IF NOT EXISTS idx_audio_transcriptions_sync_id ON audio_transcriptions(sync_id);+CREATE INDEX IF NOT EXISTS idx_audio_transcriptions_synced_at ON audio_transcriptions(synced_at);++-- Index for finding unsynced records+CREATE INDEX IF NOT EXISTS idx_frames_unsynced ON frames(synced_at) WHERE synced_at IS NULL;+CREATE INDEX IF NOT EXISTS idx_audio_transcriptions_unsynced ON audio_transcriptions(synced_at) WHERE synced_at IS NULL;diff --git a/screenpipe-js/ai-proxy/src/index.ts b/screenpipe-js/ai-proxy/src/index.tsindex bdf3a2582..cbe8eaefd 100644--- a/screenpipe-js/ai-proxy/src/index.ts+++ b/screenpipe-js/ai-proxy/src/index.ts@@ -128,6 +128,43 @@ async function handleRequest(request: Request, env: Env, ctx: ExecutionContext):return await handleVertexProxy(request, env);}+ // Anthropic-compatible endpoint for OpenCode integration+ // OpenCode sends requests to baseURL/v1/messages when configured with api: "anthropic"+ // Requires logged-in user (not anonymous)+ if (path === '/anthropic/v1/messages' && request.method === 'POST') {+ console.log('OpenCode Anthropic proxy request to /anthropic/v1/messages');++ // Require authentication for OpenCode+ if (authResult.tier === 'anonymous') {+ return addCorsHeaders(createErrorResponse(401, JSON.stringify({+ error: 'authentication_required',+ message: 'OpenCode requires authentication. Please log in to screenpipe.',+ })));+ }++ // Track usage for OpenCode requests+ const ipAddress = request.headers.get('cf-connecting-ip') || undefined;+ const usage = await trackUsage(env, authResult.deviceId, authResult.tier, authResult.userId, ipAddress);+ if (!usage.allowed) {+ return addCorsHeaders(createErrorResponse(429, JSON.stringify({+ error: 'daily_limit_exceeded',+ message: `You've used all ${usage.limit} AI queries for today. Resets at ${usage.resetsAt}`,+ used_today: usage.used,+ limit_today: usage.limit,+ resets_at: usage.resetsAt,+ tier: authResult.tier,+ })));+ }++ return await handleVertexProxy(request, env);+ }++ // Anthropic models endpoint for OpenCode+ if (path === '/anthropic/v1/models' && request.method === 'GET') {+ console.log('OpenCode Anthropic models request');+ return await handleVertexModels(env);+ }+return createErrorResponse(404, 'not found');} catch (error: any) {console.error('error in fetch:', error?.message, error?.stack);diff --git a/screenpipe-js/ai-proxy/src/providers/vertex.ts b/screenpipe-js/ai-proxy/src/providers/vertex.tsindex 815f2f609..ad44f10c8 100644--- a/screenpipe-js/ai-proxy/src/providers/vertex.ts+++ b/screenpipe-js/ai-proxy/src/providers/vertex.ts@@ -500,14 +500,12 @@ export class VertexAIProvider implements AIProvider {}/**- * List available models - all get mapped to claude-sonnet-4@20250514+ * List available models - haiku-4.5 and opus-4.5*/async listModels(): Promise<{ id: string; name: string; provider: string }[]> {const models = [- { id: 'gemini-3-pro-preview', name: 'Gemini 3 Pro', provider: 'google' },- { id: 'gemini-3-flash-preview', name: 'Gemini 3 Flash', provider: 'google' },- { id: 'claude-opus-4-5@20251101', name: 'Claude Opus 4.5', provider: 'vertex' },{ id: 'claude-haiku-4-5@20251001', name: 'Claude Haiku 4.5', provider: 'vertex' },+ { id: 'claude-opus-4-5@20251101', name: 'Claude Opus 4.5', provider: 'vertex' },];return models;}@@ -557,7 +555,7 @@ export async function proxyToVertex(console.log('proxyToVertex: got access token');// Map model to Vertex format- const model = body.model || 'claude-sonnet-4@20250514';+ const model = body.model || 'claude-haiku-4-5@20251001';const vertexModel = mapModelToVertex(model);console.log('proxyToVertex: mapped model', model, '->', vertexModel);const method = isStreaming ? 'streamRawPredict' : 'rawPredict';@@ -619,23 +617,23 @@ export async function proxyToVertex(}}-// Model aliases - map requested models to what's actually available in the GCP project-// Currently only claude-sonnet-4@20250514 is enabled+// Model aliases - map requested models to what's available in the GCP project+// Available: claude-haiku-4-5@20251001, claude-opus-4-5@20251101const MODEL_ALIASES: Record<string, string> = {- // Map all Claude models to the one that works- 'claude-sonnet-4-5@20250929': 'claude-sonnet-4@20250514',- 'claude-sonnet-4-5': 'claude-sonnet-4@20250514',- 'claude-opus-4-5@20251101': 'claude-sonnet-4@20250514',- 'claude-opus-4-5': 'claude-sonnet-4@20250514',- 'claude-haiku-4-5@20251001': 'claude-sonnet-4@20250514',- 'claude-haiku-4-5': 'claude-sonnet-4@20250514',- 'claude-opus-4@20250514': 'claude-sonnet-4@20250514',- 'claude-opus-4': 'claude-sonnet-4@20250514',- 'claude-haiku-4': 'claude-sonnet-4@20250514',- // Simple aliases- 'claude-haiku': 'claude-sonnet-4@20250514',- 'claude-sonnet': 'claude-sonnet-4@20250514',- 'claude-opus': 'claude-sonnet-4@20250514',+ // Haiku 4.5 aliases+ 'claude-haiku-4-5': 'claude-haiku-4-5@20251001',+ 'claude-haiku-4': 'claude-haiku-4-5@20251001',+ 'claude-haiku': 'claude-haiku-4-5@20251001',+ 'claude-3-haiku-20240307': 'claude-haiku-4-5@20251001',+ // Opus 4.5 aliases+ 'claude-opus-4-5': 'claude-opus-4-5@20251101',+ 'claude-opus-4': 'claude-opus-4-5@20251101',+ 'claude-opus': 'claude-opus-4-5@20251101',+ // Sonnet -> Haiku (sonnet is outdated, use haiku as default)+ 'claude-sonnet-4-5@20250929': 'claude-haiku-4-5@20251001',+ 'claude-sonnet-4-5': 'claude-haiku-4-5@20251001',+ 'claude-sonnet-4@20250514': 'claude-haiku-4-5@20251001',+ 'claude-sonnet': 'claude-haiku-4-5@20251001',};// Convert model ID format and apply aliases@@ -662,9 +660,9 @@ export function mapModelToVertex(model: string): string {return converted;}- // Default fallback to the working model for any claude request+ // Default fallback to haiku for any claude requestif (model.toLowerCase().includes('claude')) {- return 'claude-sonnet-4@20250514';+ return 'claude-haiku-4-5@20251001';}return model;diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 4e60f9d97..cf017c65e 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -17,7 +17,7 @@ oasgen = { workspace = true }screenpipe-events = { path = "../screenpipe-events" }screenpipe-vision = { path = "../screenpipe-vision" }screenpipe-audio = { path = "../screenpipe-audio" }-screenpipe-core = { path = "../screenpipe-core", features = ["security"] }+screenpipe-core = { path = "../screenpipe-core", features = ["security", "cloud-sync"] }screenpipe-db = { path = "../screenpipe-db" }killport = { version = "1.1.0" }@@ -43,6 +43,7 @@ candle-transformers = { workspace = true }tokenizers = { workspace = true }anyhow = "1.0.86"+async-trait = "0.1"moka = { version = "0.12", features = ["future"] }hf-hub = { workspace = true }diff --git a/screenpipe-server/src/cloud_search.rs b/screenpipe-server/src/cloud_search.rsnew file mode 100644index 000000000..b3b2768f7--- /dev/null+++ b/screenpipe-server/src/cloud_search.rs@@ -0,0 +1,250 @@+//! Cloud search integration for hybrid local + cloud queries.+//!+//! This module provides the interface for querying cloud-synced data+//! alongside local data in search operations.++use chrono::{DateTime, Utc};+use oasgen::OaSchema;+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tokio::sync::RwLock;++/// Cloud search client for querying encrypted cloud data.+pub struct CloudSearchClient {+ /// Whether cloud search is enabled+ enabled: Arc<RwLock<bool>>,+ /// The sync manager (if initialized)+ #[allow(dead_code)]+ manager: Option<Arc<screenpipe_core::sync::SyncManager>>,+}++impl CloudSearchClient {+ /// Create a new cloud search client (disabled by default).+ pub fn new() -> Self {+ Self {+ enabled: Arc::new(RwLock::new(false)),+ manager: None,+ }+ }++ /// Create a cloud search client with an initialized sync manager.+ #[allow(dead_code)]+ pub fn with_manager(manager: Arc<screenpipe_core::sync::SyncManager>) -> Self {+ Self {+ enabled: Arc::new(RwLock::new(true)),+ manager: Some(manager),+ }+ }++ /// Check if cloud search is enabled.+ pub async fn is_enabled(&self) -> bool {+ *self.enabled.read().await+ }++ /// Enable or disable cloud search.+ #[allow(dead_code)]+ pub async fn set_enabled(&self, enabled: bool) {+ *self.enabled.write().await = enabled;+ }++ /// Search cloud data.+ ///+ /// This performs an encrypted search on cloud-synced data.+ pub async fn search(&self, params: CloudSearchParams) -> Result<CloudSearchResult, String> {+ if !self.is_enabled().await {+ return Ok(CloudSearchResult {+ items: vec![],+ has_more: false,+ cloud_status: CloudStatus::Disabled,+ latency_ms: 0,+ });+ }++ // Check if manager is available+ let _manager = match &self.manager {+ Some(m) if m.is_initialized().await => m,+ _ => {+ return Ok(CloudSearchResult {+ items: vec![],+ has_more: false,+ cloud_status: CloudStatus::NotInitialized,+ latency_ms: 0,+ });+ }+ };++ let start = std::time::Instant::now();++ // TODO: Implement actual cloud search when sync manager is connected+ // For now, return empty results with status+ //+ // The real implementation would:+ // 1. Generate search tokens from the query using the search key+ // 2. Send tokens to cloud API+ // 3. Receive encrypted blob IDs that match+ // 4. Download and decrypt matching blobs+ // 5. Return decrypted content++ let latency_ms = start.elapsed().as_millis() as u64;++ Ok(CloudSearchResult {+ items: vec![],+ has_more: params.time_range.is_some(), // Indicate more data exists if time range was specified+ cloud_status: CloudStatus::Available,+ latency_ms,+ })+ }++ /// Get cloud search metadata (for including in search responses).+ pub async fn get_metadata(&self, query: &str, time_range: Option<TimeRange>) -> CloudSearchMetadata {+ let enabled = self.is_enabled().await;++ let status = if !enabled {+ CloudStatus::Disabled+ } else {+ match &self.manager {+ Some(m) if m.is_initialized().await => CloudStatus::Available,+ _ => CloudStatus::NotInitialized,+ }+ };++ CloudSearchMetadata {+ cloud_search_available: enabled && matches!(status, CloudStatus::Available),+ cloud_has_relevant_data: time_range.is_some(), // Assume cloud has data if time range specified+ cloud_query_hint: if enabled && !query.is_empty() {+ Some(format!("Add include_cloud=true to include cloud results for '{}'", query))+ } else {+ None+ },+ status,+ }+ }+}++impl Default for CloudSearchClient {+ fn default() -> Self {+ Self::new()+ }+}++/// Parameters for cloud search.+#[derive(Debug, Clone)]+pub struct CloudSearchParams {+ /// Search query text+ pub query: String,+ /// Content type filter+ pub content_type: CloudContentType,+ /// Time range filter+ pub time_range: Option<TimeRange>,+ /// Maximum results to return+ pub limit: u32,+ /// Result offset for pagination+ pub offset: u32,+}++/// Time range for filtering.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TimeRange {+ pub start: DateTime<Utc>,+ pub end: DateTime<Utc>,+}++/// Content types for cloud search.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CloudContentType {+ Ocr,+ Transcripts,+ All,+}++/// Result of a cloud search operation.+#[derive(Debug, Clone)]+pub struct CloudSearchResult {+ /// Matching items from cloud+ pub items: Vec<CloudContentItem>,+ /// Whether there are more results available+ pub has_more: bool,+ /// Cloud connection status+ pub cloud_status: CloudStatus,+ /// Query latency in milliseconds+ pub latency_ms: u64,+}++/// A single content item from cloud search.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CloudContentItem {+ /// Blob ID in cloud storage+ pub blob_id: String,+ /// Content type+ pub content_type: String,+ /// Timestamp of the content+ pub timestamp: DateTime<Utc>,+ /// Decrypted text content (if available)+ pub text: Option<String>,+ /// Time range of the blob+ pub time_start: String,+ pub time_end: String,+}++/// Cloud connection status.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, OaSchema)]+#[serde(rename_all = "snake_case")]+pub enum CloudStatus {+ /// Cloud sync is available and working+ Available,+ /// Cloud sync is disabled+ Disabled,+ /// Cloud sync is not initialized (no password entered)+ NotInitialized,+ /// Error connecting to cloud+ Error,+}++/// Metadata about cloud search to include in responses.+#[derive(Debug, Clone, Serialize, Deserialize, OaSchema)]+#[serde(rename_all = "camelCase")]+pub struct CloudSearchMetadata {+ /// Whether cloud search is available+ pub cloud_search_available: bool,+ /// Whether cloud might have relevant data for the query+ pub cloud_has_relevant_data: bool,+ /// Hint for how to include cloud results+ pub cloud_query_hint: Option<String>,+ /// Current cloud status+ pub status: CloudStatus,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn test_cloud_search_disabled_by_default() {+ let client = CloudSearchClient::new();+ assert!(!client.is_enabled().await);+ }++ #[tokio::test]+ async fn test_cloud_search_returns_disabled_status() {+ let client = CloudSearchClient::new();+ let result = client.search(CloudSearchParams {+ query: "test".to_string(),+ content_type: CloudContentType::All,+ time_range: None,+ limit: 10,+ offset: 0,+ }).await.unwrap();++ assert!(result.items.is_empty());+ assert_eq!(result.cloud_status, CloudStatus::Disabled);+ }++ #[tokio::test]+ async fn test_cloud_metadata_when_disabled() {+ let client = CloudSearchClient::new();+ let metadata = client.get_metadata("test query", None).await;++ assert!(!metadata.cloud_search_available);+ assert_eq!(metadata.status, CloudStatus::Disabled);+ }+}diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex be8e8bd30..1ca382a4d 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -3,7 +3,9 @@ pub mod analytics;mod auto_destruct;pub mod chunking;pub mod cli;+pub mod cloud_search;pub mod core;+pub mod sync_provider;pub mod filtering;pub mod pipe_manager;mod resource_monitor;@@ -30,3 +32,4 @@ pub use server::SCServer;pub use server::{api_list_monitors, MonitorInfo};pub use video::{FrameWriteInfo, FrameWriteTracker, VideoCapture};pub mod embedding;+pub use cloud_search::{CloudSearchClient, CloudSearchMetadata, CloudStatus};diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 650cbd481..d5b244cfb 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -112,6 +112,8 @@ pub struct AppState {pub search_cache: SearchCache,/// Enable PII removal from text contentpub use_pii_removal: bool,+ /// Cloud search client for hybrid local + cloud queries+ pub cloud_search: Arc<crate::cloud_search::CloudSearchClient>,}// Update the SearchQuery struct@@ -150,6 +152,9 @@ pub(crate) struct SearchQuery {/// Filter audio transcriptions by speaker name (case-insensitive partial match)#[serde(default)]speaker_name: Option<String>,+ /// Include cloud-synced data in search results (requires cloud sync to be enabled)+ #[serde(default)]+ include_cloud: bool,}#[derive(OaSchema, Deserialize)]@@ -337,6 +342,9 @@ pub struct HealthCheckResponse {pub struct SearchResponse {pub data: Vec<ContentItem>,pub pagination: PaginationInfo,+ /// Metadata about cloud search availability (only present when cloud sync is available)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cloud: Option<crate::cloud_search::CloudSearchMetadata>,}/// Compute a cache key for a search query by hashing its parameters@@ -357,6 +365,7 @@ fn compute_search_cache_key(query: &SearchQuery) -> u64 {query.focused.hash(&mut hasher);query.browser_url.hash(&mut hasher);query.speaker_name.hash(&mut hasher);+ query.include_cloud.hash(&mut hasher);hasher.finish()}@@ -538,6 +547,20 @@ pub(crate) async fn search(}),);+ // Get cloud search metadata+ let time_range = match (query.start_time, query.end_time) {+ (Some(start), Some(end)) => Some(crate::cloud_search::TimeRange { start, end }),+ _ => None,+ };+ let cloud_metadata = state.cloud_search.get_metadata(query_str, time_range).await;++ // Only include cloud metadata if cloud search is available or was requested+ let cloud = if cloud_metadata.cloud_search_available || query.include_cloud {+ Some(cloud_metadata)+ } else {+ None+ };+let response = SearchResponse {data: content_items,pagination: PaginationInfo {@@ -545,6 +568,7 @@ pub(crate) async fn search(offset: query.pagination.offset,total: total as i64,},+ cloud,};// Cache the result (only for queries without frame extraction)@@ -1280,6 +1304,8 @@ impl SCServer {.time_to_live(Duration::from_secs(60)).build(),use_pii_removal: self.use_pii_removal,+ // Cloud search client (disabled by default, can be enabled via API)+ cloud_search: Arc::new(crate::cloud_search::CloudSearchClient::new()),});let cors = CorsLayer::new()@@ -3902,6 +3928,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let query2 = SearchQuery {@@ -3923,6 +3950,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let key1 = compute_search_cache_key(&query1);@@ -3952,6 +3980,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let query2 = SearchQuery {@@ -3973,6 +4002,7 @@ mod tests {focused: None,browser_url: None,speaker_name: None,+ include_cloud: false,};let key1 = compute_search_cache_key(&query1);diff --git a/screenpipe-server/src/sync_api.rs b/screenpipe-server/src/sync_api.rsnew file mode 100644index 000000000..b1e0406ca--- /dev/null+++ b/screenpipe-server/src/sync_api.rs@@ -0,0 +1,200 @@+//! Sync API endpoints for cloud sync operations.+//!+//! These endpoints allow the Tauri app to:+//! - Get pending (unsynced) data for upload+//! - Mark data as synced after upload+//! - Import data from other machines++use axum::{+ extract::State,+ http::StatusCode,+ Json,+};+use screenpipe_core::sync::{PendingBlob, SyncDataProvider};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::sync::Arc;+use tracing::error;++use crate::server::AppState;+use crate::sync_provider::{ScreenpipeSyncProvider, SyncChunk};++/// Request to get pending sync data.+#[derive(Debug, Deserialize)]+pub struct GetPendingRequest {+ /// Type of data to get: "ocr" or "transcripts"+ pub data_type: String,+ /// Maximum number of records to return+ #[serde(default = "default_limit")]+ pub limit: usize,+ /// Machine ID for this device+ pub machine_id: String,+}++fn default_limit() -> usize {+ 100+}++/// Response containing pending sync data.+#[derive(Debug, Serialize)]+pub struct GetPendingResponse {+ pub success: bool,+ /// Serialized SyncChunk as JSON+ pub chunk: Option<Value>,+ /// Whether there's more data to sync+ pub has_more: bool,+ /// Count of records in this chunk+ pub record_count: usize,+}++/// Get pending (unsynced) data for upload.+pub async fn get_pending_sync_data(+ State(state): State<Arc<AppState>>,+ Json(request): Json<GetPendingRequest>,+) -> Result<Json<GetPendingResponse>, (StatusCode, Json<Value>)> {+ let provider = ScreenpipeSyncProvider::new(state.db.clone(), request.machine_id);++ let blob_type = match request.data_type.as_str() {+ "ocr" => screenpipe_core::sync::BlobType::Ocr,+ "transcripts" => screenpipe_core::sync::BlobType::Transcripts,+ _ => {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({"error": "invalid data_type, must be 'ocr' or 'transcripts'"})),+ ));+ }+ };++ match provider.get_pending_data(blob_type, request.limit).await {+ Ok(pending) => {+ let pending: Vec<PendingBlob> = pending;+ if pending.is_empty() {+ return Ok(Json(GetPendingResponse {+ success: true,+ chunk: None,+ has_more: false,+ record_count: 0,+ }));+ }++ // The pending data is already a serialized SyncChunk+ let blob = &pending[0];+ 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: {}", e)})),+ )+ })?;++ let record_count = chunk.frames.len() + chunk.ocr_records.len() + chunk.transcriptions.len();++ Ok(Json(GetPendingResponse {+ success: true,+ chunk: Some(serde_json::to_value(&chunk).unwrap()),+ has_more: pending.len() > 1 || record_count >= request.limit,+ record_count,+ }))+ }+ Err(e) => {+ error!("failed to get pending data: {}", e);+ Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": format!("failed to get pending data: {}", e)})),+ ))+ }+ }+}++/// Request to mark data as synced.+#[derive(Debug, Deserialize)]+pub struct MarkSyncedRequest {+ /// Type of data: "ocr" or "transcripts"+ pub data_type: String,+ /// Start of time range that was synced+ pub time_start: String,+ /// End of time range that was synced+ pub time_end: String,+ /// Blob ID assigned by cloud+ pub blob_id: String,+ /// Machine ID for this device+ pub machine_id: String,+}++/// Mark data as synced after successful upload.+pub async fn mark_synced(+ State(state): State<Arc<AppState>>,+ Json(request): Json<MarkSyncedRequest>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ let provider = ScreenpipeSyncProvider::new(state.db.clone(), request.machine_id);++ let blob_type = match request.data_type.as_str() {+ "ocr" => screenpipe_core::sync::BlobType::Ocr,+ "transcripts" => screenpipe_core::sync::BlobType::Transcripts,+ _ => {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({"error": "invalid data_type"})),+ ));+ }+ };++ use screenpipe_core::sync::SyncDataProvider;+ match provider+ .mark_synced(blob_type, &request.time_start, &request.time_end, &request.blob_id)+ .await+ {+ Ok(()) => Ok(Json(json!({"success": true}))),+ Err(e) => {+ error!("failed to mark as synced: {}", e);+ Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": format!("failed to mark synced: {}", e)})),+ ))+ }+ }+}++/// Request to import synced data from another machine.+#[derive(Debug, Deserialize)]+pub struct ImportChunkRequest {+ /// The SyncChunk data to import+ pub chunk: SyncChunk,+ /// Machine ID for this device (to skip own data)+ pub machine_id: String,+}++/// Response from importing data.+#[derive(Debug, Serialize)]+pub struct ImportChunkResponse {+ pub success: bool,+ pub imported_frames: usize,+ pub imported_ocr: usize,+ pub imported_transcriptions: usize,+ pub skipped: usize,+}++/// Import synced data from another machine.+pub async fn import_chunk(+ State(state): State<Arc<AppState>>,+ Json(request): Json<ImportChunkRequest>,+) -> Result<Json<ImportChunkResponse>, (StatusCode, Json<Value>)> {+ let provider = ScreenpipeSyncProvider::new(state.db.clone(), request.machine_id);++ match provider.import_chunk(&request.chunk).await {+ Ok(result) => Ok(Json(ImportChunkResponse {+ success: true,+ imported_frames: result.imported_frames,+ imported_ocr: result.imported_ocr,+ imported_transcriptions: result.imported_transcriptions,+ skipped: result.skipped,+ })),+ Err(e) => {+ error!("failed to import chunk: {}", e);+ Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": format!("failed to import: {}", e)})),+ ))+ }+ }+}diff --git a/screenpipe-server/src/sync_provider.rs b/screenpipe-server/src/sync_provider.rsnew file mode 100644index 000000000..654bfffbc--- /dev/null+++ b/screenpipe-server/src/sync_provider.rs@@ -0,0 +1,580 @@+//! Sync data provider implementation for screenpipe database.+//!+//! This module bridges the screenpipe database with the cloud sync service,+//! providing data to upload and importing data from other machines.++use async_trait::async_trait;+use chrono::Utc;+use screenpipe_core::sync::{BlobType, PendingBlob, SyncDataProvider, SyncError, SyncResult};+use screenpipe_db::DatabaseManager;+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tracing::debug;+use uuid::Uuid;++/// Sync chunk containing DB records for a time window.+/// This is what gets encrypted and uploaded to the cloud.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SyncChunk {+ /// Schema version for forward compatibility+ pub schema_version: u32,+ /// Machine that created this chunk+ pub machine_id: String,+ /// Start of time range (ISO 8601)+ pub time_start: String,+ /// End of time range (ISO 8601)+ pub time_end: String,+ /// Frame records+ #[serde(default)]+ pub frames: Vec<FrameRecord>,+ /// OCR text records+ #[serde(default)]+ pub ocr_records: Vec<OcrRecord>,+ /// Audio transcription records+ #[serde(default)]+ pub transcriptions: Vec<TranscriptionRecord>,+}++/// Frame record for sync+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FrameRecord {+ pub sync_id: String,+ pub timestamp: String,+ pub offset_index: i64,+ pub app_name: Option<String>,+ pub window_name: Option<String>,+ pub browser_url: Option<String>,+ pub device_name: String,+ /// Path to frame in cloud storage (for on-demand download)+ pub cloud_frame_path: Option<String>,+}++/// OCR record for sync+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OcrRecord {+ pub sync_id: String,+ pub frame_sync_id: String,+ pub text: String,+ pub focused: bool,+}++/// Audio transcription record for sync+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TranscriptionRecord {+ pub sync_id: String,+ pub timestamp: String,+ pub transcription: String,+ pub device: String,+ pub is_input_device: bool,+ pub speaker_id: Option<i64>,+}++/// Current schema version for sync chunks+const SCHEMA_VERSION: u32 = 1;++/// Data provider implementation for screenpipe database.+pub struct ScreenpipeSyncProvider {+ db: Arc<DatabaseManager>,+ machine_id: String,+}++impl ScreenpipeSyncProvider {+ /// Create a new sync provider.+ pub fn new(db: Arc<DatabaseManager>, machine_id: String) -> Self {+ Self { db, machine_id }+ }++ /// Get unsynced frames and their OCR data for a time window.+ async fn get_unsynced_ocr_chunk(+ &self,+ limit: usize,+ ) -> SyncResult<Option<(SyncChunk, String, String)>> {+ // Find the oldest unsynced frame+ let pool = &self.db.pool;++ // Get unsynced frames+ let frames: Vec<(i64, String, i64, Option<String>, Option<String>, Option<String>, String)> = sqlx::query_as(+ r#"+ SELECT f.id, f.timestamp, f.offset_index, f.app_name, f.window_name, f.browser_url, f.device_name+ FROM frames f+ WHERE f.synced_at IS NULL+ ORDER BY f.timestamp ASC+ LIMIT ?+ "#,+ )+ .bind(limit as i64)+ .fetch_all(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to query frames: {}", e)))?;++ if frames.is_empty() {+ return Ok(None);+ }++ let frame_ids: Vec<i64> = frames.iter().map(|f| f.0).collect();+ let time_start = frames.first().map(|f| f.1.clone()).unwrap();+ let time_end = frames.last().map(|f| f.1.clone()).unwrap();++ // Get OCR for these frames+ let ocr_results: Vec<(i64, String, bool)> = sqlx::query_as(+ r#"+ SELECT frame_id, text, focused+ FROM ocr_text+ WHERE frame_id IN (SELECT value FROM json_each(?))+ "#,+ )+ .bind(serde_json::to_string(&frame_ids).unwrap())+ .fetch_all(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to query OCR: {}", e)))?;++ // Build frame records with sync_ids+ let mut frame_records = Vec::new();+ let mut frame_sync_map = std::collections::HashMap::new();++ for (id, timestamp, offset_index, app_name, window_name, browser_url, device_name) in frames {+ let sync_id = Uuid::new_v4().to_string();+ frame_sync_map.insert(id, sync_id.clone());++ frame_records.push(FrameRecord {+ sync_id,+ timestamp,+ offset_index,+ app_name,+ window_name,+ browser_url,+ device_name,+ cloud_frame_path: None, // Will be set during upload+ });+ }++ // Build OCR records+ let ocr_records: Vec<OcrRecord> = ocr_results+ .into_iter()+ .filter_map(|(frame_id, text, focused)| {+ frame_sync_map.get(&frame_id).map(|frame_sync_id| OcrRecord {+ sync_id: Uuid::new_v4().to_string(),+ frame_sync_id: frame_sync_id.clone(),+ text,+ focused,+ })+ })+ .collect();++ let chunk = SyncChunk {+ schema_version: SCHEMA_VERSION,+ machine_id: self.machine_id.clone(),+ time_start: time_start.clone(),+ time_end: time_end.clone(),+ frames: frame_records,+ ocr_records,+ transcriptions: Vec::new(),+ };++ Ok(Some((chunk, time_start, time_end)))+ }++ /// Get unsynced audio transcriptions.+ async fn get_unsynced_transcriptions_chunk(+ &self,+ limit: usize,+ ) -> SyncResult<Option<(SyncChunk, String, String)>> {+ let pool = &self.db.pool;++ let transcriptions: Vec<(i64, String, String, String, bool, Option<i64>)> = sqlx::query_as(+ r#"+ SELECT at.id, at.timestamp, at.transcription, at.device, at.is_input_device, at.speaker_id+ FROM audio_transcriptions at+ WHERE at.synced_at IS NULL+ ORDER BY at.timestamp ASC+ LIMIT ?+ "#,+ )+ .bind(limit as i64)+ .fetch_all(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to query transcriptions: {}", e)))?;++ if transcriptions.is_empty() {+ return Ok(None);+ }++ let time_start = transcriptions.first().map(|t| t.1.clone()).unwrap();+ let time_end = transcriptions.last().map(|t| t.1.clone()).unwrap();++ let records: Vec<TranscriptionRecord> = transcriptions+ .into_iter()+ .map(|(_, timestamp, transcription, device, is_input, speaker_id)| TranscriptionRecord {+ sync_id: Uuid::new_v4().to_string(),+ timestamp,+ transcription,+ device,+ is_input_device: is_input,+ speaker_id,+ })+ .collect();++ let chunk = SyncChunk {+ schema_version: SCHEMA_VERSION,+ machine_id: self.machine_id.clone(),+ time_start: time_start.clone(),+ time_end: time_end.clone(),+ frames: Vec::new(),+ ocr_records: Vec::new(),+ transcriptions: records,+ };++ Ok(Some((chunk, time_start, time_end)))+ }++ /// Import a sync chunk from another machine into the local database.+ pub async fn import_chunk(&self, chunk: &SyncChunk) -> SyncResult<ImportResult> {+ let pool = &self.db.pool;+ let mut imported_frames = 0;+ let mut imported_ocr = 0;+ let mut imported_transcriptions = 0;+ let mut skipped = 0;++ // Skip if this is our own machine+ if chunk.machine_id == self.machine_id {+ debug!("skipping own chunk from machine {}", self.machine_id);+ return Ok(ImportResult {+ imported_frames: 0,+ imported_ocr: 0,+ imported_transcriptions: 0,+ skipped: chunk.frames.len() + chunk.ocr_records.len() + chunk.transcriptions.len(),+ });+ }++ // Import frames+ for frame in &chunk.frames {+ // Check if already exists+ let exists: Option<(i64,)> = sqlx::query_as(+ "SELECT id FROM frames WHERE sync_id = ?"+ )+ .bind(&frame.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to check frame: {}", e)))?;++ if exists.is_some() {+ skipped += 1;+ continue;+ }++ // We need a video_chunk for this frame - create a virtual one for synced data+ let video_chunk_id: i64 = sqlx::query_scalar(+ r#"+ INSERT INTO video_chunks (file_path, device_name, sync_id, machine_id)+ VALUES ('cloud://' || ?, ?, ?, ?)+ ON CONFLICT DO NOTHING+ RETURNING id+ "#+ )+ .bind(&frame.sync_id)+ .bind(&frame.device_name)+ .bind(&frame.sync_id)+ .bind(&chunk.machine_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to create video_chunk: {}", e)))?+ .unwrap_or(0);++ if video_chunk_id == 0 {+ skipped += 1;+ continue;+ }++ // Insert frame+ sqlx::query(+ r#"+ INSERT INTO frames (video_chunk_id, offset_index, timestamp, app_name, window_name, browser_url, device_name, sync_id, machine_id, synced_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ "#+ )+ .bind(video_chunk_id)+ .bind(frame.offset_index)+ .bind(&frame.timestamp)+ .bind(&frame.app_name)+ .bind(&frame.window_name)+ .bind(&frame.browser_url)+ .bind(&frame.device_name)+ .bind(&frame.sync_id)+ .bind(&chunk.machine_id)+ .bind(Utc::now().to_rfc3339())+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to insert frame: {}", e)))?;++ imported_frames += 1;+ }++ // Build sync_id to local frame_id map+ let frame_sync_ids: Vec<String> = chunk.frames.iter().map(|f| f.sync_id.clone()).collect();+ let frame_id_map: std::collections::HashMap<String, i64> = if !frame_sync_ids.is_empty() {+ sqlx::query_as::<_, (String, i64)>(+ "SELECT sync_id, id FROM frames WHERE sync_id IN (SELECT value FROM json_each(?))"+ )+ .bind(serde_json::to_string(&frame_sync_ids).unwrap())+ .fetch_all(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to get frame IDs: {}", e)))?+ .into_iter()+ .collect()+ } else {+ std::collections::HashMap::new()+ };++ // Import OCR+ for ocr in &chunk.ocr_records {+ if let Some(&frame_id) = frame_id_map.get(&ocr.frame_sync_id) {+ // Check if already exists+ let exists: Option<(i64,)> = sqlx::query_as(+ "SELECT 1 FROM ocr_text WHERE sync_id = ?"+ )+ .bind(&ocr.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to check OCR: {}", e)))?;++ if exists.is_some() {+ skipped += 1;+ continue;+ }++ sqlx::query(+ r#"+ INSERT INTO ocr_text (frame_id, text, focused, sync_id, synced_at)+ VALUES (?, ?, ?, ?, ?)+ "#+ )+ .bind(frame_id)+ .bind(&ocr.text)+ .bind(ocr.focused)+ .bind(&ocr.sync_id)+ .bind(Utc::now().to_rfc3339())+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to insert OCR: {}", e)))?;++ imported_ocr += 1;+ } else {+ skipped += 1;+ }+ }++ // Import transcriptions+ for trans in &chunk.transcriptions {+ // Check if already exists+ let exists: Option<(i64,)> = sqlx::query_as(+ "SELECT 1 FROM audio_transcriptions WHERE sync_id = ?"+ )+ .bind(&trans.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to check transcription: {}", e)))?;++ if exists.is_some() {+ skipped += 1;+ continue;+ }++ // Create audio chunk for synced transcription+ let audio_chunk_id: i64 = sqlx::query_scalar(+ r#"+ INSERT INTO audio_chunks (file_path, device_name, sync_id, machine_id)+ VALUES ('cloud://' || ?, ?, ?, ?)+ RETURNING id+ "#+ )+ .bind(&trans.sync_id)+ .bind(&trans.device)+ .bind(&trans.sync_id)+ .bind(&chunk.machine_id)+ .fetch_one(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to create audio_chunk: {}", e)))?;++ sqlx::query(+ r#"+ INSERT INTO audio_transcriptions (audio_chunk_id, offset_index, timestamp, transcription, device, is_input_device, speaker_id, sync_id, synced_at)+ VALUES (?, 0, ?, ?, ?, ?, ?, ?, ?)+ "#+ )+ .bind(audio_chunk_id)+ .bind(&trans.timestamp)+ .bind(&trans.transcription)+ .bind(&trans.device)+ .bind(trans.is_input_device)+ .bind(trans.speaker_id)+ .bind(&trans.sync_id)+ .bind(Utc::now().to_rfc3339())+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to insert transcription: {}", e)))?;++ imported_transcriptions += 1;+ }++ Ok(ImportResult {+ imported_frames,+ imported_ocr,+ imported_transcriptions,+ skipped,+ })+ }++ /// Mark records as synced after successful upload.+ async fn mark_records_synced(+ &self,+ blob_type: BlobType,+ time_start: &str,+ time_end: &str,+ ) -> SyncResult<()> {+ let pool = &self.db.pool;+ let now = Utc::now().to_rfc3339();++ match blob_type {+ BlobType::Ocr => {+ // Mark frames and their OCR as synced+ sqlx::query(+ r#"+ UPDATE frames SET synced_at = ?+ WHERE timestamp >= ? AND timestamp <= ? AND synced_at IS NULL+ "#+ )+ .bind(&now)+ .bind(time_start)+ .bind(time_end)+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to mark frames synced: {}", e)))?;+ }+ BlobType::Transcripts => {+ sqlx::query(+ r#"+ UPDATE audio_transcriptions SET synced_at = ?+ WHERE timestamp >= ? AND timestamp <= ? AND synced_at IS NULL+ "#+ )+ .bind(&now)+ .bind(time_start)+ .bind(time_end)+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to mark transcriptions synced: {}", e)))?;+ }+ _ => {}+ }++ Ok(())+ }++ /// Get combined text from a chunk for search token generation.+ fn get_chunk_text(chunk: &SyncChunk) -> String {+ let mut text_parts = Vec::new();++ for ocr in &chunk.ocr_records {+ text_parts.push(ocr.text.clone());+ }++ for trans in &chunk.transcriptions {+ text_parts.push(trans.transcription.clone());+ }++ text_parts.join(" ")+ }+}++#[async_trait]+impl SyncDataProvider for ScreenpipeSyncProvider {+ async fn get_pending_data(+ &self,+ blob_type: BlobType,+ limit: usize,+ ) -> SyncResult<Vec<PendingBlob>> {+ let chunk_result = match blob_type {+ BlobType::Ocr => self.get_unsynced_ocr_chunk(limit).await?,+ BlobType::Transcripts => self.get_unsynced_transcriptions_chunk(limit).await?,+ _ => return Ok(Vec::new()),+ };++ match chunk_result {+ Some((chunk, time_start, time_end)) => {+ let text_content = Self::get_chunk_text(&chunk);+ let data = serde_json::to_vec(&chunk)+ .map_err(|e| SyncError::Database(format!("failed to serialize chunk: {}", e)))?;++ Ok(vec![PendingBlob {+ data,+ time_start,+ time_end,+ text_content: if text_content.is_empty() {+ None+ } else {+ Some(text_content)+ },+ }])+ }+ None => Ok(Vec::new()),+ }+ }++ async fn mark_synced(+ &self,+ blob_type: BlobType,+ time_start: &str,+ time_end: &str,+ _blob_id: &str,+ ) -> SyncResult<()> {+ self.mark_records_synced(blob_type, time_start, time_end).await+ }+}++/// Result of importing a sync chunk.+#[derive(Debug, Clone)]+pub struct ImportResult {+ pub imported_frames: usize,+ pub imported_ocr: usize,+ pub imported_transcriptions: usize,+ pub skipped: usize,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_sync_chunk_serialization() {+ let chunk = SyncChunk {+ schema_version: 1,+ machine_id: "test-machine".to_string(),+ time_start: "2024-01-28T14:00:00Z".to_string(),+ time_end: "2024-01-28T14:05:00Z".to_string(),+ frames: vec![FrameRecord {+ sync_id: "abc-123".to_string(),+ timestamp: "2024-01-28T14:00:00Z".to_string(),+ offset_index: 0,+ app_name: Some("Chrome".to_string()),+ window_name: Some("Meeting".to_string()),+ browser_url: None,+ device_name: "MacBook".to_string(),+ cloud_frame_path: None,+ }],+ ocr_records: vec![OcrRecord {+ sync_id: "def-456".to_string(),+ frame_sync_id: "abc-123".to_string(),+ text: "Hello world".to_string(),+ focused: true,+ }],+ transcriptions: Vec::new(),+ };++ let json = serde_json::to_string(&chunk).unwrap();+ let parsed: SyncChunk = serde_json::from_str(&json).unwrap();++ assert_eq!(parsed.machine_id, "test-machine");+ assert_eq!(parsed.frames.len(), 1);+ assert_eq!(parsed.ocr_records.len(), 1);+ }+}