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
fix(search): sort results by timestamp, fix timeline jump-to-beginning bugs
Louis Beaumont25cbdc6bd9e6
diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline.tsxindex 1307f7a2b..8fa4980fc 100644--- a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx@@ -278,16 +278,16 @@ export default function Timeline() {// Auto-select first frame when frames arrive and no frame is selected// Skip during intentional navigation (day change) to prevent double-jumpuseEffect(() => {- // Don't auto-select during navigation OR if there's a pending navigation+ // Don't auto-select during navigation, pending navigation, or active seeking// The pending navigation effect handles frame selection during navigation- if (isNavigatingRef.current || pendingNavigationRef.current) {+ if (isNavigatingRef.current || pendingNavigationRef.current || seekingTimestamp) {return;}if (!currentFrame && frames.length > 0) {setCurrentFrame(frames[0]);setCurrentIndex(0);}- }, [frames.length, currentFrame, setCurrentFrame]);+ }, [frames.length, currentFrame, setCurrentFrame, seekingTimestamp]);// Track timeline opened and setup session trackinguseEffect(() => {@@ -657,10 +657,13 @@ export default function Timeline() {const jumpToTime = (targetDate: Date) => {// Find the closest frame to the target date- if (frames.length === 0) return;+ if (frames.length === 0) {+ console.warn("[jumpToTime] No frames loaded, cannot jump");+ return;+ }const targetTime = targetDate.getTime();- let closestIndex = 0;+ let closestIndex = -1;let closestDiff = Infinity;frames.forEach((frame, index) => {@@ -672,6 +675,13 @@ export default function Timeline() {}});+ if (closestIndex < 0) {+ console.warn("[jumpToTime] No matching frame found");+ return;+ }++ console.log(`[jumpToTime] Jumping to index ${closestIndex}, diff=${Math.round(closestDiff / 1000)}s from target`);+// Update cursor positionsetCurrentIndex(closestIndex);if (frames[closestIndex]) {@@ -770,8 +780,9 @@ export default function Timeline() {// correct frame once the new date's frames arrive via WebSocket.console.log("[handleDateChange] Navigation initiated, waiting for frames to load...");- // Safety timeout: clear navigation state if frames don't arrive within 10s- // This prevents the app from getting stuck in a loading state+ // Safety timeout: clear navigation state if frames don't arrive within 30s+ // This prevents the app from getting stuck in a loading state.+ // Using 30s because disk I/O can be slow (iCloud contention, large DB).setTimeout(() => {if (pendingNavigationRef.current && isSameDay(pendingNavigationRef.current, newDate)) {console.warn("[handleDateChange] Timeout: frames didn't arrive, clearing navigation state");@@ -779,7 +790,7 @@ export default function Timeline() {setSeekingTimestamp(null);isNavigatingRef.current = false;}- }, 10000);+ }, 30000);} catch (error) {console.error("[handleDateChange] Error:", error);diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsxindex eb6d88dbd..073b85356 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx@@ -136,12 +136,15 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({clearTimeout(flushTimer);flushTimer = null;}- // DON'T clear frames - keep showing stale data while loading new- // Only clear the request tracking and show loading indicator- set((state) => ({+ // Clear frames and timestamps so cross-day navigation starts fresh.+ // Keeping stale frames from the old day causes the pendingNavigation+ // effect to see mixed-day data and potentially jump to the wrong frame.+ set(() => ({+ frames: [],+ frameTimestamps: new Set<string>(),sentRequests: new Set<string>(),isLoading: true,- loadingProgress: { loaded: state.frames.length, isStreaming: false },+ loadingProgress: { loaded: 0, isStreaming: false },error: null,message: "loading...",}));diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex b889ad6e9..9027b9417 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -2980,7 +2980,7 @@ SELECTFROM frames fINNER JOIN ocr_text o ON f.id = o.frame_idWHERE {}-ORDER BY {} DESC, f.timestamp {}+ORDER BY f.timestamp {}, {} DESCLIMIT ? OFFSET ?"#,if conditions.is_empty() {@@ -2988,11 +2988,11 @@ LIMIT ? OFFSET ?} else {conditions.join(" AND ")},- relevance_case,match order {Order::Ascending => "ASC",Order::Descending => "DESC",- }+ },+ relevance_case);let mut query_builder = sqlx::query_as::<_, FrameRow>(&sql);diff --git a/crates/screenpipe-db/tests/keyword_search_order_test.rs b/crates/screenpipe-db/tests/keyword_search_order_test.rsnew file mode 100644index 000000000..0b3143814--- /dev/null+++ b/crates/screenpipe-db/tests/keyword_search_order_test.rs@@ -0,0 +1,247 @@+#[cfg(test)]+mod tests {+ use std::sync::Arc;+ use chrono::{Duration, Utc};+ use screenpipe_db::{DatabaseManager, OcrEngine, Order};++ async fn setup_test_db() -> DatabaseManager {+ let db = DatabaseManager::new("sqlite::memory:").await.unwrap();+ sqlx::migrate!("./src/migrations")+ .run(&db.pool)+ .await+ .unwrap();+ db+ }++ /// Insert a frame with OCR text and return the frame_id.+ /// The ocr_text MUST contain the search keyword for FTS to find it.+ async fn insert_frame_with_ocr(+ db: &DatabaseManager,+ app_name: &str,+ window_name: &str,+ ocr_text: &str,+ minutes_ago: i64,+ ) -> i64 {+ let _ = db+ .insert_video_chunk("test_video.mp4", "test_device")+ .await+ .unwrap();++ let frame_id = db+ .insert_frame(+ "test_device",+ None,+ None,+ Some(app_name),+ Some(window_name),+ false,+ None,+ )+ .await+ .unwrap();++ // Manually set the timestamp to the desired time+ let ts = Utc::now() - Duration::minutes(minutes_ago);+ sqlx::query("UPDATE frames SET timestamp = ? WHERE id = ?")+ .bind(ts)+ .bind(frame_id)+ .execute(&db.pool)+ .await+ .unwrap();++ db.insert_ocr_text(+ frame_id,+ ocr_text,+ "[]",+ Arc::new(OcrEngine::AppleNative),+ )+ .await+ .unwrap();++ frame_id+ }++ #[tokio::test]+ async fn test_keyword_search_sorted_by_timestamp_descending() {+ let db = setup_test_db().await;++ // All frames have "hello" in OCR text so FTS finds them.+ // They differ in timestamp — we verify results come back newest-first.+ // Frame A: 60 min ago, "hello" also in window_name (high relevance)+ let _frame_a = insert_frame_with_ocr(+ &db,+ "Arc",+ "hello world page",+ "hello from the browser",+ 60,+ )+ .await;++ // Frame B: 10 min ago, "hello" only in OCR (low relevance)+ let _frame_b = insert_frame_with_ocr(+ &db,+ "WezTerm",+ "terminal",+ "echo hello",+ 10,+ )+ .await;++ // Frame C: 30 min ago+ let _frame_c = insert_frame_with_ocr(+ &db,+ "Cursor",+ "editor",+ "println hello",+ 30,+ )+ .await;++ let results = db+ .search_with_text_positions(+ "hello",+ 10,+ 0,+ None,+ None,+ true,+ Order::Descending,+ None,+ )+ .await+ .unwrap();++ assert!(+ results.len() >= 3,+ "Expected at least 3 results, got {}",+ results.len()+ );++ // Results must be sorted by timestamp DESCENDING (most recent first)+ // Frame B (10 min ago) → Frame C (30 min ago) → Frame A (60 min ago)+ for i in 0..results.len() - 1 {+ assert!(+ results[i].timestamp >= results[i + 1].timestamp,+ "Results not sorted by timestamp descending: [{}] {} should be >= [{}] {}",+ i,+ results[i].timestamp,+ i + 1,+ results[i + 1].timestamp,+ );+ }++ // The most recent result (Frame B, 10 min ago) should be first+ // even though Frame A has higher relevance (keyword in window_name)+ assert_eq!(+ results[0].app_name, "WezTerm",+ "Most recent frame should be first regardless of relevance. Got: {} at {}",+ results[0].app_name, results[0].timestamp+ );+ }++ #[tokio::test]+ async fn test_keyword_search_sorted_by_timestamp_ascending() {+ let db = setup_test_db().await;++ let _frame_old = insert_frame_with_ocr(+ &db,+ "Arc",+ "browser",+ "old content with hello",+ 120,+ )+ .await;++ let _frame_new = insert_frame_with_ocr(+ &db,+ "WezTerm",+ "terminal",+ "new content hello world",+ 5,+ )+ .await;++ let results = db+ .search_with_text_positions(+ "hello",+ 10,+ 0,+ None,+ None,+ true,+ Order::Ascending,+ None,+ )+ .await+ .unwrap();++ assert!(results.len() >= 2, "Expected at least 2 results, got {}", results.len());++ // Ascending: oldest first+ for i in 0..results.len() - 1 {+ assert!(+ results[i].timestamp <= results[i + 1].timestamp,+ "Results not sorted by timestamp ascending: [{}] {} should be <= [{}] {}",+ i,+ results[i].timestamp,+ i + 1,+ results[i + 1].timestamp,+ );+ }+ }++ #[tokio::test]+ async fn test_keyword_search_same_timestamp_uses_relevance_tiebreak() {+ let db = setup_test_db().await;++ // Two frames at the same time, different relevance.+ // Both have "hello" in OCR text so FTS finds both.+ // Frame 1: "hello" only in OCR (relevance 1)+ let _frame_low = insert_frame_with_ocr(+ &db,+ "Terminal",+ "bash",+ "hello world from terminal",+ 10,+ )+ .await;++ // Frame 2: "hello" in window_name too (relevance 3)+ let _frame_high = insert_frame_with_ocr(+ &db,+ "Arc",+ "hello dashboard",+ "hello content here",+ 10, // same time+ )+ .await;++ let results = db+ .search_with_text_positions(+ "hello",+ 10,+ 0,+ None,+ None,+ true,+ Order::Descending,+ None,+ )+ .await+ .unwrap();++ assert!(results.len() >= 2, "Expected at least 2 results, got {}", results.len());++ // Both have ~same timestamp, so within the same second,+ // the one with "hello" in window_name (higher relevance) should come first+ let first_has_hello_in_window = results[0]+ .window_name+ .to_lowercase()+ .contains("hello");+ assert!(+ first_has_hello_in_window,+ "Within same timestamp, higher relevance result should come first. Got: {} - {}",+ results[0].app_name, results[0].window_name+ );+ }+}