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

works - but slow

Louis Beaumont9e365763afb2
diff --git a/screenpipe-server/examples/timeline_ui/index.html b/screenpipe-server/examples/timeline_ui/index.html
index 306949ace..f86eae691 100644
--- a/screenpipe-server/examples/timeline_ui/index.html
+++ b/screenpipe-server/examples/timeline_ui/index.html
@@ -10,9 +10,26 @@
margin: 0;
padding: 20px;
}
+ #timeline {
+ position: relative;
+ width: 100%;
+ height: 60px;
+ background: #111;
+ margin: 10px 0;
+ border: 1px solid #333;
+ cursor: pointer;
+ }
+ #cursor {
+ position: absolute;
+ width: 2px;
+ height: 100%;
+ background: #fff;
+ top: 0;
+ }
#frame {
max-width: 100%;
border: 1px solid #333;
+ min-height: 200px; /* prevent layout shift */
}
#info {
margin-top: 10px;
@@ -25,55 +42,149 @@
white-space: pre-wrap;
font-family: monospace;
}
+ .loading {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ background: rgba(0,0,0,0.8);
+ padding: 20px;
+ border-radius: 4px;
+ border: 1px solid #333;
+ display: none;
+ }
+ .loading.active {
+ display: block;
+ }
+ /* retro loading animation */
+ .loading::after {
+ content: '';
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ background: #fff;
+ animation: blink 1s infinite;
+ }
+ @keyframes blink {
+ 0% { opacity: 0; }
+ 50% { opacity: 1; }
+ 100% { opacity: 0; }
+ }
</style>
</head>
<body>
+ <div id="timeline"><div id="cursor"></div></div>
<img id="frame" />
<div id="info"></div>
<div id="error"></div>
+ <div class="loading">loading frames...</div>
<script>
- const endTime = new Date();
- const startTime = new Date(endTime - 1000 * 60 * 5); // last 5 minutes
+ let currentTime = new Date();
+ const timelineWidth = document.getElementById('timeline').offsetWidth;
+ const loading = document.querySelector('.loading');
+ let isLoading = false;
- // Properly encode the dates for the URL
- const url = new URL('http://localhost:3030/stream/frames');
- url.searchParams.append('start_time', startTime.toISOString());
- url.searchParams.append('end_time', endTime.toISOString());
- url.searchParams.append('fps', '1');
-
- console.log('connecting to:', url.toString());
-
- const eventSource = new EventSource(url.toString(), {
- withCredentials: false
- });
-
- eventSource.onopen = () => {
- console.log('connection opened');
- document.getElementById('error').textContent = 'connected successfully';
- };
-
- eventSource.addEventListener('frame', (event) => {
- const data = JSON.parse(event.data);
- document.getElementById('frame').src = `data:image/jpeg;base64,${data.frame}`;
- document.getElementById('info').textContent = `timestamp: ${data.timestamp} | app: ${data.app_name || 'n/a'} | window: ${data.window_name || 'n/a'}`;
- });
+ function setLoading(state) {
+ isLoading = state;
+ loading.classList.toggle('active', state);
+ }
+
+ function updateTimeline() {
+ const cursor = document.getElementById('cursor');
+ const position = ((currentTime - startTime) / (endTime - startTime)) * 100;
+ cursor.style.left = `${position}%`;
+ }
+
+ function connectToStream(startTime, endTime) {
+ if (window.eventSource) {
+ window.eventSource.close();
+ }
- eventSource.onerror = (error) => {
- const errorDetails = {
- type: error.type,
- target: {
- readyState: eventSource.readyState,
- url: url.toString()
- },
- timestamp: new Date().toISOString()
+ setLoading(true);
+
+ const url = new URL('http://localhost:3030/stream/frames');
+ url.searchParams.append('start_time', startTime.toISOString());
+ url.searchParams.append('end_time', endTime.toISOString());
+ url.searchParams.append('fps', '1');
+
+ console.log('connecting to:', url.toString());
+
+ window.eventSource = new EventSource(url.toString(), {
+ withCredentials: false
+ });
+
+ window.eventSource.onopen = () => {
+ console.log('connection opened');
+ document.getElementById('error').textContent = 'connected successfully';
};
- console.error('sse error:', errorDetails);
- document.getElementById('error').textContent =
- `error connecting to stream:\n${JSON.stringify(errorDetails, null, 2)}`;
- eventSource.close();
- };
+ window.eventSource.addEventListener('frame', (event) => {
+ setLoading(false);
+ const data = JSON.parse(event.data);
+ document.getElementById('frame').src = `data:image/jpeg;base64,${data.frame}`;
+ document.getElementById('info').textContent =
+ `timestamp: ${data.timestamp} | app: ${data.app_name || 'n/a'} | window: ${data.window_name || 'n/a'}`;
+ currentTime = new Date(data.timestamp);
+ updateTimeline();
+ });
+
+ window.eventSource.onerror = (error) => {
+ setLoading(false);
+ const errorDetails = {
+ type: error.type,
+ target: {
+ readyState: window.eventSource.readyState,
+ url: url.toString()
+ },
+ timestamp: new Date().toISOString()
+ };
+
+ console.error('sse error:', errorDetails);
+ document.getElementById('error').textContent =
+ `error connecting to stream:\n${JSON.stringify(errorDetails, null, 2)}`;
+ window.eventSource.close();
+ };
+ }
+
+ // Initialize timeline interaction
+ const timeline = document.getElementById('timeline');
+ timeline.addEventListener('click', (e) => {
+ const rect = timeline.getBoundingClientRect();
+ const position = (e.clientX - rect.left) / rect.width;
+ const timeRange = endTime - startTime;
+ currentTime = new Date(startTime.getTime() + (timeRange * position));
+
+ // Recalculate window around new current time
+ const windowSize = 5 * 60 * 1000; // 5 minutes
+ const newStartTime = new Date(currentTime.getTime() - (windowSize / 2));
+ const newEndTime = new Date(currentTime.getTime() + (windowSize / 2));
+
+ connectToStream(newStartTime, newEndTime);
+ });
+
+ // Handle keyboard navigation
+ document.addEventListener('keydown', (e) => {
+ const step = 1000; // 1 second step
+ if (e.key === 'ArrowLeft') {
+ currentTime = new Date(currentTime.getTime() - step);
+ connectToStream(
+ new Date(currentTime.getTime() - 150000),
+ new Date(currentTime.getTime() + 150000)
+ );
+ } else if (e.key === 'ArrowRight') {
+ currentTime = new Date(currentTime.getTime() + step);
+ connectToStream(
+ new Date(currentTime.getTime() - 150000),
+ new Date(currentTime.getTime() + 150000)
+ );
+ }
+ });
+
+ // Initial connection
+ const endTime = new Date();
+ const startTime = new Date(endTime - 1000 * 60 * 5); // last 5 minutes
+ connectToStream(startTime, endTime);
</script>
</body>
</html>
\ No newline at end of file
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 644ff917a..ce7f8d864 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -19,7 +19,7 @@ use crate::{
db::TagContentType,
pipe_manager::{PipeInfo, PipeManager},
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
- video_cache::FrameCache,
+ video_cache::{FrameCache, FrameCacheConfig},
video_utils::{merge_videos, MergeVideosRequest, MergeVideosResponse},
ContentType, DatabaseManager, SearchResult,
};
@@ -750,7 +750,18 @@ impl Server {
pipe_manager: self.pipe_manager,
vision_disabled: self.vision_disabled,
audio_disabled: self.audio_disabled,
- frame_cache: Arc::new(FrameCache::new(self.screenpipe_dir.clone()).await.unwrap()),
+ frame_cache: Arc::new(
+ FrameCache::with_config(
+ self.screenpipe_dir.clone().join("data"),
+ FrameCacheConfig {
+ prefetch_size: chrono::Duration::seconds(60),
+ cleanup_interval: chrono::Duration::minutes(360),
+ fps: 1.0,
+ },
+ )
+ .await
+ .unwrap(),
+ ),
});
let app = create_router()
@@ -1233,7 +1244,7 @@ async fn stream_frames_handler(
info!("no frame found at time: {}", current_time);
}
- current_time = current_time - chrono::Duration::milliseconds((1000.0 / request.fps.unwrap_or(10.0)) as i64);
+ current_time = current_time - chrono::Duration::milliseconds((1000.0 / request.fps.unwrap_or(1.0)) as i64);
tokio::time::sleep(Duration::from_millis(5)).await;
}
};
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index 3f3cd64bd..24c43ee49 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -1,5 +1,5 @@
use anyhow::Result;
-use chrono::{DateTime, Duration, Timelike, Utc};
+use chrono::{DateTime, Duration, Utc};
use dirs::cache_dir;
use std::path::PathBuf;
use std::sync::Arc;
@@ -11,8 +11,6 @@ use tokio::sync::RwLock;
use tracing::{debug, error, info};
use glob::glob;
-use lazy_static::lazy_static;
-use regex::Regex;
use screenpipe_core::find_ffmpeg_path;
use std::collections::HashMap;
use std::time::SystemTime;
@@ -27,9 +25,9 @@ pub struct FrameCacheConfig {
impl Default for FrameCacheConfig {
fn default() -> Self {
Self {
- prefetch_size: Duration::minutes(30),
+ prefetch_size: Duration::minutes(5),
cleanup_interval: Duration::minutes(5),
- fps: 10.0,
+ fps: 1.0,
}
}
}
@@ -46,6 +44,7 @@ pub struct FrameCache {
#[derive(Debug)]
enum CacheCommand {
Cleanup,
+ ScanForNewFrames,
}
#[derive(Debug)]
@@ -149,41 +148,62 @@ impl FrameCache {
config,
};
+ // Start background scanner task
+ let scanner_cache = cache.clone();
+ tokio::spawn(async move {
+ let mut interval = tokio::time::interval(Duration::seconds(10).to_std().unwrap());
+ loop {
+ interval.tick().await;
+ let now = Utc::now();
+ let scan_start = now - Duration::minutes(5); // Scan last 5 minutes
+ debug!("scanning for new frames from {} to {}", scan_start, now);
+
+ if let Err(e) = scanner_cache.preload_frames(&scan_start, &now).await {
+ error!("failed to scan for new frames: {}", e);
+ }
+ }
+ });
+
// Clone the parts needed for the cleanup task
- let cleanup_cache = FrameCache {
- screenpipe_dir: cache.screenpipe_dir.clone(),
- cache_dir: cache.cache_dir.clone(),
- cache_tx: cache.cache_tx.clone(),
- last_accessed_range: cache.last_accessed_range.clone(),
- config: cache.config,
- };
+ let cleanup_cache = cache.clone();
+
+ // Modify existing cleanup task to also handle ScanForNewFrames
+ tokio::spawn(async move {
+ let mut interval =
+ tokio::time::interval(cleanup_cache.config.cleanup_interval.to_std().unwrap());
+ loop {
+ tokio::select! {
+ _ = interval.tick() => {
+ debug!("performing scheduled cleanup");
+ // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {
+ // error!("failed to cleanup frames: {}", e);
+ // }
+ }
+ Some(cmd) = cache_rx.recv() => {
+ match cmd {
+ CacheCommand::Cleanup => {
+ debug!("performing requested cleanup");
+ // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {
+ // error!("failed to cleanup frames: {}", e);
+ // }
+ }
+ CacheCommand::ScanForNewFrames => {
+ let now = Utc::now();
+ // should be a percentage of the prefetch size
+ let scan_start = now - Duration::minutes(
+ cleanup_cache.config.prefetch_size.num_minutes() / 10
+ );
+ if let Err(e) = cleanup_cache.preload_frames(&scan_start, &now).await {
+ error!("failed to scan for new frames: {}", e);
+ }
+ }
+ }
+ }
+ }
+ }
+ });
- // tokio::spawn(async move {
- // let mut interval =
- // tokio::time::interval(cleanup_cache.config.cleanup_interval.to_std().unwrap());
- // loop {
- // tokio::select! {
- // _ = interval.tick() => {
- // info!("performing cleanup");
- // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {
- // error!("failed to cleanup frames: {}", e);
- // }
- // }
- // Some(cmd) = cache_rx.recv() => {
- // match cmd {
- // CacheCommand::Cleanup => {
- // info!("performing cleanup");
- // if let Err(e) = Self::cleanup_old_frames(&cleanup_cache).await {
- // error!("failed to cleanup frames: {}", e);
- // }
- // }
- // }
- // }
- // }
- // }
- // });
-
- Ok(cleanup_cache)
+ Ok(cache)
}
async fn cleanup_old_frames(cache: &FrameCache) -> Result<()> {
@@ -235,19 +255,27 @@ impl FrameCache {
let frame_path = self
.cache_dir
.join(format!("frame_{}.jpg", target_time.timestamp()));
+
if frame_path.exists() {
+ debug!("frame found in cache: {:?}", frame_path);
return Some(frame_path);
}
- // If not in cache, do the prefetch and WAIT for it
+ // If not in cache, trigger prefetch
let prefetch_end = target_time + self.config.prefetch_size;
- if let Err(e) = self.update_access_pattern(target_time, prefetch_end).await {
+ debug!(
+ "frame not in cache, prefetching range {} to {}",
+ target_time, prefetch_end
+ );
+
+ if let Err(e) = self.preload_frames(&target_time, &prefetch_end).await {
error!("prefetch failed: {}", e);
return None;
}
- // After prefetch completes, check cache again
+ // After prefetch, check cache again
if frame_path.exists() {
+ debug!("frame found after prefetch: {:?}", frame_path);
Some(frame_path)
} else {
debug!("frame not found even after prefetch: {}", target_time);
@@ -484,8 +512,8 @@ impl FrameCache {
debug!("file age: {}s, chunk_time: {}", age.as_secs(), chunk_time);
- if age.as_secs() < 60 {
- debug!("skipping recent file: {}", file_path);
+ if age.as_secs() < 10 {
+ debug!("skipping very recent file: {}", file_path);
continue;
}
diff --git a/screenpipe-server/tests/video_cache_test.rs b/screenpipe-server/tests/video_cache_test.rs
index f5405fced..06f0bf69e 100644
--- a/screenpipe-server/tests/video_cache_test.rs
+++ b/screenpipe-server/tests/video_cache_test.rs
@@ -26,7 +26,15 @@ async fn setup_test_env() -> Result<FrameCache> {
#[tokio::test]
async fn test_frame_retrieval() -> Result<()> {
- let cache = setup_test_env().await?;
+ // Use custom config with shorter timeouts for testing
+ let config = FrameCacheConfig {
+ prefetch_size: Duration::seconds(10),
+ cleanup_interval: Duration::minutes(1),
+ fps: 1.0,
+ };
+
+ let frame_cache = setup_test_env().await?;
+ let cache = FrameCache::with_config(frame_cache.screenpipe_dir, config).await?;
let target_time = Utc::now() - Duration::minutes(30);
println!("triggering initial frame load for {}", target_time);