Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

Bump app to v2.4.147, Bump CLI to v0.3.318 — feat(memories,sync): cross-device memories sync (Pro, opt-in) + device provenance via source_context._device — release-app release-cli

Louis Beaumont63c709110645
diff --git a/Cargo.toml b/Cargo.toml
index aa075e57a..be20cc74f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,7 @@ exclude = ["apps/screenpipe-app-tauri/src-tauri", "crates/screenpipe-integration
resolver = "2"
[workspace.package]
-version = "0.3.317"
+version = "0.3.318"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/screenpipe/screenpipe"
diff --git a/apps/screenpipe-app-tauri/components/settings/account-section.tsx b/apps/screenpipe-app-tauri/components/settings/account-section.tsx
index 3968cc0fb..92e726763 100644
--- a/apps/screenpipe-app-tauri/components/settings/account-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/account-section.tsx
@@ -33,6 +33,7 @@ export function AccountSection() {
const { settings, updateSettings, loadUser } = useSettings();
const [isAnnual, setIsAnnual] = useState(true);
const [pipeSyncing, setPipeSyncing] = useState(false);
+ const [memoriesSyncing, setMemoriesSyncing] = useState(false);
useEffect(() => {
if (!settings.user?.email) {
@@ -314,6 +315,62 @@ export function AccountSection() {
</div>
</div>
</div>
+
+ {/* Memories sync — independent toggle. A user might keep pipes
+ device-local but want their memories everywhere, or vice versa. */}
+ <div className="mt-4 pt-4 border-t border-border/50">
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="text-sm font-medium">memories sync across devices</p>
+ <p className="text-xs text-muted-foreground">
+ sync your memories (facts, preferences, decisions) across devices
+ </p>
+ </div>
+ <div className="flex items-center gap-3">
+ <div className="flex items-center gap-1.5">
+ <Switch
+ id="memories-sync-toggle"
+ checked={!!settings.memoriesSyncEnabled}
+ onCheckedChange={async (checked) => {
+ await updateSettings({ memoriesSyncEnabled: checked });
+ toast({
+ title: checked ? "memories sync enabled" : "memories sync disabled",
+ description: checked
+ ? "memories will sync across your devices"
+ : "memories will no longer sync",
+ });
+ }}
+ />
+ <Label htmlFor="memories-sync-toggle" className="text-xs text-muted-foreground cursor-pointer sr-only">
+ sync
+ </Label>
+ </div>
+ {settings.memoriesSyncEnabled && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs uppercase tracking-wide"
+ disabled={memoriesSyncing}
+ onClick={async () => {
+ setMemoriesSyncing(true);
+ try {
+ await localFetch("/sync/memories/pull", { method: "POST" });
+ await localFetch("/sync/memories/push", { method: "POST" });
+ toast({ title: "memories synced" });
+ } catch (e: any) {
+ toast({ title: "sync failed", description: e.message, variant: "destructive" });
+ } finally {
+ setMemoriesSyncing(false);
+ }
+ }}
+ >
+ <RefreshCw className={`h-3 w-3 mr-1 ${memoriesSyncing ? "animate-spin" : ""}`} />
+ sync now
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
</Card>
) : !settings.user?.token ? (
/* Not logged in: login-first layout */
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 55d63b15c..a251c8b70 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -194,6 +194,10 @@ export type Settings = SettingsStore & {
cloudArchiveRetentionDays?: number;
/** Sync pipe configurations across devices (requires cloud sync subscription) */
pipeSyncEnabled?: boolean;
+ /** Sync memories (facts, preferences, decisions, insights) across devices.
+ * Independent of pipeSyncEnabled — a user might want their memories on
+ * every device but keep pipes device-local, or vice versa. Pro-gated. */
+ memoriesSyncEnabled?: boolean;
/** OpenAI-compatible transcription endpoint URL */
openaiCompatibleEndpoint?: string;
/** OpenAI-compatible transcription API key */
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 4187c08e9..3b58647bb 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9754,7 +9754,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.4.146"
+version = "2.4.147"
dependencies = [
"anyhow",
"arboard",
@@ -9861,7 +9861,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"anyhow",
"audiopipe",
@@ -9917,7 +9917,7 @@ dependencies = [
[[package]]
name = "screenpipe-config"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -9929,7 +9929,7 @@ dependencies = [
[[package]]
name = "screenpipe-connect"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"anyhow",
"async-trait",
@@ -9962,7 +9962,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -10010,7 +10010,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"anyhow",
"chrono",
@@ -10035,7 +10035,7 @@ dependencies = [
[[package]]
name = "screenpipe-engine"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"anyhow",
"arc-swap",
@@ -10101,7 +10101,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"anyhow",
"chrono",
@@ -10117,7 +10117,7 @@ dependencies = [
[[package]]
name = "screenpipe-screen"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"accessibility-sys",
"anyhow",
@@ -10170,7 +10170,7 @@ dependencies = [
[[package]]
name = "screenpipe-vault"
-version = "0.3.317"
+version = "0.3.318"
dependencies = [
"argon2",
"chacha20poly1305",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 7223bb516..2546fea8d 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.4.146"
+version = "2.4.147"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/crates/screenpipe-core/src/memories/sync.rs b/crates/screenpipe-core/src/memories/sync.rs
index c0290b966..999eaefcc 100644
--- a/crates/screenpipe-core/src/memories/sync.rs
+++ b/crates/screenpipe-core/src/memories/sync.rs
@@ -126,8 +126,7 @@ pub fn merge_manifests(
let mut actions = Vec::new();
let now = Utc::now();
- let mut all_uuids: std::collections::HashSet<String> =
- local.memories.keys().cloned().collect();
+ let mut all_uuids: std::collections::HashSet<String> = local.memories.keys().cloned().collect();
all_uuids.extend(remote.memories.keys().cloned());
for uuid in &all_uuids {
@@ -212,7 +211,9 @@ fn parse_rfc3339(s: &str) -> DateTime<Utc> {
}
fn parse_rfc3339_opt(s: &str) -> Option<DateTime<Utc>> {
- DateTime::parse_from_rfc3339(s).ok().map(|d| d.with_timezone(&Utc))
+ DateTime::parse_from_rfc3339(s)
+ .ok()
+ .map(|d| d.with_timezone(&Utc))
}
#[cfg(test)]
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 769eb9468..27dae0f86 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -31,8 +31,8 @@ use crate::{
text_similarity::is_similar_transcription, AudioChunksResponse, AudioDevice, AudioEntry,
AudioResult, AudioResultRaw, ContentType, DeviceType, Element, ElementRow, ElementSource,
FrameData, FrameRow, FrameRowLight, FrameWindowData, InsertUiEvent, MeetingRecord,
- MemoryRecord, OCREntry, OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock, Order, SearchMatch,
- SearchMatchGroup, SearchResult, Speaker, TagContentType, TextBounds, TextPosition,
+ MemoryRecord, MemorySyncRow, OCREntry, OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock, Order,
+ SearchMatch, SearchMatchGroup, SearchResult, Speaker, TagContentType, TextBounds, TextPosition,
TimeSeriesChunk, UiContent, UiEventRecord, UiEventRow, VideoMetadata,
};
@@ -512,10 +512,7 @@ impl DatabaseManager {
/// the cross-device memories sync feature, so DBs that upgraded across
/// the migration boundary without applying it converge on next launch.
async fn ensure_memories_sync_columns(pool: &SqlitePool) -> Result<(), sqlx::Error> {
- let cols: &[(&str, &str)] = &[
- ("sync_uuid", "TEXT"),
- ("sync_modified_by", "TEXT"),
- ];
+ let cols: &[(&str, &str)] = &[("sync_uuid", "TEXT"), ("sync_modified_by", "TEXT")];
for (col_name, col_type) in cols {
let row: (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM pragma_table_info('memories') WHERE name = ?1",
@@ -8040,6 +8037,142 @@ LIMIT ? OFFSET ?
Ok(())
}
+ // -- memories cross-device sync helpers --
+ //
+ // The HTTP layer + background loop in screenpipe-engine/src/memories_sync.rs
+ // calls these to read all rows for the manifest, mint sync_uuids on first
+ // publish, and apply remote rows back into the local table. Conflict
+ // resolution (LWW) lives in screenpipe-core::memories::sync and is pure;
+ // these are the I/O endpoints.
+
+ /// Read every memory + its sync metadata for manifest building.
+ /// Returns the full row including sync_uuid (may be NULL for rows
+ /// born locally that haven't synced yet) and sync_modified_by.
+ pub async fn list_memories_for_sync(&self) -> Result<Vec<MemorySyncRow>, SqlxError> {
+ sqlx::query_as::<_, MemorySyncRow>(
+ "SELECT id, sync_uuid, content, source, source_context, tags, importance, \
+ created_at, updated_at, sync_modified_by \
+ FROM memories",
+ )
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ /// Stamp a freshly-minted sync_uuid + machine id on a row that's
+ /// being published for the first time. No-op if the row was deleted
+ /// while the sync was in flight (id no longer exists).
+ pub async fn set_memory_sync_identity(
+ &self,
+ id: i64,
+ sync_uuid: &str,
+ machine_id: &str,
+ ) -> Result<(), SqlxError> {
+ let mut tx = self.begin_immediate_with_retry().await?;
+ sqlx::query(
+ "UPDATE memories SET sync_uuid = ?1, sync_modified_by = ?2 \
+ WHERE id = ?3 AND sync_uuid IS NULL",
+ )
+ .bind(sync_uuid)
+ .bind(machine_id)
+ .bind(id)
+ .execute(&mut **tx.conn())
+ .await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// Apply a memory pulled from a remote machine. INSERTs if the
+ /// sync_uuid is unknown locally, UPDATEs the existing row if not.
+ /// Caller is responsible for LWW: this just writes what it's given.
+ /// `frame_id` is intentionally not synced (it's a local FK), so
+ /// imported rows always have NULL frame_id.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn upsert_synced_memory(
+ &self,
+ sync_uuid: &str,
+ content: &str,
+ source: &str,
+ source_context: Option<&str>,
+ tags: &str,
+ importance: f64,
+ created_at: &str,
+ updated_at: &str,
+ sync_modified_by: &str,
+ ) -> Result<(), SqlxError> {
+ let mut tx = self.begin_immediate_with_retry().await?;
+ // SQLite's INSERT … ON CONFLICT (sync_uuid) is the cleanest path,
+ // but the unique index is partial (WHERE sync_uuid IS NOT NULL),
+ // and partial indexes can't drive ON CONFLICT in SQLite < 3.40
+ // we don't gate on. Two-step is safer and the table is small.
+ let existing: Option<(i64,)> =
+ sqlx::query_as("SELECT id FROM memories WHERE sync_uuid = ?1 LIMIT 1")
+ .bind(sync_uuid)
+ .fetch_optional(&mut **tx.conn())
+ .await?;
+ if let Some((id,)) = existing {
+ sqlx::query(
+ "UPDATE memories SET content = ?1, source = ?2, source_context = ?3, \
+ tags = ?4, importance = ?5, created_at = ?6, \
+ updated_at = ?7, sync_modified_by = ?8 \
+ WHERE id = ?9",
+ )
+ .bind(content)
+ .bind(source)
+ .bind(source_context)
+ .bind(tags)
+ .bind(importance)
+ .bind(created_at)
+ .bind(updated_at)
+ .bind(sync_modified_by)
+ .bind(id)
+ .execute(&mut **tx.conn())
+ .await?;
+ } else {
+ sqlx::query(
+ "INSERT INTO memories (sync_uuid, content, source, source_context, tags, \
+ importance, created_at, updated_at, sync_modified_by) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
+ )
+ .bind(sync_uuid)
+ .bind(content)
+ .bind(source)
+ .bind(source_context)
+ .bind(tags)
+ .bind(importance)
+ .bind(created_at)
+ .bind(updated_at)
+ .bind(sync_modified_by)
+ .execute(&mut **tx.conn())
+ .await?;
+ }
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// Apply a remote tombstone — delete the local row matching the
+ /// uuid. No-op if not found (already deleted, or never synced).
+ pub async fn delete_memory_by_sync_uuid(&self, sync_uuid: &str) -> Result<(), SqlxError> {
+ let mut tx = self.begin_immediate_with_retry().await?;
+ sqlx::query("DELETE FROM memories WHERE sync_uuid = ?1")
+ .bind(sync_uuid)
+ .execute(&mut **tx.conn())
+ .await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// Look up a memory's sync_uuid by local id. Used by the DELETE
+ /// route to know whether to record a tombstone (skip if NULL —
+ /// the row was never published, so no other device has it).
+ pub async fn get_memory_sync_uuid(&self, id: i64) -> Result<Option<String>, SqlxError> {
+ let row: Option<(Option<String>,)> =
+ sqlx::query_as("SELECT sync_uuid FROM memories WHERE id = ?1")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.and_then(|(u,)| u))
+ }
+
#[allow(clippy::too_many_arguments)]
pub async fn list_memories(
&self,
diff --git a/crates/screenpipe-db/src/types.rs b/crates/screenpipe-db/src/types.rs
index b914171be..bf79edb75 100644
--- a/crates/screenpipe-db/src/types.rs
+++ b/crates/screenpipe-db/src/types.rs
@@ -198,6 +198,24 @@ pub struct MemoryRecord {
pub updated_at: String,
}
+/// A memory row + the columns the cross-device sync layer needs.
+/// Used only by [`DatabaseManager::list_memories_for_sync`] — the
+/// HTTP/UI surface keeps using [`MemoryRecord`] to avoid leaking
+/// sync state into the public API.
+#[derive(Debug, FromRow, Clone)]
+pub struct MemorySyncRow {
+ pub id: i64,
+ pub sync_uuid: Option<String>,
+ pub content: String,
+ pub source: String,
+ pub source_context: Option<String>,
+ pub tags: Option<String>,
+ pub importance: f64,
+ pub created_at: String,
+ pub updated_at: String,
+ pub sync_modified_by: Option<String>,
+}
+
#[derive(OaSchema, Debug, Serialize, Deserialize, FromRow, Clone)]
pub struct MeetingRecord {
pub id: i64,
diff --git a/crates/screenpipe-engine/src/routes/memories.rs b/crates/screenpipe-engine/src/routes/memories.rs
index 2f29f6a95..693cb0cd1 100644
--- a/crates/screenpipe-engine/src/routes/memories.rs
+++ b/crates/screenpipe-engine/src/routes/memories.rs
@@ -165,7 +165,8 @@ pub(crate) async fn create_memory_handler(
validate_tags(&payload.tags)?;
let tags_json = serde_json::to_string(&payload.tags).unwrap_or_else(|_| "[]".to_string());
- let source_context_json = payload.source_context.map(|v| v.to_string());
+ let enriched_ctx = enrich_source_context_with_device(payload.source_context);
+ let source_context_json = enriched_ctx.map(|v| v.to_string());
let id = state
.db
@@ -294,7 +295,14 @@ pub(crate) async fn update_memory_handler(
let tags_json = payload
.tags
.map(|t| serde_json::to_string(&t).unwrap_or_else(|_| "[]".to_string()));
- let source_context_json = payload.source_context.map(|v| v.to_string());
+ // Re-stamp `_device` on update so a row whose source_context is replaced
+ // by a caller (UI, pipe) doesn't lose its provenance. If the caller
+ // didn't pass source_context at all, leave the existing DB row alone.
+ let source_context_json = payload.source_context.map(|v| {
+ enrich_source_context_with_device(Some(v))
+ .unwrap()
+ .to_string()
+ });
state
.db
@@ -328,6 +336,13 @@ pub(crate) async fn delete_memory_handler(
State(state): State<Arc<AppState>>,
Path(id): Path<i64>,
) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
+ // If this row was already published to the cloud sync, remember the
+ // sync_uuid before we drop the row so the next push can publish a
+ // tombstone. Reads should never block the delete on failure — a
+ // missing tombstone means the deletion only takes effect locally,
+ // which is the safer outcome.
+ let sync_uuid = state.db.get_memory_sync_uuid(id).await.ok().flatten();
+
state.db.delete_memory(id).await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
@@ -335,6 +350,8 @@ pub(crate) async fn delete_memory_handler(
)
})?;
+ crate::sync_api::record_memory_tombstone(&state.screenpipe_dir, sync_uuid.as_deref());
+
Ok(JsonResponse(json!({"ok": true})))
}
@@ -350,3 +367,87 @@ pub(crate) async fn list_memory_tags_handler(
})?;
Ok(JsonResponse(tags))
}
+
+/// Stamp the originating device's stable id into a memory's
+/// `source_context` JSON. Three input shapes:
+///
+/// * `None` / `Value::Null` → `{"_device":"<machine_id>"}` (no original
+/// context to merge with).
+/// * `Value::Object(map)` → original keys preserved, `_device` added.
+/// If the caller already provided a `_device` key (rare — typically
+/// pipes don't), we overwrite it: trust the local server, not the
+/// client.
+/// * Anything else (string, number, array, bool) → wrap as
+/// `{"_value": <original>, "_device":"<machine_id>"}` so downstream
+/// consumers always see an object and can rely on `.["_device"]`.
+///
+/// We use the underscore prefix to distinguish system-managed fields
+/// from caller-provided keys; pipes that read source_context can keep
+/// reading their own keys and ignore anything starting with `_`.
+///
+/// Returns `None` only if `get_or_create_machine_id` fails to produce
+/// a stable id, which in practice never happens — the helper falls
+/// back to a fresh UUID v4 it persists. So this function effectively
+/// always returns `Some`.
+fn enrich_source_context_with_device(ctx: Option<Value>) -> Option<Value> {
+ let machine_id = screenpipe_core::sync::get_or_create_machine_id();
+ let enriched = match ctx {
+ None | Some(Value::Null) => json!({"_device": machine_id}),
+ Some(Value::Object(mut map)) => {
+ map.insert("_device".to_string(), Value::String(machine_id));
+ Value::Object(map)
+ }
+ Some(other) => json!({"_value": other, "_device": machine_id}),
+ };
+ Some(enriched)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn enrich_none_creates_device_object() {
+ let v = enrich_source_context_with_device(None).unwrap();
+ let obj = v.as_object().unwrap();
+ assert!(obj.get("_device").and_then(|v| v.as_str()).is_some());
+ assert_eq!(obj.len(), 1);
+ }
+
+ #[test]
+ fn enrich_object_preserves_caller_keys() {
+ let v = enrich_source_context_with_device(Some(json!({
+ "pipe_run_id": "abc",
+ "trigger": "manual"
+ })))
+ .unwrap();
+ let obj = v.as_object().unwrap();
+ assert_eq!(obj.get("pipe_run_id").and_then(|v| v.as_str()), Some("abc"));
+ assert_eq!(obj.get("trigger").and_then(|v| v.as_str()), Some("manual"));
+ assert!(obj.get("_device").and_then(|v| v.as_str()).is_some());
+ }
+
+ #[test]
+ fn enrich_overwrites_caller_provided_device() {
+ // A malicious or buggy caller can't impersonate another machine —
+ // server-side machine_id always wins.
+ let v = enrich_source_context_with_device(Some(json!({
+ "_device": "fake-id"
+ })))
+ .unwrap();
+ let device = v.get("_device").and_then(|v| v.as_str()).unwrap();
+ assert_ne!(device, "fake-id");
+ }
+
+ #[test]
+ fn enrich_wraps_non_object_value() {
+ // Pipes that pass a bare string get wrapped, not silently lost.
+ let v = enrich_source_context_with_device(Some(json!("raw note text"))).unwrap();
+ let obj = v.as_object().unwrap();
+ assert_eq!(
+ obj.get("_value").and_then(|v| v.as_str()),
+ Some("raw note text")
+ );
+ assert!(obj.get("_device").and_then(|v| v.as_str()).is_some());
+ }
+}
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 0559b5b06..48e6acd0d 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -612,6 +612,8 @@ impl SCServer {
.post("/sync/download", sync_api::sync_download)
.post("/sync/pipes/push", sync_api::sync_pipes_push)
.post("/sync/pipes/pull", sync_api::sync_pipes_pull)
+ .post("/sync/memories/push", sync_api::sync_memories_push)
+ .post("/sync/memories/pull", sync_api::sync_memories_pull)
// Cloud Archive API routes
.post("/archive/init", crate::archive::archive_init)
.post("/archive/configure", crate::archive::archive_configure)
diff --git a/crates/screenpipe-engine/src/sync_api.rs b/crates/screenpipe-engine/src/sync_api.rs
index f0ec09cef..7c897b282 100644
--- a/crates/screenpipe-engine/src/sync_api.rs
+++ b/crates/screenpipe-engine/src/sync_api.rs
@@ -234,6 +234,10 @@ pub async fn sync_init(
let pipe_sync_dir = state.screenpipe_dir.clone();
let pipe_sync_manager = runtime_state.manager.clone();
let pipe_sync_pipe_manager = state.pipe_manager.clone();
+ // Memories sync shares the same SyncManager (same encrypted upload pipe)
+ // and the same screenpipe_dir for the toggle file, but it talks to the
+ // db directly rather than the disk-backed pipe manager.
+ let pipe_sync_db = state.db.clone();
tokio::spawn(async move {
use crate::sync_provider::SCHEMA_VERSION;
@@ -348,6 +352,19 @@ pub async fn sync_init(
.await;
}
+ // -- Memories sync (independent toggle from pipe sync — a user
+ // might want their memories on every device but keep pipes
+ // device-local, or vice versa) --
+ if is_memories_sync_enabled(&pipe_sync_dir) {
+ run_background_memories_sync(
+ &pipe_sync_manager,
+ &pipe_sync_dir,
+ &download_machine_id,
+ &pipe_sync_db,
+ )
+ .await;
+ }
+
// Exponential backoff after 3+ consecutive failures (capped at 30 min)
let sleep_dur = if consecutive_failures >= 3 {
let exp = (consecutive_failures - 2).min(3); // 1,2,3 → 2x,4x,8x
@@ -808,6 +825,18 @@ async fn upload_pipe_manifest(
/// Check if pipe sync is enabled by reading store.bin → settings.pipeSyncEnabled.
fn is_pipe_sync_enabled(screenpipe_dir: &std::path::Path) -> bool {
+ is_settings_bool_enabled(screenpipe_dir, "pipeSyncEnabled")
+}
+
+/// Check if memories sync is enabled by reading store.bin → settings.memoriesSyncEnabled.
+fn is_memories_sync_enabled(screenpipe_dir: &std::path::Path) -> bool {
+ is_settings_bool_enabled(screenpipe_dir, "memoriesSyncEnabled")
+}
+
+/// Read `settings.<key>` as a bool from `<screenpipe_dir>/store.bin`.
+/// Returns false on any failure (missing file, corrupt JSON, missing key).
+/// Shared with pipe sync to keep both feature toggles consistent.
+fn is_settings_bool_enabled(screenpipe_dir: &std::path::Path, key: &str) -> bool {
let store_path = screenpipe_dir.join("store.bin");
let content = match std::fs::read_to_string(&store_path) {
Ok(c) => c,
@@ -819,7 +848,7 @@ fn is_pipe_sync_enabled(screenpipe_dir: &std::path::Path) -> bool {
};
store
.get("settings")
- .and_then(|s| s.get("pipeSyncEnabled"))
+ .and_then(|s| s.get(key))
.and_then(|v| v.as_bool())
.unwrap_or(false)
}
@@ -885,6 +914,405 @@ async fn run_background_pipe_sync(
}
}
+// ============================================================================
+// Memories Sync — handlers, manifest IO, background loop
+// ============================================================================
+//
+// Shape mirrors pipe sync above so the two are easy to read side-by-side:
+//
+// * download_memories_manifest / upload_memories_manifest
+// — same shape as the pipe equivalents; just swap BlobType::PipeConfig
+// for BlobType::Memories and the manifest type for MemoriesSyncManifest.
+//
+// * build_memories_local_manifest / apply_memories_manifest_to_db
+// — equivalent of build_local_manifest / apply_manifest_to_disk for
+// pipes, but driven off the SQLite memories table instead of pipe.md
+// files. Side-effects on the DB (UUID minting, INSERT/UPDATE/DELETE)
+// are confined to these two functions.
+//
+// * sync_memories_pull / sync_memories_push — HTTP routes (parity with
+// /sync/pipes/{pull,push}).
+//
+// * run_background_memories_sync — called inside the existing
+// download loop guarded by `is_memories_sync_enabled`.
+//
+// Frame ids are NEVER synced. They reference local frames that don't exist on
+// the receiving device, so `apply_memories_manifest_to_db` writes NULL for
+// frame_id on every imported row. The local `frame_id` column is preserved
+// when we update an already-known sync_uuid (so locally-attributed memories
+// keep their provenance for that user's own browsing).
+
+use screenpipe_db::DatabaseManager;
+
+const MEMORY_TOMBSTONES_FILE: &str = ".memory_sync_tombstones.json";
+
+/// Read the local tombstone log. Returns an empty map on any error.
+fn read_memory_tombstones(
+ screenpipe_dir: &std::path::Path,
+) -> std::collections::HashMap<String, String> {
+ let path = screenpipe_dir.join(MEMORY_TOMBSTONES_FILE);
+ match std::fs::read_to_string(&path) {
+ Ok(content) => serde_json::from_str(&content).unwrap_or_else(|e| {
+ warn!("memories sync: tombstones file corrupt, ignoring: {}", e);
+ std::collections::HashMap::new()
+ }),
+ Err(_) => std::collections::HashMap::new(),
+ }
+}
+
+/// Atomic write of the tombstone log (write to .tmp, rename).
+fn write_memory_tombstones(
+ screenpipe_dir: &std::path::Path,
+ tombstones: &std::collections::HashMap<String, String>,
+) -> Result<(), String> {
+ let path = screenpipe_dir.join(MEMORY_TOMBSTONES_FILE);
+ let tmp_path = screenpipe_dir.join(format!("{}.tmp", MEMORY_TOMBSTONES_FILE));
+ let json = serde_json::to_string_pretty(tombstones).map_err(|e| format!("serialize: {}", e))?;
+ std::fs::write(&tmp_path, &json).map_err(|e| format!("write tmp: {}", e))?;
+ std::fs::rename(&tmp_path, &path).map_err(|e| format!("rename: {}", e))?;
+ Ok(())
+}
+
+/// Public entrypoint for the DELETE /memories/:id route to call after
+/// committing the row deletion. No-op when the memory was never synced
+/// (sync_uuid is None) — there's nothing on any other device to delete.
+pub fn record_memory_tombstone(screenpipe_dir: &std::path::Path, sync_uuid: Option<&str>) {
+ let Some(uuid) = sync_uuid else { return };
+ let mut t = read_memory_tombstones(screenpipe_dir);
+ t.insert(uuid.to_string(), chrono::Utc::now().to_rfc3339());
+ if let Err(e) = write_memory_tombstones(screenpipe_dir, &t) {
+ warn!(
+ "memories sync: failed to record tombstone for {}: {}",
+ uuid, e
+ );
+ }
+}
+
+/// Build the manifest of local memories. Mints sync_uuid for any rows
+/// born locally that haven't been published yet, persisting back to the
+/// DB so a follow-up push won't mint a different uuid for the same row.
+async fn build_memories_local_manifest(
+ db: &Arc<DatabaseManager>,
+ screenpipe_dir: &std::path::Path,
+ machine_id: &str,
+) -> screenpipe_core::memories::sync::MemoriesSyncManifest {
+ use screenpipe_core::memories::sync::{MemoriesSyncManifest, SyncedMemory};
+
+ let mut manifest = MemoriesSyncManifest::empty(machine_id);
+
+ let rows = match db.list_memories_for_sync().await {
+ Ok(rows) => rows,
+ Err(e) => {
+ warn!("memories sync: failed to read local memories: {}", e);
+ return manifest;
+ }
+ };
+
+ for row in rows {
+ let (uuid, modified_by) = match row.sync_uuid.as_deref() {
+ Some(u) => (
+ u.to_string(),
+ row.sync_modified_by
+ .clone()
+ .unwrap_or_else(|| machine_id.to_string()),
+ ),
+ None => {
+ // First publish — mint uuid, stamp current machine as author.
+ let new_uuid = uuid::Uuid::new_v4().to_string();
+ if let Err(e) = db
+ .set_memory_sync_identity(row.id, &new_uuid, machine_id)
+ .await
+ {
+ warn!(
+ "memories sync: failed to mint sync_uuid for memory {}: {}",
+ row.id, e
+ );
+ continue;
+ }
+ (new_uuid, machine_id.to_string())
+ }
+ };
+
+ manifest.memories.insert(
+ uuid.clone(),
+ SyncedMemory {
+ sync_uuid: uuid,
+ content: row.content,
+ source: row.source,
+ source_context: row.source_context,
+ tags: row.tags.unwrap_or_else(|| "[]".to_string()),
+ importance: row.importance,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ last_modified_by: modified_by,
+ },
+ );
+ }
+
+ // Carry forward our own outstanding tombstones (deletions that haven't
+ // been confirmed by an upload yet). The merge function GCs anything
+ // older than 30 days.
+ for (uuid, ts) in read_memory_tombstones(screenpipe_dir) {
+ manifest.tombstones.entry(uuid).or_insert(ts);
+ }
+
+ manifest
+}
+
+/// Apply the merged manifest to the local DB. Each action is independent;
+/// a failure on one row is logged but doesn't abort the rest.
+async fn apply_memories_manifest_to_db(
+ db: &Arc<DatabaseManager>,
+ manifest: &screenpipe_core::memories::sync::MemoriesSyncManifest,
+ actions: &[screenpipe_core::memories::sync::MemorySyncAction],
+) -> Vec<String> {
+ use screenpipe_core::memories::sync::MemorySyncAction;
+ let mut errors = Vec::new();
+
+ for action in actions {
+ match action {
+ MemorySyncAction::Imported(uuid) | MemorySyncAction::Updated(uuid) => {
+ if let Some(m) = manifest.memories.get(uuid) {
+ if let Err(e) = db
+ .upsert_synced_memory(
+ &m.sync_uuid,
+ &m.content,
+ &m.source,
+ m.source_context.as_deref(),
+ &m.tags,
+ m.importance,
+ &m.created_at,
+ &m.updated_at,
+ &m.last_modified_by,
+ )
+ .await
+ {
+ errors.push(format!("upsert {}: {}", uuid, e));
+ }
+ }
+ }
+ MemorySyncAction::Deleted(uuid) => {
+ if let Err(e) = db.delete_memory_by_sync_uuid(uuid).await {
+ errors.push(format!("delete {}: {}", uuid, e));
+ }
+ }
+ MemorySyncAction::Skipped(_) => {}
+ }
+ }
+
+ errors
+}
+
+/// Download the latest memories manifest from the cloud. Returns an
+/// empty manifest on any failure (first-run user, network blip).
+async fn download_memories_manifest(
+ manager: &Arc<screenpipe_core::sync::SyncManager>,
+) -> screenpipe_core::memories::sync::MemoriesSyncManifest {
+ use screenpipe_core::memories::sync::MemoriesSyncManifest;
+ use screenpipe_core::sync::BlobType;
+
+ let end = chrono::Utc::now();
+ let start = end - chrono::Duration::days(365);
+
+ match manager
+ .download_by_time_range(
+ Some(start.to_rfc3339()),
+ Some(end.to_rfc3339()),
+ Some(vec![BlobType::Memories]),
+ Some(1),
+ )
+ .await
+ {
+ Ok(blobs) if !blobs.is_empty() => {
+ match serde_json::from_slice::<MemoriesSyncManifest>(&blobs[0].data) {
+ Ok(m) => {
+ info!(
+ "memories sync: downloaded manifest with {} memories, {} tombstones",
+ m.memories.len(),
+ m.tombstones.len()
+ );
+ m
+ }
+ Err(e) => {
+ warn!("memories sync: failed to deserialize manifest: {}", e);
+ MemoriesSyncManifest::empty("unknown")
+ }
+ }
+ }
+ Ok(_) => MemoriesSyncManifest::empty("unknown"),
+ Err(e) => {
+ warn!("memories sync: failed to download manifest: {}", e);
+ MemoriesSyncManifest::empty("unknown")
+ }
+ }
+}
+
+async fn upload_memories_manifest(
+ manager: &Arc<screenpipe_core::sync::SyncManager>,
+ manifest: &screenpipe_core::memories::sync::MemoriesSyncManifest,
+) -> Vec<String> {
+ use screenpipe_core::sync::BlobType;
+ let data = match serde_json::to_vec(manifest) {
+ Ok(d) => d,
+ Err(e) => return vec![format!("serialize manifest: {}", e)],
+ };
+ let now = chrono::Utc::now().to_rfc3339();
+ match manager
+ .upload(&data, BlobType::Memories, &now, &now, None)
+ .await
+ {
+ Ok(_) => vec![],
+ Err(e) => vec![format!("upload manifest: {}", e)],
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize, OaSchema)]
+pub struct MemoriesSyncResponse {
+ pub success: bool,
+ pub actions: Vec<String>,
+ pub errors: Vec<String>,
+}
+
+/// POST /sync/memories/push — build local manifest, merge with cloud,
+/// upload merged. Mirror of `sync_pipes_push`.
+#[oasgen]
+pub async fn sync_memories_push(
+ State(state): State<Arc<AppState>>,
+) -> Result<JsonResponse<MemoriesSyncResponse>, (StatusCode, JsonResponse<Value>)> {
+ use screenpipe_core::memories::sync::*;
+
+ let sync_state = state.sync_state.read().await;
+ let runtime = sync_state.as_ref().ok_or_else(|| {
+ (
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "sync not initialized"})),
+ )
+ })?;
+
+ let machine_id = &runtime.machine_id;
+ let local = build_memories_local_manifest(&state.db, &state.screenpipe_dir, machine_id).await;
+ let remote = download_memories_manifest(&runtime.manager).await;
+ let (merged, actions) = merge_manifests(&local, &remote, machine_id);
+
+ let action_strs: Vec<String> = actions.iter().map(action_str).collect();
+ let errors = upload_memories_manifest(&runtime.manager, &merged).await;
+
+ info!(
+ "memories sync push: uploaded {} memories, {} tombstones",
+ merged.memories.len(),
+ merged.tombstones.len()
+ );
+
+ Ok(JsonResponse(MemoriesSyncResponse {
+ success: errors.is_empty(),
+ actions: action_strs,
+ errors,
+ }))
+}
+
+/// POST /sync/memories/pull — download cloud manifest, merge with local,
+/// apply to DB, push merged back. Mirror of `sync_pipes_pull`.
+#[oasgen]
+pub async fn sync_memories_pull(
+ State(state): State<Arc<AppState>>,
+) -> Result<JsonResponse<MemoriesSyncResponse>, (StatusCode, JsonResponse<Value>)> {
+ use screenpipe_core::memories::sync::*;
+
+ let sync_state = state.sync_state.read().await;
+ let runtime = sync_state.as_ref().ok_or_else(|| {
+ (
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "sync not initialized"})),
+ )
+ })?;
+
+ let machine_id = &runtime.machine_id;
+ let remote = download_memories_manifest(&runtime.manager).await;
+ let local = build_memories_local_manifest(&state.db, &state.screenpipe_dir, machine_id).await;
+ let (merged, actions) = merge_manifests(&local, &remote, machine_id);
+
+ let action_strs: Vec<String> = actions.iter().map(action_str).collect();
+ let mut errors = apply_memories_manifest_to_db(&state.db, &merged, &actions).await;
+
+ // Confirmed deletes — drop from the local tombstone log so we don't
+ // re-publish them forever. (The merged manifest now carries them, so
+ // every other device will see the tombstone via the cloud copy.)
+ if actions
+ .iter()
+ .any(|a| matches!(a, MemorySyncAction::Deleted(_)))
+ {
+ let mut t = read_memory_tombstones(&state.screenpipe_dir);
+ for a in &actions {
+ if let MemorySyncAction::Deleted(uuid) = a {
+ t.remove(uuid);
+ }
+ }
+ if let Err(e) = write_memory_tombstones(&state.screenpipe_dir, &t) {
+ errors.push(format!("clear tombstones: {}", e));
+ }
+ }
+
+ errors.extend(upload_memories_manifest(&runtime.manager, &merged).await);
+
+ info!(
+ "memories sync pull: applied {} actions, {} errors",
+ action_strs.len(),
+ errors.len()
+ );
+
+ Ok(JsonResponse(MemoriesSyncResponse {
+ success: errors.is_empty(),
+ actions: action_strs,
+ errors,
+ }))
+}
+
+/// Run a full pull-merge-push cycle from the background loop.
+async fn run_background_memories_sync(
+ manager: &Arc<screenpipe_core::sync::SyncManager>,
+ screenpipe_dir: &std::path::Path,
+ machine_id: &str,
+ db: &Arc<DatabaseManager>,
+) {
+ use screenpipe_core::memories::sync::*;
+
+ let remote = download_memories_manifest(manager).await;
+ let local = build_memories_local_manifest(db, screenpipe_dir, machine_id).await;
+ let (merged, actions) = merge_manifests(&local, &remote, machine_id);
+
+ let errors = apply_memories_manifest_to_db(db, &merged, &actions).await;
+ for err in &errors {
+ warn!("memories sync background: {}", err);
+ }
+
+ let upload_errors = upload_memories_manifest(manager, &merged).await;
+ for err in &upload_errors {
+ warn!("memories sync background: {}", err);
+ }
+
+ let changed = actions
+ .iter()
+ .filter(|a| !matches!(a, MemorySyncAction::Skipped(_)))
+ .count();
+ if changed > 0 {
+ info!(
+ "memories sync background: {} changes applied ({} memories total)",
+ changed,
+ merged.memories.len()
+ );
+ }
+}
+
+fn action_str(a: &screenpipe_core::memories::sync::MemorySyncAction) -> String {
+ use screenpipe_core::memories::sync::MemorySyncAction;
+ match a {
+ MemorySyncAction::Imported(u) => format!("imported: {}", u),
+ MemorySyncAction::Updated(u) => format!("updated: {}", u),
+ MemorySyncAction::Deleted(u) => format!("deleted: {}", u),
+ MemorySyncAction::Skipped(u) => format!("skipped: {}", u),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;