Skip to content

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

feat: element dedup at write time + bump app to v2.2.175

Louis Beaumont1403800a32a8
diff --git a/Cargo.lock b/Cargo.lock
index 237c7e702..2e52750a9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6513,7 +6513,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"anyhow",
"audiopipe",
@@ -6572,7 +6572,7 @@ dependencies = [
[[package]]
name = "screenpipe-config"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -6585,7 +6585,7 @@ dependencies = [
[[package]]
name = "screenpipe-connect"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"anyhow",
"async-trait",
@@ -6611,7 +6611,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -6654,7 +6654,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"anyhow",
"chrono",
@@ -6679,7 +6679,7 @@ dependencies = [
[[package]]
name = "screenpipe-engine"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"anyhow",
"async-trait",
@@ -6747,7 +6747,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"anyhow",
"chrono",
@@ -6765,7 +6765,7 @@ dependencies = [
[[package]]
name = "screenpipe-screen"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"accessibility-sys",
"anyhow",
@@ -6805,7 +6805,7 @@ dependencies = [
[[package]]
name = "screenpipe-vault"
-version = "0.3.186"
+version = "0.3.187"
dependencies = [
"argon2",
"chacha20poly1305",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index bed42f57e..98f0b44cd 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.2.174"
+version = "2.2.175"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 2e5993944..70bb9f6e0 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -330,6 +330,7 @@ impl DatabaseManager {
("accessibility_tree_json", "TEXT DEFAULT NULL"),
("content_hash", "INTEGER DEFAULT NULL"),
("simhash", "INTEGER DEFAULT NULL"),
+ ("elements_ref_frame_id", "INTEGER DEFAULT NULL"),
];
for (col_name, col_type) in missing_columns {
@@ -1418,6 +1419,7 @@ impl DatabaseManager {
content_hash,
simhash,
None,
+ None, // elements_ref_frame_id
)
.await
}
@@ -1744,6 +1746,7 @@ impl DatabaseManager {
content_hash: Option<i64>,
simhash: Option<i64>,
ocr_data: Option<(&str, &str, &str)>, // (text, text_json, ocr_engine)
+ elements_ref_frame_id: Option<i64>,
) -> Result<i64, sqlx::Error> {
use crate::write_queue::{WriteOp, WriteResult};
@@ -1789,6 +1792,7 @@ impl DatabaseManager {
ocr_text_json: ocr_data.map(|(_, j, _)| j.to_string()),
ocr_engine: ocr_data.map(|(_, _, e)| e.to_string()),
full_text,
+ elements_ref_frame_id,
})
.await?;
@@ -4022,6 +4026,62 @@ impl DatabaseManager {
.await?;
let ocr_deleted = ocr_result.rows_affected();
+ // 4b. Migrate elements from anchor frames being deleted that are referenced
+ // by frames outside the delete range. For each such anchor, move its elements
+ // to the first referencing frame and update all references.
+ let anchor_ids: Vec<i64> = sqlx::query_scalar(
+ r#"SELECT DISTINCT f.id FROM frames f
+ WHERE f.timestamp BETWEEN ?1 AND ?2
+ AND EXISTS (
+ SELECT 1 FROM frames ref
+ WHERE ref.elements_ref_frame_id = f.id
+ AND ref.timestamp NOT BETWEEN ?1 AND ?2
+ )"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+
+ for anchor_id in &anchor_ids {
+ // Find the first referencing frame outside the delete range
+ let new_anchor_id: Option<i64> = sqlx::query_scalar(
+ r#"SELECT MIN(id) FROM frames
+ WHERE elements_ref_frame_id = ?1
+ AND timestamp NOT BETWEEN ?2 AND ?3"#,
+ )
+ .bind(anchor_id)
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_optional(&mut **tx.conn())
+ .await?
+ .flatten();
+
+ if let Some(new_id) = new_anchor_id {
+ // Move elements to the new anchor frame
+ sqlx::query("UPDATE elements SET frame_id = ?1 WHERE frame_id = ?2")
+ .bind(new_id)
+ .bind(anchor_id)
+ .execute(&mut **tx.conn())
+ .await?;
+ // Update all references to point to new anchor
+ sqlx::query(
+ "UPDATE frames SET elements_ref_frame_id = ?1 WHERE elements_ref_frame_id = ?2",
+ )
+ .bind(new_id)
+ .bind(anchor_id)
+ .execute(&mut **tx.conn())
+ .await?;
+ // Clear ref on the new anchor (it now owns the elements)
+ sqlx::query(
+ "UPDATE frames SET elements_ref_frame_id = NULL WHERE id = ?1",
+ )
+ .bind(new_id)
+ .execute(&mut **tx.conn())
+ .await?;
+ }
+ }
+
// 5. Delete frames — triggers frames_fts delete; vision_tags CASCADE'd automatically
let frames_result = sqlx::query("DELETE FROM frames WHERE timestamp BETWEEN ?1 AND ?2")
.bind(&start_str)
@@ -4846,18 +4906,30 @@ LIMIT ? OFFSET ?
/// Get all elements for a single frame, ordered by sort_order.
/// Returns the full tree; clients reconstruct hierarchy from `parent_id`/`depth`.
+ ///
+ /// If the frame has `elements_ref_frame_id` set (element dedup), this follows
+ /// the reference and returns elements from the anchor frame instead.
pub async fn get_frame_elements(
&self,
frame_id: i64,
source: Option<&ElementSource>,
) -> Result<Vec<Element>, sqlx::Error> {
+ // Check if this frame references another frame's elements
+ let effective_frame_id: i64 = sqlx::query_scalar(
+ "SELECT COALESCE(elements_ref_frame_id, id) FROM frames WHERE id = ?1",
+ )
+ .bind(frame_id)
+ .fetch_optional(&self.pool)
+ .await?
+ .unwrap_or(frame_id);
+
let sql = if source.is_some() {
"SELECT id, frame_id, source, role, text, parent_id, depth, left_bound, top_bound, width_bound, height_bound, confidence, sort_order FROM elements WHERE frame_id = ?1 AND source = ?2 ORDER BY sort_order"
} else {
"SELECT id, frame_id, source, role, text, parent_id, depth, left_bound, top_bound, width_bound, height_bound, confidence, sort_order FROM elements WHERE frame_id = ?1 ORDER BY sort_order"
};
- let mut query = sqlx::query_as::<_, ElementRow>(sql).bind(frame_id);
+ let mut query = sqlx::query_as::<_, ElementRow>(sql).bind(effective_frame_id);
if let Some(src) = source {
query = query.bind(src.to_string());
}
diff --git a/crates/screenpipe-db/src/migrations/20260318000000_add_elements_ref_frame_id.sql b/crates/screenpipe-db/src/migrations/20260318000000_add_elements_ref_frame_id.sql
new file mode 100644
index 000000000..9624bed31
--- /dev/null
+++ b/crates/screenpipe-db/src/migrations/20260318000000_add_elements_ref_frame_id.sql
@@ -0,0 +1,4 @@
+-- Add elements_ref_frame_id to frames table for element deduplication.
+-- When consecutive frames from the same device have identical content_hash,
+-- the new frame references the previous frame's elements instead of inserting duplicates.
+ALTER TABLE frames ADD COLUMN elements_ref_frame_id INTEGER DEFAULT NULL;
diff --git a/crates/screenpipe-db/src/write_queue.rs b/crates/screenpipe-db/src/write_queue.rs
index dc4735f38..46d614b60 100644
--- a/crates/screenpipe-db/src/write_queue.rs
+++ b/crates/screenpipe-db/src/write_queue.rs
@@ -93,6 +93,9 @@ pub(crate) enum WriteOp {
ocr_engine: Option<String>,
/// Pre-computed full_text for FTS indexing
full_text: Option<String>,
+ /// When Some, this frame references another frame's elements (dedup).
+ /// The frame row is still inserted but element insertions are skipped.
+ elements_ref_frame_id: Option<i64>,
},
InsertVideoChunkWithFps {
file_path: String,
@@ -569,18 +572,21 @@ async fn execute_single_write(
ocr_text_json,
ocr_engine,
full_text,
+ elements_ref_frame_id,
} => {
let id = sqlx::query(
r#"INSERT INTO frames (
video_chunk_id, offset_index, timestamp, name,
browser_url, app_name, window_name, focused, device_name,
snapshot_path, capture_trigger, accessibility_text, text_source,
- accessibility_tree_json, content_hash, simhash, full_text
+ accessibility_tree_json, content_hash, simhash, full_text,
+ elements_ref_frame_id
) VALUES (
NULL, 0, ?1, ?2,
?3, ?4, ?5, ?6, ?7,
?8, ?9, ?10, ?11,
- ?12, ?13, ?14, ?15
+ ?12, ?13, ?14, ?15,
+ ?16
)"#,
)
.bind(timestamp)
@@ -598,11 +604,12 @@ async fn execute_single_write(
.bind(content_hash)
.bind(simhash)
.bind(full_text.as_deref())
+ .bind(elements_ref_frame_id)
.execute(&mut **conn)
.await?
.last_insert_rowid();
- // Insert OCR text in same transaction
+ // Insert OCR text in same transaction (always — needed for search)
if let (Some(text), Some(text_json), Some(engine)) = (
ocr_text.as_deref(),
ocr_text_json.as_deref(),
@@ -620,18 +627,29 @@ async fn execute_single_write(
.execute(&mut **conn)
.await?;
- // Dual-write OCR elements
- crate::db::DatabaseManager::insert_ocr_elements(conn, id, text_json).await;
+ // Skip OCR element insertion when referencing another frame's elements
+ if elements_ref_frame_id.is_none() {
+ crate::db::DatabaseManager::insert_ocr_elements(conn, id, text_json).await;
+ }
}
- // Dual-write accessibility elements
- if let Some(tree_json) = accessibility_tree_json.as_deref() {
- if !tree_json.is_empty() {
- crate::db::DatabaseManager::insert_accessibility_elements(conn, id, tree_json)
- .await;
+ // Skip accessibility element insertion when referencing another frame's elements
+ if elements_ref_frame_id.is_none() {
+ if let Some(tree_json) = accessibility_tree_json.as_deref() {
+ if !tree_json.is_empty() {
+ crate::db::DatabaseManager::insert_accessibility_elements(conn, id, tree_json)
+ .await;
+ }
}
}
+ if let Some(ref_id) = elements_ref_frame_id {
+ debug!(
+ "elements dedup: frame {} references {} (same content_hash)",
+ id, ref_id
+ );
+ }
+
debug!(
"write_queue: insert_snapshot_frame: id={}, trigger={:?}",
id, capture_trigger
@@ -949,7 +967,8 @@ mod tests {
accessibility_tree_json TEXT,
content_hash INTEGER,
simhash INTEGER,
- full_text TEXT
+ full_text TEXT,
+ elements_ref_frame_id INTEGER DEFAULT NULL
)",
)
.execute(&pool)
@@ -1222,6 +1241,7 @@ mod tests {
ocr_text_json: None,
ocr_engine: None,
full_text: Some("page content".to_string()),
+ elements_ref_frame_id: None,
})
.await
.unwrap();
diff --git a/crates/screenpipe-engine/src/event_driven_capture.rs b/crates/screenpipe-engine/src/event_driven_capture.rs
index 5f7540301..8232a2254 100644
--- a/crates/screenpipe-engine/src/event_driven_capture.rs
+++ b/crates/screenpipe-engine/src/event_driven_capture.rs
@@ -20,6 +20,7 @@ use screenpipe_screen::frame_comparison::{FrameComparer, FrameComparisonConfig};
use screenpipe_screen::monitor::SafeMonitor;
use screenpipe_screen::snapshot_writer::SnapshotWriter;
use screenpipe_screen::utils::capture_monitor_image;
+use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -242,6 +243,10 @@ pub async fn event_driven_capture_loop(
// Track last successful DB write time — dedup is bypassed after 30s
// to guarantee the timeline always has periodic entries
let mut last_db_write = Instant::now();
+ // Per-device elements dedup cache: device_name → (last_frame_id, last_content_hash)
+ // When consecutive frames have the same content_hash, we skip inserting elements
+ // and reference the previous frame's elements instead.
+ let mut last_elements_cache: HashMap<String, (i64, i64)> = HashMap::new();
// Debounce consecutive capture errors — log error! once on first failure,
// then suppress until success. Prevents monitor disconnect from flooding
// Sentry with 100k+ identical events.
@@ -265,6 +270,7 @@ pub async fn event_driven_capture_loop(
use_pii_removal,
None, // first capture — no previous hash
last_db_write,
+ None, // first capture — no elements ref
)
.await
{
@@ -276,6 +282,10 @@ pub async fn event_driven_capture_loop(
if let Some(ref result) = output.result {
last_content_hash = result.content_hash;
last_db_write = Instant::now();
+ // Update elements cache for this device (first frame = anchor)
+ if let Some(hash) = result.content_hash {
+ last_elements_cache.insert(device_name.clone(), (result.frame_id, hash));
+ }
vision_metrics.record_capture();
vision_metrics.record_db_write(Duration::from_millis(result.duration_ms));
if let Some(ref cache) = hot_frame_cache {
@@ -386,6 +396,8 @@ pub async fn event_driven_capture_loop(
CaptureTrigger::AppSwitch { .. } | CaptureTrigger::WindowFocus { .. }
) {
last_content_hash = None;
+ // Also reset elements cache on context change
+ last_elements_cache.remove(&device_name);
}
if state.can_capture() {
@@ -393,6 +405,24 @@ pub async fn event_driven_capture_loop(
// This keeps health "ok" even if the DB write below times out.
vision_metrics.record_capture_attempt();
+ // Compute elements_ref for frame-to-frame element dedup.
+ // If the current content_hash matches the previous frame's hash
+ // for this device, reference that frame's elements instead of
+ // inserting duplicate element rows.
+ let elements_ref = if let Some(hash) = last_content_hash {
+ if let Some(&(prev_frame_id, prev_hash)) = last_elements_cache.get(&device_name) {
+ if hash == prev_hash && hash != 0 {
+ Some(prev_frame_id)
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
// Timeout prevents the capture loop from blocking indefinitely
// if the DB is truly stuck. 15s is generous — normal captures take
// 1-3s on debug builds. The semaphore serializes writes so they
@@ -410,6 +440,7 @@ pub async fn event_driven_capture_loop(
use_pii_removal,
last_content_hash,
last_db_write,
+ elements_ref,
),
)
.await;
@@ -437,6 +468,18 @@ pub async fn event_driven_capture_loop(
// Full capture — update hash, metrics, cache
last_content_hash = result.content_hash;
last_db_write = Instant::now();
+
+ // Update elements cache: only when we inserted new elements
+ // (not when we referenced another frame's elements)
+ if !output.elements_deduped {
+ if let Some(hash) = result.content_hash {
+ last_elements_cache.insert(
+ device_name.clone(),
+ (result.frame_id, hash),
+ );
+ }
+ }
+
vision_metrics.record_capture();
vision_metrics
.record_db_write(Duration::from_millis(result.duration_ms));
@@ -446,11 +489,12 @@ pub async fn event_driven_capture_loop(
}
debug!(
- "event capture: trigger={}, frame_id={}, text_source={:?}, dur={}ms",
+ "event capture: trigger={}, frame_id={}, text_source={:?}, dur={}ms, elements_deduped={}",
trigger.as_str(),
result.frame_id,
result.text_source,
- result.duration_ms
+ result.duration_ms,
+ output.elements_deduped
);
} else {
// Content dedup or window filter — capture skipped
@@ -548,6 +592,8 @@ struct CaptureOutput {
/// The captured image — reused for frame comparer update to avoid taking
/// a redundant extra screenshot after each capture.
image: image::DynamicImage,
+ /// Whether elements were deduped (referenced another frame's elements).
+ elements_deduped: bool,
}
fn resolve_capture_metadata(
@@ -609,6 +655,7 @@ async fn do_capture(
use_pii_removal: bool,
previous_content_hash: Option<i64>,
last_db_write: Instant,
+ elements_ref_frame_id: Option<i64>,
) -> Result<CaptureOutput> {
let captured_at = Utc::now();
@@ -639,6 +686,7 @@ async fn do_capture(
return Ok(CaptureOutput {
result: None,
image,
+ elements_deduped: false,
});
}
TreeWalkResult::NotFound => None,
@@ -665,6 +713,7 @@ async fn do_capture(
return Ok(CaptureOutput {
result: None,
image,
+ elements_deduped: false,
});
}
}
@@ -694,6 +743,7 @@ async fn do_capture(
return Ok(CaptureOutput {
result: None,
image,
+ elements_deduped: false,
});
} else if crate::sleep_monitor::screen_is_locked() {
// Screen was marked locked but now a real app is focused — unlock
@@ -714,6 +764,7 @@ async fn do_capture(
return Ok(CaptureOutput {
result: None,
image,
+ elements_deduped: false,
});
}
@@ -730,15 +781,18 @@ async fn do_capture(
focused: true, // event-driven captures are always for the focused window
capture_trigger: trigger.as_str(),
use_pii_removal,
+ elements_ref_frame_id,
};
let result = paired_capture(&ctx, tree_snapshot.as_ref()).await?;
+ let deduped = elements_ref_frame_id.is_some();
// Extract image from Arc for comparer reuse. Arc::try_unwrap succeeds
// because paired_capture no longer retains a clone.
let image = Arc::try_unwrap(ctx.image).unwrap_or_else(|arc| (*arc).clone());
Ok(CaptureOutput {
result: Some(result),
image,
+ elements_deduped: deduped,
})
}
diff --git a/crates/screenpipe-engine/src/paired_capture.rs b/crates/screenpipe-engine/src/paired_capture.rs
index e1a2a3565..77542231f 100644
--- a/crates/screenpipe-engine/src/paired_capture.rs
+++ b/crates/screenpipe-engine/src/paired_capture.rs
@@ -44,6 +44,8 @@ pub struct CaptureContext<'a> {
pub focused: bool,
pub capture_trigger: &'a str,
pub use_pii_removal: bool,
+ /// When Some, this frame references another frame's elements (dedup).
+ pub elements_ref_frame_id: Option<i64>,
}
/// Result of a paired capture operation.
@@ -282,6 +284,7 @@ pub async fn paired_capture(
content_hash,
simhash,
ocr_data,
+ ctx.elements_ref_frame_id,
)
.await?;
@@ -550,6 +553,7 @@ mod tests {
focused: true,
capture_trigger: "click",
use_pii_removal: false,
+ elements_ref_frame_id: None,
};
let result = paired_capture(&ctx, None).await.unwrap();
@@ -583,6 +587,7 @@ mod tests {
focused: true,
capture_trigger: "app_switch",
use_pii_removal: false,
+ elements_ref_frame_id: None,
};
let snap = TreeSnapshot {
@@ -639,6 +644,7 @@ mod tests {
focused: true,
capture_trigger: "idle",
use_pii_removal: false,
+ elements_ref_frame_id: None,
};
// Empty accessibility text should be treated as no text