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

fix(activity): recover previews from linked events (#6798)

Ezra Ellettea8c4b90042f2
diff --git a/crates/screenpipe-db/src/db/search.rs b/crates/screenpipe-db/src/db/search.rs
index 81f894a4c..b18061f69 100644
--- a/crates/screenpipe-db/src/db/search.rs
+++ b/crates/screenpipe-db/src/db/search.rs
@@ -1561,6 +1561,8 @@ impl DatabaseManager {
///
/// Domain-filtered queries retain one candidate per URL so exact host
/// validation cannot discard another URL from the same bucket.
+ /// Frame attribution remains authoritative; blank frame attribution falls
+ /// back to the latest named UI event directly linked to that frame.
pub async fn get_frame_preview_candidates(
&self,
start: DateTime<Utc>,
@@ -1579,107 +1581,89 @@ impl DatabaseManager {
SqlxError,
> {
let mut connection = self.acquire_search_read().await?;
- let rows = if let Some(domain) = browser_domain {
- sqlx::query_as::<
- _,
- (
- i64,
- DateTime<Utc>,
- Option<String>,
- String,
- Option<i64>,
- Option<f64>,
- ),
- >(
- r#"
- WITH bucketed AS (
- SELECT
- f.id,
- f.timestamp,
- f.browser_url,
- COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) AS source_path,
- CASE WHEN NULLIF(f.snapshot_path, '') IS NULL THEN vc.id END AS video_chunk_id,
- CASE
- WHEN NULLIF(f.snapshot_path, '') IS NULL
- THEN CAST(f.offset_index AS REAL) / MAX(COALESCE(vc.fps, 0.5), 0.001)
- END AS video_offset_seconds,
- ROW_NUMBER() OVER (
- PARTITION BY
- CAST(unixepoch(f.timestamp) / 10 AS INTEGER),
- COALESCE(f.browser_url, '')
- ORDER BY f.timestamp, f.id
- ) AS bucket_rank
- FROM frames f
- LEFT JOIN video_chunks vc ON f.video_chunk_id = vc.id
- WHERE f.app_name = ?1
- AND f.timestamp >= ?2
- AND f.timestamp <= ?3
- AND f.focused = 1
- AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) IS NOT NULL
- AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) NOT LIKE 'cloud://%'
- AND instr(lower(COALESCE(f.browser_url, '')), lower(?4)) > 0
- )
- SELECT id, timestamp, browser_url, source_path, video_chunk_id, video_offset_seconds
- FROM bucketed
- WHERE bucket_rank = 1
- ORDER BY timestamp, id
- "#,
- )
- .bind(app_name)
- .bind(start)
- .bind(end)
- .bind(domain)
- .fetch_all(&mut *connection)
- .await?
- } else {
- sqlx::query_as::<
- _,
- (
- i64,
- DateTime<Utc>,
- Option<String>,
- String,
- Option<i64>,
- Option<f64>,
- ),
- >(
- r#"
- WITH bucketed AS (
- SELECT
- f.id,
- f.timestamp,
- f.browser_url,
- COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) AS source_path,
- CASE WHEN NULLIF(f.snapshot_path, '') IS NULL THEN vc.id END AS video_chunk_id,
- CASE
- WHEN NULLIF(f.snapshot_path, '') IS NULL
- THEN CAST(f.offset_index AS REAL) / MAX(COALESCE(vc.fps, 0.5), 0.001)
- END AS video_offset_seconds,
- ROW_NUMBER() OVER (
- PARTITION BY CAST(unixepoch(f.timestamp) / 10 AS INTEGER)
- ORDER BY f.timestamp, f.id
- ) AS bucket_rank
- FROM frames f
- LEFT JOIN video_chunks vc ON f.video_chunk_id = vc.id
- WHERE f.app_name = ?1
- AND f.timestamp >= ?2
- AND f.timestamp <= ?3
- AND f.focused = 1
- AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) IS NOT NULL
- AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) NOT LIKE 'cloud://%'
- )
- SELECT id, timestamp, browser_url, source_path, video_chunk_id, video_offset_seconds
- FROM bucketed
- WHERE bucket_rank = 1
- ORDER BY timestamp, id
- "#,
+ let rows = sqlx::query_as::<
+ _,
+ (
+ i64,
+ DateTime<Utc>,
+ Option<String>,
+ String,
+ Option<i64>,
+ Option<f64>,
+ ),
+ >(
+ r#"
+ WITH candidates AS (
+ SELECT
+ f.id,
+ f.timestamp,
+ f.browser_url,
+ COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) AS source_path,
+ CASE WHEN NULLIF(f.snapshot_path, '') IS NULL THEN vc.id END AS video_chunk_id,
+ CASE
+ WHEN NULLIF(f.snapshot_path, '') IS NULL
+ THEN CAST(f.offset_index AS REAL) / MAX(COALESCE(vc.fps, 0.5), 0.001)
+ END AS video_offset_seconds
+ FROM frames f
+ LEFT JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ WHERE f.app_name = ?1
+ AND f.timestamp >= ?2
+ AND f.timestamp <= ?3
+ AND f.focused = 1
+ AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) IS NOT NULL
+ AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) NOT LIKE 'cloud://%'
+ UNION ALL
+ SELECT
+ f.id,
+ f.timestamp,
+ u.browser_url,
+ COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) AS source_path,
+ CASE WHEN NULLIF(f.snapshot_path, '') IS NULL THEN vc.id END AS video_chunk_id,
+ CASE
+ WHEN NULLIF(f.snapshot_path, '') IS NULL
+ THEN CAST(f.offset_index AS REAL) / MAX(COALESCE(vc.fps, 0.5), 0.001)
+ END AS video_offset_seconds
+ FROM ui_events u
+ JOIN frames f ON f.id = u.frame_id
+ LEFT JOIN video_chunks vc ON f.video_chunk_id = vc.id
+ WHERE u.app_name = ?1
+ AND f.timestamp >= ?2
+ AND f.timestamp <= ?3
+ AND (f.app_name IS NULL OR f.app_name = '')
+ AND u.id = (
+ SELECT latest.id
+ FROM ui_events latest
+ WHERE latest.frame_id = f.id
+ AND latest.app_name IS NOT NULL
+ AND latest.app_name != ''
+ ORDER BY latest.timestamp DESC, latest.id DESC
+ LIMIT 1
+ )
+ AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) IS NOT NULL
+ AND COALESCE(NULLIF(f.snapshot_path, ''), vc.file_path) NOT LIKE 'cloud://%'
+ ), bucketed AS (
+ SELECT *, ROW_NUMBER() OVER (
+ PARTITION BY
+ CAST(unixepoch(timestamp) / 10 AS INTEGER),
+ CASE WHEN ?4 IS NULL THEN '' ELSE COALESCE(browser_url, '') END
+ ORDER BY timestamp, id
+ ) AS bucket_rank
+ FROM candidates
+ WHERE ?4 IS NULL
+ OR instr(lower(COALESCE(browser_url, '')), lower(?4)) > 0
)
- .bind(app_name)
- .bind(start)
- .bind(end)
- .fetch_all(&mut *connection)
- .await?
- };
+ SELECT id, timestamp, browser_url, source_path, video_chunk_id, video_offset_seconds
+ FROM bucketed
+ WHERE bucket_rank = 1
+ ORDER BY timestamp, id
+ "#,
+ )
+ .bind(app_name)
+ .bind(start)
+ .bind(end)
+ .bind(browser_domain)
+ .fetch_all(&mut *connection)
+ .await?;
drop(connection);
Ok(rows)
}
diff --git a/crates/screenpipe-db/src/db/tests.rs b/crates/screenpipe-db/src/db/tests.rs
index e43c0287c..979fb8160 100644
--- a/crates/screenpipe-db/src/db/tests.rs
+++ b/crates/screenpipe-db/src/db/tests.rs
@@ -697,12 +697,36 @@ async fn frame_preview_candidates_are_bucketed_indexed_and_reuse_existing_media(
.execute(&db.pool)
.await
.unwrap();
+ let fallback_frame_id = sqlx::query(
+ "INSERT INTO frames (timestamp, video_chunk_id, offset_index, focused) \
+ VALUES ('2026-08-20T10:00:47Z', ?1, 2, 0)",
+ )
+ .bind(chunk_id)
+ .execute(&db.pool)
+ .await
+ .unwrap()
+ .last_insert_rowid();
+ sqlx::query(
+ "INSERT INTO ui_events (timestamp, event_type, app_name, browser_url, frame_id) \
+ VALUES ('2026-08-20T10:00:47Z', 'window_focus', 'Arc', \
+ 'https://github.com/linked-event', ?1)",
+ )
+ .bind(fallback_frame_id)
+ .execute(&db.pool)
+ .await
+ .unwrap();
let app_candidates = db
.get_frame_preview_candidates(start, end, "Arc", None)
.await
.unwrap();
- assert_eq!(app_candidates.len(), 4);
+ assert_eq!(app_candidates.len(), 5);
+ let fallback = app_candidates
+ .iter()
+ .find(|candidate| candidate.0 == fallback_frame_id)
+ .unwrap();
+ assert_eq!(fallback.4, Some(chunk_id));
+ assert_eq!(fallback.5, Some(1.0));
let video = app_candidates.last().unwrap();
assert_eq!(video.4, Some(chunk_id));
assert_eq!(video.5, Some(2.0));
@@ -713,7 +737,7 @@ async fn frame_preview_candidates_are_bucketed_indexed_and_reuse_existing_media(
.unwrap();
// The SQL predicate is deliberately coarse and index-friendly; the HTTP
// layer parses these URLs and removes the path-only false positive.
- assert_eq!(domain_candidates.len(), 5);
+ assert_eq!(domain_candidates.len(), 6);
assert!(domain_candidates
.iter()
.all(|(_, _, url, _, _, _)| url.as_deref().unwrap().contains("github.com")));
diff --git a/crates/screenpipe-engine/tests/endpoint_test.rs b/crates/screenpipe-engine/tests/endpoint_test.rs
index 4e5d01635..48841ae2f 100644
--- a/crates/screenpipe-engine/tests/endpoint_test.rs
+++ b/crates/screenpipe-engine/tests/endpoint_test.rs
@@ -226,6 +226,60 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn activity_preview_uses_linked_event_when_frame_attribution_is_blank() {
+ let (app, db) = setup_test_app().await;
+ let temp_dir = tempfile::tempdir().unwrap();
+ let media_path = temp_dir.path().join("preview-linked-event.mp4");
+ std::fs::write(&media_path, b"existing-compacted-media").unwrap();
+ let chunk_id = db
+ .insert_video_chunk_with_fps(
+ media_path.to_string_lossy().as_ref(),
+ "preview-monitor",
+ 2.0,
+ )
+ .await
+ .unwrap();
+ let frame_id = sqlx::query(
+ "INSERT INTO frames \
+ (timestamp, app_name, video_chunk_id, offset_index, focused) \
+ VALUES ('2026-08-20T10:00:10Z', '', ?1, 4, 0)",
+ )
+ .bind(chunk_id)
+ .execute(&db.pool)
+ .await
+ .unwrap()
+ .last_insert_rowid();
+ sqlx::query(
+ "INSERT INTO ui_events \
+ (timestamp, event_type, app_name, browser_url, frame_id) \
+ VALUES ('2026-08-20T10:00:10Z', 'window_focus', 'Arc', \
+ 'https://example.com/work', ?1)",
+ )
+ .bind(frame_id)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+
+ let samples = app
+ .oneshot(
+ Request::builder()
+ .uri("/frames/preview-samples?start_time=2026-08-20T10%3A00%3A00Z&end_time=2026-08-20T10%3A01%3A00Z&app_name=Arc&browser_domain=example.com&limit=6")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(samples.status(), StatusCode::OK);
+ let payload: serde_json::Value =
+ serde_json::from_slice(&to_bytes(samples.into_body(), usize::MAX).await.unwrap())
+ .unwrap();
+ assert_eq!(payload["frames"][0]["frame_id"], frame_id);
+ assert_eq!(payload["frames"][0]["source"], "video");
+ assert_eq!(payload["frames"][0]["video_chunk_id"], chunk_id);
+ assert_eq!(payload["frames"][0]["video_offset_seconds"], "2.000000");
+ }
+
#[tokio::test]
async fn frame_thumbnail_endpoint_can_disable_nearby_fallback() {
let (app, db) = setup_test_app().await;