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

24h timeline up

Louis Beaumontecac87d93baa
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsx
index 1a2f8d9a8..a7d8333e2 100644
--- a/screenpipe-app-tauri/app/timeline/page.tsx
+++ b/screenpipe-app-tauri/app/timeline/page.tsx
@@ -19,7 +19,6 @@ export default function Timeline() {
const [error, setError] = useState<string | null>(null);
const eventSourceRef = useRef<EventSource | null>(null);
const retryTimeoutRef = useRef<NodeJS.Timeout>();
- const maxRetries = 3;
const retryCount = useRef(0);
const setupEventSource = () => {
@@ -27,9 +26,13 @@ export default function Timeline() {
eventSourceRef.current.close();
}
+ // now minus 2 minutes
const endTime = new Date();
- const startTime = new Date(endTime.getTime() - 5 * 60 * 1000);
- const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&fps=1&reverse=true`;
+ endTime.setMinutes(endTime.getMinutes() - 2);
+ // at 00.01 am today
+ const startTime = new Date();
+ startTime.setHours(0, 1, 0, 0);
+ const url = `http://localhost:3030/stream/frames?start_time=${startTime.toISOString()}&end_time=${endTime.toISOString()}&order=descending`;
console.log("starting stream:", url);
@@ -59,7 +62,7 @@ export default function Timeline() {
eventSource.onerror = (error) => {
// Ignore end of stream errors (expected behavior)
if (eventSource.readyState === EventSource.CLOSED) {
- console.log("stream ended (expected behavior)");
+ console.log("stream ended (expected behavior)", error);
setIsLoading(false);
return;
}
@@ -68,21 +71,6 @@ export default function Timeline() {
setError("connection lost. retrying...");
eventSource.close();
-
- if (retryCount.current < maxRetries) {
- retryTimeoutRef.current = setTimeout(() => {
- retryCount.current += 1;
- console.log(
- `retrying connection (${retryCount.current}/${maxRetries})...`
- );
- setupEventSource();
- }, 2000 * Math.pow(2, retryCount.current)); // Exponential backoff
- } else {
- setError(
- "failed to connect after multiple attempts. please refresh the page."
- );
- setIsLoading(false);
- }
};
eventSource.onopen = () => {
@@ -117,9 +105,17 @@ export default function Timeline() {
e.preventDefault();
e.stopPropagation();
- const delta = Math.sign(e.deltaY);
+ // Add a sensitivity factor to slow down scrolling (higher = slower)
+ const scrollSensitivity = 1;
+ // Negate the delta to invert the scrolling direction
+ const delta = -Math.sign(e.deltaY) / scrollSensitivity;
+
+ // Use Math.floor or Math.ceil depending on scroll direction to ensure we don't get stuck
const newIndex = Math.min(
- Math.max(0, currentIndex + delta),
+ Math.max(
+ 0,
+ currentIndex + (delta > 0 ? Math.ceil(delta) : Math.floor(delta))
+ ),
frames.length - 1
);
@@ -129,13 +125,26 @@ export default function Timeline() {
}
};
+ const getCurrentTimePercentage = () => {
+ const now = new Date();
+ const startOfDay = new Date(now);
+ startOfDay.setHours(0, 0, 0, 0);
+ const endOfDay = new Date(now);
+ endOfDay.setHours(23, 59, 59, 999);
+
+ const totalDayMilliseconds = endOfDay.getTime() - startOfDay.getTime();
+ const currentMilliseconds = now.getTime() - startOfDay.getTime();
+
+ return (currentMilliseconds / totalDayMilliseconds) * 100;
+ };
+
return (
<div
className="fixed inset-0 flex flex-col bg-black text-white overflow-hidden font-['Press_Start_2P'] relative"
onWheel={handleScroll}
style={{
height: "100vh",
- overscrollBehavior: "none", // Prevent bounce/overscroll effects
+ overscrollBehavior: "none",
}}
>
{/* Scanline effect overlay */}
@@ -144,7 +153,6 @@ export default function Timeline() {
style={{
background:
"repeating-linear-gradient(0deg, rgba(0,0,0,0.1) 0px, rgba(0,0,0,0.1) 1px, transparent 1px, transparent 2px)",
- imageRendering: "pixelated",
}}
/>
@@ -164,32 +172,29 @@ export default function Timeline() {
</div>
)}
{currentFrame && (
- <img
- src={`data:image/png;base64,${currentFrame.frame}`}
- className="absolute inset-0 w-4/5 h-auto max-h-[80vh] object-contain mx-auto mt-8 border-4 border-[#333] shadow-[0_0_16px_rgba(255,255,255,0.1)]"
- style={{ imageRendering: "pixelated" }}
- alt="Current frame"
- />
- )}
- </div>
-
- {/* Info text */}
- <div className="text-center text-[#888] text-xs tracking-wider my-5">
- {currentFrame && (
- <span>
- timestamp: {new Date(currentFrame.timestamp).toLocaleString()} |
- app: {currentFrame?.app_name || "n/a"} | window:{" "}
- {currentFrame?.window_name || "n/a"}
- </span>
+ <>
+ {/* App info centered above frame */}
+ <div className="w-4/5 mx-auto mt-4 mb-2 text-center">
+ <div className="inline-block bg-black/50 p-2 rounded shadow-lg backdrop-blur-sm border border-[#333] text-[#888] text-xs tracking-wider">
+ <div className="flex items-center gap-4">
+ <div>{new Date(currentFrame?.timestamp).toLocaleTimeString()}</div>
+ <div>app: {currentFrame?.app_name || "n/a"}</div>
+ <div>window: {currentFrame?.window_name || "n/a"}</div>
+ </div>
+ </div>
+ </div>
+ <img
+ src={`data:image/png;base64,${currentFrame.frame}`}
+ className="absolute inset-0 w-4/5 h-auto max-h-[80vh] object-contain mx-auto mt-12"
+ alt="Current frame"
+ />
+ </>
)}
</div>
{/* Timeline bar */}
<div className="w-4/5 mx-auto mb-8 relative">
- <div
- className="h-[60px] bg-[#111] border-4 border-[#444] shadow-[0_0_16px_rgba(0,0,0,0.8),inset_0_0_8px_rgba(255,255,255,0.1)] cursor-crosshair relative"
- style={{ imageRendering: "pixelated" }}
- >
+ <div className="h-[60px] bg-[#111] border-4 border-[#444] shadow-[0_0_16px_rgba(0,0,0,0.8),inset_0_0_8px_rgba(255,255,255,0.1)] cursor-crosshair relative">
{/* Grid lines */}
<div
className="absolute inset-0"
@@ -204,31 +209,28 @@ export default function Timeline() {
<div
className="absolute top-0 h-full w-1 bg-[#0f0] shadow-[0_0_12px_#0f0] opacity-80"
style={{
- left: `${(currentIndex / Math.max(frames.length - 1, 1)) * 100}%`,
+ left: `${getCurrentTimePercentage()}%`,
}}
/>
</div>
{/* Timeline timestamps */}
<div className="relative mt-1 px-2 text-[10px] text-[#0f0] shadow-[0_0_8px_#0f0]">
- {frames.length > 0 &&
- Array(5)
- .fill(0)
- .map((_, i) => {
- const position = i / 4;
- const frameIndex = Math.floor(position * (frames.length - 1));
- return (
- <div
- key={i}
- className="absolute transform -translate-x-1/2"
- style={{ left: `${position * 100}%` }}
- >
- {new Date(
- frames[frameIndex]?.timestamp
- ).toLocaleTimeString()}
- </div>
- );
- })}
+ {Array(7)
+ .fill(0)
+ .map((_, i) => {
+ const hour = (i * 4) % 24; // Start at 0 and increment by 4 hours
+
+ return (
+ <div
+ key={i}
+ className="absolute transform -translate-x-1/2"
+ style={{ left: `${(i * 100) / 6}%` }}
+ >
+ {`${hour.toString().padStart(2, "0")}:00`}
+ </div>
+ );
+ })}
</div>
</div>
</div>
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 6d37f4142..dc83a34e9 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.8.1"
+version = "0.8.2"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/tauri.conf.json b/screenpipe-app-tauri/src-tauri/tauri.conf.json
index 45d11fe11..8a081a788 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.conf.json
@@ -67,9 +67,9 @@
{
"title": "timeline",
"url": "/timeline",
- "width": 1400,
+ "width": 1200,
"height": 600,
- "minWidth": 1400,
+ "minWidth": 1000,
"minHeight": 600,
"visible": false,
"decorations": true,
diff --git a/screenpipe-server/examples/timeline_ui/index.html b/screenpipe-server/examples/timeline_ui/index.html
index e0bb75253..ba0eb01a7 100644
--- a/screenpipe-server/examples/timeline_ui/index.html
+++ b/screenpipe-server/examples/timeline_ui/index.html
@@ -383,6 +383,34 @@
to { transform: translateX(-50%) scale(1.1); }
}
+ .loading-indicator {
+ position: fixed;
+ bottom: 10px;
+ left: 50%;
+ transform: translateX(-50%);
+ background: rgba(0, 255, 0, 0.1);
+ border: 2px solid #0f0;
+ padding: 8px 16px;
+ font-family: 'Press Start 2P', monospace;
+ font-size: 10px;
+ color: #0f0;
+ text-shadow: 0 0 8px rgba(0, 255, 0, 0.5);
+ display: none;
+ z-index: 1000;
+ box-shadow: 0 0 16px rgba(0, 255, 0, 0.2);
+ }
+
+ .loading-indicator.active {
+ display: block;
+ animation: pulse 1s infinite;
+ }
+
+ @keyframes pulse {
+ 0% { opacity: 0.5; }
+ 50% { opacity: 1; }
+ 100% { opacity: 0.5; }
+ }
+
</style>
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>
@@ -406,6 +434,8 @@
<div id="info"></div>
<div id="error"></div>
+ <div class="loading-indicator">loading frames...</div>
+
<script>
let currentTime = new Date();
let endTime = new Date();
@@ -417,8 +447,13 @@
let scrollTimeout = null;
// Add these new variables
- const PREFETCH_THRESHOLD = 0.8; // When to fetch more frames (80% of range)
- const FETCH_OVERLAP = 1000 * 60 * 5; // 2 minutes overlap when fetching new frames
+ const PREFETCH_THRESHOLD = 0.8; // When to fetch more frames (80% of visible range)
+ const FETCH_OVERLAP = 1000 * 60 * 2; // 2 minutes overlap when fetching new frames
+
+ // Add debounce utility at the top
+ let prefetchTimeout = null;
+ let lastPrefetchDirection = null;
+ let isPrefetching = false;
function debugFrames() {
console.log('Current frames:', {
@@ -457,47 +492,88 @@
}
}
+ // Update prefetchFrames to prevent duplicate requests
async function prefetchFrames(direction) {
- let newStartTime, newEndTime;
-
- // Adjust the time window based on current view
- const currentTimeWindow = endTime - startTime;
-
- if (direction === 'future') {
- newStartTime = new Date(endTime - FETCH_OVERLAP);
- newEndTime = new Date(endTime.getTime() + currentTimeWindow);
- } else {
- newEndTime = new Date(startTime + FETCH_OVERLAP);
- newStartTime = new Date(startTime.getTime() - currentTimeWindow);
+ if (isPrefetching || direction === lastPrefetchDirection) {
+ return;
}
-
- console.log(`Prefetching ${direction} frames from ${newStartTime} to ${newEndTime}`);
-
- // Fetch new frames but keep existing ones
- const url = new URL('http://localhost:3030/stream/frames');
- url.searchParams.append('start_time', `${newStartTime.toISOString().slice(0, -1)}Z`);
- url.searchParams.append('end_time', `${newEndTime.toISOString().slice(0, -1)}Z`);
-
- try {
- const response = await fetch(url.toString());
- const newFrames = await response.json();
-
- // Merge new frames with existing ones, avoiding duplicates
- const existingTimestamps = new Set(frames.map(f => f.timestamp));
- const uniqueNewFrames = newFrames.filter(f => !existingTimestamps.has(f.timestamp));
+
+ if (prefetchTimeout) {
+ clearTimeout(prefetchTimeout);
+ }
+
+ prefetchTimeout = setTimeout(async () => {
+ isPrefetching = true;
+ lastPrefetchDirection = direction;
- if (direction === 'future') {
- frames.push(...uniqueNewFrames);
- endTime = newEndTime;
- } else {
- frames.unshift(...uniqueNewFrames);
- startTime = newStartTime;
+ // Show loading indicator
+ const loadingIndicator = document.querySelector('.loading-indicator');
+ loadingIndicator.classList.add('active');
+
+ try {
+ const timeWindow = endTime - startTime;
+ let newStartTime, newEndTime;
+
+ if (direction === 'future') {
+ newStartTime = new Date(endTime - FETCH_OVERLAP);
+ newEndTime = new Date(endTime.getTime() + timeWindow);
+ } else {
+ newEndTime = new Date(startTime + FETCH_OVERLAP);
+ newStartTime = new Date(startTime.getTime() - timeWindow);
+ }
+
+ console.log(`Prefetching ${direction} frames:`, {
+ newStartTime,
+ newEndTime,
+ currentFrames: frames.length
+ });
+
+ // Use /frames endpoint instead of /stream/frames for batch fetch
+ const url = new URL('http://localhost:3030/stream/frames');
+ url.searchParams.append('start_time', newStartTime.toISOString());
+ url.searchParams.append('end_time', newEndTime.toISOString());
+
+ const response = await fetch(url.toString());
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ const newFrames = await response.json();
+
+ if (!Array.isArray(newFrames)) {
+ throw new Error('Expected array of frames');
+ }
+
+ const existingTimestamps = new Set(frames.map(f => f.timestamp));
+ const uniqueNewFrames = newFrames.filter(f => !existingTimestamps.has(f.timestamp));
+
+ if (direction === 'future') {
+ frames.push(...uniqueNewFrames);
+ endTime = newEndTime;
+ } else {
+ frames.unshift(...uniqueNewFrames);
+ startTime = newStartTime;
+ }
+
+ frames.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
+ updateTimelineMarkers();
+
+ console.log('Prefetch complete:', {
+ direction,
+ newFramesAdded: uniqueNewFrames.length,
+ totalFrames: frames.length
+ });
+ } catch (e) {
+ console.error('Failed to prefetch frames:', e);
+ } finally {
+ // Hide loading indicator
+ loadingIndicator.classList.remove('active');
+
+ setTimeout(() => {
+ isPrefetching = false;
+ lastPrefetchDirection = null;
+ }, 1000);
}
-
- updateTimelineMarkers();
- } catch (e) {
- console.error('Failed to prefetch frames:', e);
- }
+ }, 500);
}
function displayFrameAtTime(timestamp) {
@@ -654,8 +730,7 @@
e.preventDefault();
const timeRange = endTime - startTime;
- // Make scroll less sensitive - adjust this value to control speed
- const scrollSensitivity = timeRange / 200; // Changed from 20 to 200 for slower movement
+ const scrollSensitivity = timeRange / 200;
const timeDelta = e.deltaY > 0 ? scrollSensitivity : -scrollSensitivity;
const newTime = new Date(currentTime.getTime() + timeDelta);
@@ -663,12 +738,15 @@
if (newTime >= startTime && newTime <= endTime) {
currentTime = newTime;
- console.log('Scroll update:', {
- timeDelta,
- newTime: currentTime.toISOString()
- });
+ // Check if we're near boundaries and need to prefetch
+ const position = (currentTime - startTime) / (endTime - startTime);
+
+ if (position > PREFETCH_THRESHOLD) {
+ prefetchFrames('future');
+ } else if (position < (1 - PREFETCH_THRESHOLD)) {
+ prefetchFrames('past');
+ }
- debugFrames();
displayFrameAtTime(currentTime);
updateTimelinePosition();
}
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index a0e75ef02..dfb2cdf5b 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1163,11 +1163,20 @@ struct InputControlResponse {
success: bool,
}
+#[derive(Deserialize, PartialEq)]
+enum Order {
+ Ascending,
+ Descending,
+}
+
// Add this new struct
#[derive(Deserialize)]
pub struct StreamFramesRequest {
start_time: DateTime<Utc>,
end_time: DateTime<Utc>,
+ // #[serde(rename = "order")]
+ // #[serde(default = "descending")]
+ // order: Order,
}
#[derive(Serialize)]
@@ -1238,7 +1247,7 @@ async fn stream_frames_handler(
let frame_tx = frame_tx.clone();
async move {
tokio::select! {
- result = cache.get_frames(center_timestamp, duration_minutes, frame_tx) => {
+ result = cache.get_frames(center_timestamp, duration_minutes, frame_tx, true) => {
if let Err(e) = result {
error!("frame extraction failed: {}", e);
}
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index f0c571eb2..907fe21b9 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -482,8 +482,16 @@ impl FrameCache {
start: &DateTime<Utc>,
end: &DateTime<Utc>,
frame_tx: FrameChannel,
+ descending: bool,
) -> Result<()> {
- let chunks = self.find_video_chunks(*start, *end).await?;
+ let mut chunks = self.find_video_chunks(*start, *end).await?;
+
+ // Sort chunks based on the descending flag
+ if descending {
+ chunks.sort_by(|a, b| b.start_time.cmp(&a.start_time));
+ } else {
+ chunks.sort_by(|a, b| a.start_time.cmp(&b.start_time));
+ }
for chunk in chunks {
if !self.is_video_file_complete(&chunk.file_path).await {
@@ -598,6 +606,7 @@ impl FrameCache {
timestamp: DateTime<Utc>,
duration_minutes: i64,
frame_tx: Sender<FrameInfo>,
+ descending: bool,
) -> Result<()> {
let start = timestamp - Duration::minutes(duration_minutes / 2);
let end = timestamp + Duration::minutes(duration_minutes / 2);
@@ -607,7 +616,7 @@ impl FrameCache {
let cache_clone = self.clone();
let extract_handle = tokio::spawn(async move {
cache_clone
- .extract_frames_range(&start, &end, extract_tx)
+ .extract_frames_range(&start, &end, extract_tx, descending)
.await
});