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: broken cache timeline

Louis Beaumontf1dd129b020b
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsx
index 66714f3d4..b4372fe43 100644
--- a/screenpipe-app-tauri/app/timeline/page.tsx
+++ b/screenpipe-app-tauri/app/timeline/page.tsx
@@ -191,17 +191,26 @@ export default function Timeline() {
const exists = prev.some((f) => f.timestamp === data.timestamp);
if (exists) return prev;
- // ! HACK: Add new frame and sort in descending order
+ // Get current timestamp if there's a current frame
+ const currentTimestamp = prev[currentIndex]?.timestamp;
+
+ // Add new frame and sort
const newFrames = [...prev, data].sort((a, b) => {
- return (
- new Date(b.timestamp).getTime() -
- new Date(a.timestamp).getTime()
- );
+ return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
});
+ // If we have a current frame, adjust the currentIndex
+ if (currentTimestamp) {
+ const newIndex = newFrames.findIndex(f => f.timestamp === currentTimestamp);
+ if (newIndex !== -1) {
+ setCurrentIndex(newIndex);
+ }
+ }
+
return newFrames;
});
+ // Only set initial frame if we don't have one
setCurrentFrame((prev) => prev || data.devices[0]);
setIsLoading(false);
}
@@ -766,6 +775,9 @@ export default function Timeline() {
<div>
window: {currentFrame.metadata.window_name || "n/a"}
</div>
+ <div className="border-l pl-4 font-mono">
+ {new Date(currentFrame.metadata.timestamp || frames[currentIndex].timestamp).toLocaleString()}
+ </div>
</div>
</div>
</div>
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index a7edb58ce..df6b4a923 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -1,7 +1,7 @@
use crate::filtering::filter_texts;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
-use log::{debug, error, info, warn};
+use log::{debug, error, warn};
use screenpipe_audio::{AudioDevice, DeviceType};
use screenpipe_integrations::friend_wearable::FriendWearableDatabase;
use screenpipe_vision::OcrEngine;
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index 7d0a4699f..65d4e88dd 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -43,6 +43,18 @@ pub struct AudioEntry {
pub duration_secs: f64,
}
+impl From<crate::db::AudioEntry> for AudioEntry {
+ fn from(db_entry: crate::db::AudioEntry) -> Self {
+ Self {
+ transcription: db_entry.transcription,
+ device_name: db_entry.device_name,
+ is_input: db_entry.is_input,
+ audio_file_path: db_entry.audio_file_path,
+ duration_secs: db_entry.duration_secs,
+ }
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrameMetadata {
pub file_path: String,
@@ -109,7 +121,7 @@ impl Default for CacheConfig {
cache_dir: PathBuf::from("frame_cache"),
max_cache_size_gb: 10.0,
frame_retention_days: 7,
- compression_quality: 85,
+ compression_quality: 50,
}
}
}
@@ -202,21 +214,7 @@ impl FrameDiskCache {
.split_once("||")
.ok_or_else(|| anyhow::anyhow!("invalid cache key format"))?;
- let clean_timestamp = timestamp_str
- .trim_end_matches(" UTC")
- .replace(' ', "T")
- .trim()
- .to_string();
-
- let clean_timestamp = if !clean_timestamp.ends_with('Z') && !clean_timestamp.contains('+') {
- format!("{}Z", clean_timestamp)
- } else {
- clean_timestamp
- };
-
- let timestamp = DateTime::parse_from_rfc3339(&clean_timestamp).map_err(|e| {
- anyhow::anyhow!("failed to parse timestamp '{}': {}", clean_timestamp, e)
- })?;
+ let timestamp = parse_timestamp(timestamp_str)?;
let frame_path = self.get_frame_path(&timestamp.into(), device_id);
@@ -278,17 +276,25 @@ impl FrameDiskCache {
None => return Ok(None),
};
- let timestamp = match DateTime::parse_from_rfc3339(timestamp_str) {
+ debug!("cache lookup for key: {}", cache_key);
+
+ let timestamp = match parse_timestamp(timestamp_str) {
Ok(ts) => ts,
- Err(_) => return Ok(None),
+ Err(e) => {
+ debug!("failed to parse timestamp {}: {}", timestamp_str, e);
+ return Ok(None);
+ }
};
let frame_path = self.get_frame_path(&timestamp.into(), device_id);
+ debug!("looking for cached frame at: {:?}", frame_path);
if !frame_path.exists() {
+ debug!("cache miss - frame not found at {:?}", frame_path);
return Ok(None);
}
+ debug!("cache hit - reading frame from {:?}", frame_path);
let frame_data = fs::read(&frame_path).await?;
if let Some(entry) = self.entries.get(&(timestamp.into(), device_id.to_string())) {
@@ -301,12 +307,14 @@ impl FrameDiskCache {
return Ok(None);
}
+ debug!("successfully retrieved cached frame");
Ok(Some((
frame_data,
entry.frame.metadata.clone(),
(timestamp.into(), device_id.to_string()),
)))
} else {
+ debug!("cache miss - no entry in index for frame");
Ok(None)
}
}
@@ -381,6 +389,7 @@ impl FrameCache {
frame_tx: FrameChannel,
) -> Result<()> {
let mut extraction_queue = HashMap::new();
+ let mut total_frames = 0;
debug!(
"extracting frames for time range: {} to {}",
@@ -388,25 +397,12 @@ impl FrameCache {
);
let mut chunks = self.db.find_video_chunks(start_time, end_time).await?;
-
- // Sort frames in descending order by timestamp
- chunks.frames.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
-
- debug!("found {} chunks", chunks.frames.len());
-
- let frame_times = chunks
- .frames
- .iter()
- .map(|c| c.timestamp)
- .collect::<Vec<_>>();
+ // Sort by timestamp to ensure consistent ordering
+ chunks.frames.sort_by_key(|a| (a.timestamp, a.offset_index));
- debug!(
- "🎯 requested time range: {} to {} ({} frames)",
- start_time,
- end_time,
- frame_times.len()
- );
+ debug!("found {} chunks to process", chunks.frames.len());
+ // First pass: process all cache hits
for chunk in &chunks.frames {
let mut timeseries_frame = TimeSeriesFrame {
timestamp: chunk.timestamp,
@@ -415,6 +411,7 @@ impl FrameCache {
for device_data in &chunk.ocr_entries {
let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);
+ debug!("checking cache for key: {}", cache_key);
let (response_tx, response_rx) = oneshot::channel();
self.cache_tx
@@ -424,50 +421,65 @@ impl FrameCache {
})
.await?;
- if let Ok(Some((frame_data, metadata, _))) = response_rx.await? {
- timeseries_frame.frame_data.push(DeviceFrame {
- device_id: device_data.device_name.clone(),
- image_data: frame_data,
- metadata,
- audio_entries: chunk
- .audio_entries
- .iter()
- .map(|a| AudioEntry {
- transcription: a.transcription.clone(),
- device_name: a.device_name.clone(),
- is_input: a.is_input,
- audio_file_path: a.audio_file_path.clone(),
- duration_secs: a.duration_secs,
- })
- .collect(),
- });
- } else {
- extraction_queue
- .entry(device_data.video_file_path.clone())
- .or_insert_with(Vec::new)
- .push((chunk.clone(), device_data.clone()));
+ match response_rx.await? {
+ Ok(Some((frame_data, metadata, _))) => {
+ debug!("cache hit for {}", cache_key);
+ timeseries_frame.frame_data.push(DeviceFrame {
+ device_id: device_data.device_name.clone(),
+ image_data: frame_data,
+ metadata,
+ audio_entries: chunk
+ .audio_entries
+ .iter()
+ .map(|a| AudioEntry {
+ transcription: a.transcription.clone(),
+ device_name: a.device_name.clone(),
+ is_input: a.is_input,
+ audio_file_path: a.audio_file_path.clone(),
+ duration_secs: a.duration_secs,
+ })
+ .collect(),
+ });
+ }
+ _ => {
+ debug!("cache miss for {}", cache_key);
+ extraction_queue
+ .entry(device_data.video_file_path.clone())
+ .or_insert_with(Vec::new)
+ .push((chunk.clone(), device_data.clone()));
+ }
}
}
if !timeseries_frame.frame_data.is_empty() {
+ total_frames += timeseries_frame.frame_data.len();
+ debug!(
+ "sending cached frame batch with {} devices",
+ timeseries_frame.frame_data.len()
+ );
frame_tx.send(timeseries_frame).await?;
}
}
- let ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;
+ // Second pass: handle cache misses
+ if !extraction_queue.is_empty() {
+ let ffmpeg = find_ffmpeg_path().ok_or_else(|| anyhow::anyhow!("ffmpeg not found"))?;
- for (file_path, tasks) in extraction_queue {
- extract_frame(
- ffmpeg.clone(),
- file_path,
- tasks,
- frame_tx.clone(),
- self.cache_tx.clone(),
- )
- .await?;
+ for (file_path, tasks) in extraction_queue {
+ debug!("extracting {} frames from {}", tasks.len(), file_path);
+ let extracted = extract_frame(
+ ffmpeg.clone(),
+ file_path,
+ tasks,
+ frame_tx.clone(),
+ self.cache_tx.clone(),
+ )
+ .await?;
+ total_frames += extracted;
+ }
}
- debug!("extraction queue completed");
+ debug!("total frames processed: {}", total_frames);
Ok(())
}
@@ -546,10 +558,10 @@ async fn extract_frame(
tasks: Vec<(FrameData, OCREntry)>,
frame_tx: FrameChannel,
cache_tx: mpsc::Sender<CacheMessage>,
-) -> Result<()> {
+) -> Result<usize> {
if !is_video_file_complete(&ffmpeg, &video_file_path).await? {
debug!("skipping incomplete video file: {}", video_file_path);
- return Ok(());
+ return Ok(0);
}
let temp_dir = tempfile::tempdir()?;
@@ -562,9 +574,15 @@ async fn extract_frame(
"-c:v",
"mjpeg",
"-q:v",
- "3",
+ "8",
+ "-qmin",
+ "8",
+ "-qmax",
+ "12",
"-vsync",
"0",
+ "-threads",
+ "2",
output_pattern.to_str().unwrap(),
]);
@@ -573,52 +591,54 @@ async fn extract_frame(
let output = cmd.output().await?;
if !output.status.success() {
error!("ffmpeg error: {}", String::from_utf8_lossy(&output.stderr));
- return Ok(());
+ return Ok(0);
}
+ let mut processed = 0;
let mut entries = tokio::fs::read_dir(temp_dir.path()).await?;
+ let mut all_frames = Vec::new();
+
while let Some(entry) = entries.next_entry().await? {
let frame_data = tokio::fs::read(entry.path()).await?;
+ all_frames.push(frame_data);
+ }
- debug!(
- "extracted frame of size {} bytes from {}",
- frame_data.len(),
- video_file_path
- );
-
- let mut frames_by_timestamp: HashMap<DateTime<Utc>, Vec<DeviceFrame>> = HashMap::new();
+ debug!("extracted {} frames from video", all_frames.len());
- for (chunk, device_data) in &tasks {
- let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);
+ for (task_index, (chunk, device_data)) in tasks.iter().enumerate() {
+ if task_index >= all_frames.len() {
+ debug!("warning: ran out of frames at index {}", task_index);
+ break;
+ }
- let (response_tx, response_rx) = oneshot::channel();
- cache_tx
- .send(CacheMessage::Store {
- cache_key: cache_key.clone(),
- frame_data: frame_data.clone(),
- device_data: device_data.clone(),
- audio_entries: chunk
- .audio_entries
- .iter()
- .map(|a| AudioEntry {
- transcription: a.transcription.clone(),
- device_name: a.device_name.clone(),
- is_input: a.is_input,
- audio_file_path: a.audio_file_path.clone(),
- duration_secs: a.duration_secs,
- })
- .collect(),
- response: response_tx,
- })
- .await?;
+ let frame_data = &all_frames[task_index];
+ let cache_key = format!("{}||{}", chunk.timestamp, device_data.device_name);
+ debug!("processing frame {} with key {}", task_index, cache_key);
+
+ // Store in cache first
+ let (response_tx, response_rx) = oneshot::channel();
+ cache_tx
+ .send(CacheMessage::Store {
+ cache_key: cache_key.clone(),
+ frame_data: frame_data.clone(),
+ device_data: device_data.clone(),
+ audio_entries: chunk
+ .audio_entries
+ .clone()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ response: response_tx,
+ })
+ .await?;
- response_rx.await??;
- debug!("cached frame for {}", device_data.device_name);
+ response_rx.await??;
- frames_by_timestamp
- .entry(chunk.timestamp)
- .or_default()
- .push(DeviceFrame {
+ // Then send the frame
+ frame_tx
+ .send(TimeSeriesFrame {
+ timestamp: chunk.timestamp,
+ frame_data: vec![DeviceFrame {
device_id: device_data.device_name.clone(),
image_data: frame_data.clone(),
metadata: FrameMetadata {
@@ -644,24 +664,15 @@ async fn extract_frame(
duration_secs: a.duration_secs,
})
.collect(),
- });
- }
-
- for (timestamp, device_frames) in frames_by_timestamp {
- frame_tx
- .send(TimeSeriesFrame {
- timestamp,
- frame_data: device_frames,
- })
- .await?;
- }
+ }],
+ })
+ .await?;
- debug!("sent frames for entire video file {}", video_file_path);
+ processed += 1;
}
- debug!("extraction completed");
-
- Ok(())
+ debug!("processed {} frames from video file", processed);
+ Ok(processed)
}
async fn is_video_file_complete(ffmpeg_path: &PathBuf, file_path: &str) -> Result<bool> {
@@ -698,3 +709,24 @@ async fn is_video_file_complete(ffmpeg_path: &PathBuf, file_path: &str) -> Resul
}
}
}
+
+fn parse_timestamp(timestamp_str: &str) -> Result<DateTime<Utc>> {
+ // First try direct RFC3339 parsing
+ if let Ok(dt) = DateTime::parse_from_rfc3339(timestamp_str) {
+ return Ok(dt.with_timezone(&Utc));
+ }
+
+ // Handle " UTC" suffix by converting to Z format
+ let cleaned = timestamp_str.trim_end_matches(" UTC").replace(' ', "T");
+
+ // Ensure we have a Z or +00:00 timezone marker
+ let timestamp_with_tz = if !cleaned.ends_with('Z') && !cleaned.contains('+') {
+ format!("{}Z", cleaned)
+ } else {
+ cleaned
+ };
+
+ DateTime::parse_from_rfc3339(&timestamp_with_tz)
+ .map(|dt| dt.with_timezone(&Utc))
+ .map_err(|e| anyhow::anyhow!("failed to parse timestamp '{}': {}", timestamp_str, e))
+}
diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rs
index fa53d1b4c..4eec5f00c 100644
--- a/screenpipe-server/tests/video_cache_test.rs
+++ b/screenpipe-server/tests/video_cache_test.rs
@@ -1,7 +1,6 @@
use anyhow::Result;
-use chrono::{Duration, Utc};
+use chrono::{DateTime, Duration, Utc};
use dirs::home_dir;
-use screenpipe_server::{db::OCREntry, video_cache::AudioEntry};
use std::sync::Arc;
use tracing::{debug, error};
@@ -440,3 +439,111 @@ async fn test_frame_ordering() -> Result<()> {
Ok(())
}
+
+#[tokio::test]
+async fn test_cache_effectiveness() -> Result<()> {
+ let (cache, _db) = setup_test_env().await?;
+
+ println!("\ncache effectiveness test:");
+ println!("-----------------------");
+
+ // First request - should process and cache frames
+ let target_time = Utc::now() - Duration::minutes(5);
+ let (tx1, mut rx1) = tokio::sync::mpsc::channel(100);
+
+ println!("first request - should process and cache frames");
+ let start = std::time::Instant::now();
+ cache.get_frames(target_time, 2, tx1, true).await?;
+
+ let mut first_request_frames = Vec::new();
+ while let Some(frame) = rx1.recv().await {
+ first_request_frames.push(frame);
+ }
+ let first_request_time = start.elapsed();
+
+ println!(
+ "first request: {} frames in {:.2}s",
+ first_request_frames.len(),
+ first_request_time.as_secs_f64()
+ );
+
+ // Wait a moment to ensure async operations complete
+ tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
+
+ // Second request - should use cached frames
+ let (tx2, mut rx2) = tokio::sync::mpsc::channel(100);
+
+ println!("\nsecond request - should use cached frames");
+ let start = std::time::Instant::now();
+ cache.get_frames(target_time, 2, tx2, true).await?;
+
+ let mut second_request_frames = Vec::new();
+ while let Some(frame) = rx2.recv().await {
+ second_request_frames.push(frame);
+ }
+ let second_request_time = start.elapsed();
+
+ println!(
+ "second request: {} frames in {:.2}s",
+ second_request_frames.len(),
+ second_request_time.as_secs_f64()
+ );
+
+ // Verify cache effectiveness
+ assert_eq!(
+ first_request_frames.len(),
+ second_request_frames.len(),
+ "both requests should return the same number of frames"
+ );
+
+ // Second request should be significantly faster (at least 2x)
+ assert!(
+ second_request_time < first_request_time / 2,
+ "cached request should be at least 2x faster: first={:.2}s, second={:.2}s",
+ first_request_time.as_secs_f64(),
+ second_request_time.as_secs_f64()
+ );
+
+ // Verify frame data integrity between requests
+ for (i, (first, second)) in first_request_frames
+ .iter()
+ .zip(second_request_frames.iter())
+ .enumerate()
+ {
+ assert_eq!(
+ first.timestamp, second.timestamp,
+ "frame {} timestamps should match",
+ i
+ );
+
+ for (first_device, second_device) in first.frame_data.iter().zip(second.frame_data.iter()) {
+ assert_eq!(
+ first_device.device_id, second_device.device_id,
+ "frame {} device IDs should match",
+ i
+ );
+ assert_eq!(
+ first_device.image_data, second_device.image_data,
+ "frame {} image data should match",
+ i
+ );
+ }
+ }
+
+ println!("\ncache effectiveness metrics:");
+ println!(
+ "- first request time: {:.2}s",
+ first_request_time.as_secs_f64()
+ );
+ println!(
+ "- second request time: {:.2}s",
+ second_request_time.as_secs_f64()
+ );
+ println!(
+ "- speedup factor: {:.2}x",
+ first_request_time.as_secs_f64() / second_request_time.as_secs_f64()
+ );
+ println!("- frames processed: {}", first_request_frames.len());
+
+ Ok(())
+}