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 result navigation 10s+ slow, wrong frame, and nothing happens
Louis Beaumont535e634ceb1a
diff --git a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsxindex 40d6307f9..8ead298b2 100644--- a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx@@ -30,6 +30,10 @@ interface CurrentFrameTimelineProps {onUrlsDetected?: (urls: DetectedUrl[]) => void;/** all unique device_ids seen in this session (e.g. ["monitor_1", "monitor_4"]) */allDeviceIds?: string[];+ /** When true, use HTTP JPEG fallback instead of video seek for instant display after search navigation */+ searchNavFrame?: boolean;+ /** Called after the search nav frame has loaded, so subsequent scrolling uses video mode */+ onSearchNavComplete?: () => void;}@@ -84,6 +88,8 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({onFrameLoadError,onUrlsDetected,allDeviceIds,+ searchNavFrame,+ onSearchNavComplete,}) => {const { isMac } = usePlatform();const [isLoading, setIsLoading] = useState(true);@@ -233,7 +239,7 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({// Main video seeking effectuseEffect(() => {- if (!debouncedFrame || !useVideoMode || isSnapshotFrame) return;+ if (!debouncedFrame || !useVideoMode || isSnapshotFrame || searchNavFrame) return;const { filePath: path, offsetIndex: idx, fps: serverFps, frameId: fid } = debouncedFrame;// If this chunk previously failed, go straight to fallback@@ -346,7 +352,7 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({loadedChunkRef.current = null;setUseVideoMode(false);});- }, [debouncedFrame, useVideoMode, getVideoUrl, resolveEffectiveFps, isSnapshotFrame]);+ }, [debouncedFrame, useVideoMode, getVideoUrl, resolveEffectiveFps, isSnapshotFrame, searchNavFrame]);// Snapshot frames: load directly via Tauri asset protocol (no HTTP/DB needed)useEffect(() => {@@ -389,11 +395,17 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({// Fallback: ffmpeg <img> mode (same as old behavior)// Skipped for snapshot frames that loaded successfully via asset protocol+ // Also used when searchNavFrame is true (instant JPEG for first frame after search nav)const fallbackImageUrl = useMemo(() => {- if (useVideoMode || !debouncedFrame) return null;+ if (!debouncedFrame) return null;+ // Force HTTP JPEG for search navigation (skip slow video seek)+ if (searchNavFrame) {+ return `http://localhost:3030/frames/${debouncedFrame.frameId}`;+ }+ if (useVideoMode) return null;if (isSnapshotFrame && !snapshotFailed) return null;return `http://localhost:3030/frames/${debouncedFrame.frameId}`;- }, [useVideoMode, debouncedFrame, isSnapshotFrame, snapshotFailed]);+ }, [useVideoMode, debouncedFrame, isSnapshotFrame, snapshotFailed, searchNavFrame]);// Preload fallback image — only swap displayed URL when the new image loads successfullyuseEffect(() => {@@ -412,16 +424,24 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({duration_ms: Math.round(loadTime),frame_id: debouncedFrame?.frameId,success: true,- mode: "ffmpeg_fallback",+ mode: searchNavFrame ? "search_nav_fallback" : "ffmpeg_fallback",frames_skipped: framesSkippedRef.current,});frameLoadStartTimeRef.current = null;framesSkippedRef.current = 0;}+ // Clear search nav mode after first frame loads so subsequent scrolling uses video seek+ if (searchNavFrame) {+ onSearchNavComplete?.();+ }};img.onerror = () => {// Preload failed — keep showing previous imagesetIsLoading(false);+ // Still clear search nav mode on error to avoid getting stuck+ if (searchNavFrame) {+ onSearchNavComplete?.();+ }};img.src = fallbackImageUrl;return () => {@@ -746,8 +766,8 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({/>)}- {/* Fallback mode: preloaded <img> via HTTP server */}- {displayedFallbackUrl && !useVideoMode && !(snapshotAssetUrl && isSnapshotFrame && !snapshotFailed) && (+ {/* Fallback mode: preloaded <img> via HTTP server (also used for search nav) */}+ {displayedFallbackUrl && (!useVideoMode || searchNavFrame) && !(snapshotAssetUrl && isSnapshotFrame && !snapshotFailed) && (// eslint-disable-next-line @next/next/no-img-element<imgsrc={displayedFallbackUrl}diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline.tsxindex 70a274572..08d90d59a 100644--- a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx@@ -144,6 +144,10 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {// Navigation in progress — disables day arrows to prevent double-clicksconst [isNavigating, setIsNavigating] = useState(false);+ // When true, CurrentFrameTimeline uses HTTP JPEG fallback instead of video seek+ // for the first frame after a cross-date search navigation (avoids ~5s video load)+ const [searchNavFrame, setSearchNavFrame] = useState(false);+// Get timeline selection for chat contextconst { selectionRange, loadTagsForFrames } = useTimelineSelection();@@ -504,12 +508,15 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {if (isSameDay(targetDate, currentDate) && hasFramesForTargetDate) {console.log("[pendingNavigation] Frames loaded for target date, jumping to closest frame:", targetDate.toISOString());- // Find the closest frame to the target timestamp+ // Find the closest frame to the target timestamp — only consider+ // frames from the target date (old-date frames may still be in+ // the array during pendingDateSwap transitions)const targetTime = targetDate.getTime();let closestIndex = 0;let closestDiff = Infinity;frames.forEach((frame, index) => {+ if (!isSameDay(new Date(frame.timestamp), targetDate)) return;const frameTime = new Date(frame.timestamp).getTime();const diff = Math.abs(frameTime - targetTime);if (diff < closestDiff) {@@ -521,6 +528,8 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {const snapped = snapToDevice(closestIndex);setCurrentIndex(snapped);setCurrentFrame(frames[snapped]);+ // Use HTTP JPEG fallback for this first frame (skip slow video seek)+ setSearchNavFrame(true);console.log("[pendingNavigation] Jumped to frame index:", snapped);// Clear pending navigation and UI state@@ -943,6 +952,9 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {if (cancelled) return;+ // Always fetch full day. For search navigation, the narrow ±5min+ // fetch was already fired synchronously in navigateDirectToDate().+ // This full-day fetch acts as backfill to populate the timeline.const startTime = startOfDay(dateToCheck);const endTime = endOfDay(dateToCheck);fetchTimeRange(startTime, endTime);@@ -1179,19 +1191,38 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {pendingNavigationRef.current = targetDate;setSeekingTimestamp(targetDate.toISOString());- setCurrentFrame(null);+ // Fire narrow ±5min fetch IMMEDIATELY via the store's websocket+ // (don't wait for React effect cycle — that delays by 100ms+ and+ // can get cancelled by dependency changes)+ const targetMs = targetDate.getTime();+ const narrowStart = new Date(targetMs - 5 * 60 * 1000);+ const narrowEnd = new Date(targetMs + 5 * 60 * 1000);+ fetchTimeRange(narrowStart, narrowEnd);++ // Don't clear currentFrame — keep old frame visible while new ones loadsetCurrentIndex(0);setCurrentDate(targetDate);- console.log("[navigateDirectToDate] Navigation initiated, waiting for frames...");+ console.log("[navigateDirectToDate] Navigation initiated, narrow fetch sent");+ // Timeout: if frames haven't arrived after 10s, retry with full-day fetch+ // instead of giving up entirelysetTimeout(() => {if (pendingNavigationRef.current && isSameDay(pendingNavigationRef.current, targetDate)) {- console.warn("[navigateDirectToDate] Timeout: frames didn't arrive, clearing navigation state");- pendingNavigationRef.current = null;- setSeekingTimestamp(null);- setIsNavigating(false);- isNavigatingRef.current = false;+ console.warn("[navigateDirectToDate] Timeout: retrying with full-day fetch");+ clearSentRequestForDate(targetDate);+ fetchTimeRange(startOfDay(targetDate), endOfDay(targetDate));++ // Final timeout: give up after another 10s+ setTimeout(() => {+ if (pendingNavigationRef.current && isSameDay(pendingNavigationRef.current, targetDate)) {+ console.warn("[navigateDirectToDate] Final timeout: clearing navigation state");+ pendingNavigationRef.current = null;+ setSeekingTimestamp(null);+ setIsNavigating(false);+ isNavigatingRef.current = false;+ }+ }, 10000);}}, 10000);};@@ -1282,9 +1313,8 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {// Store pending navigation - will be processed when frames arrivependingNavigationRef.current = targetDate;- // Clear current frame and update date+ // Keep old frame visible while new date's frames load// This triggers the effect that fetches frames for the new date- setCurrentFrame(null);setCurrentIndex(0);setCurrentDate(targetDate);@@ -1385,6 +1415,8 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {<CurrentFrameTimelinecurrentFrame={currentFrame}allDeviceIds={allDeviceIds}+ searchNavFrame={searchNavFrame}+ onSearchNavComplete={() => setSearchNavFrame(false)}onNavigate={(direction) => {// newer = lower index (-1), older = higher index (+1)const newIndex = direction === "next"@@ -1739,9 +1771,18 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {if (!isSameDay(targetDate, currentDate)) {navigateDirectToDate(targetDate);} else {- pendingNavigationRef.current = null;- jumpToTime(targetDate);- setSeekingTimestamp(null);+ // Set pending ref so the effect handles it if jumpToTime+ // fails (e.g. frames are stale from a previous date swap)+ pendingNavigationRef.current = targetDate;+ const hasTargetDayFrames = frames.some(f =>+ isSameDay(new Date(f.timestamp), targetDate)+ );+ if (hasTargetDayFrames) {+ jumpToTime(targetDate);+ pendingNavigationRef.current = null;+ setSeekingTimestamp(null);+ }+ // else: pending effect will handle when correct frames arrive}}}/>@@ -1757,9 +1798,18 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {if (!isSameDay(targetDate, currentDate)) {navigateDirectToDate(targetDate);} else {- pendingNavigationRef.current = null;- jumpToTime(targetDate);- setSeekingTimestamp(null);+ // Set pending ref so the effect handles it if jumpToTime+ // fails (e.g. frames are stale from a previous date swap)+ pendingNavigationRef.current = targetDate;+ const hasTargetDayFrames = frames.some(f =>+ isSameDay(new Date(f.timestamp), targetDate)+ );+ if (hasTargetDayFrames) {+ jumpToTime(targetDate);+ pendingNavigationRef.current = null;+ setSeekingTimestamp(null);+ }+ // else: pending effect will handle when correct frames arrive}}}/>diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsxindex 63d65dedd..5e777a967 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx@@ -49,6 +49,8 @@ interface TimelineState {// Optimistic UI stateisConnected: boolean; // WebSocket connection statushasCachedData: boolean; // Whether we loaded from cache+ // When true, next flushFrameBuffer replaces frames instead of merging (date swap)+ pendingDateSwap: boolean;// Deep link navigation — persists across component mountspendingNavigation: { timestamp: string; frameId?: string } | null;@@ -86,6 +88,7 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({lastFlushTimestamp: 0,isConnected: false,hasCachedData: false,+ pendingDateSwap: false,pendingNavigation: null,setPendingNavigation: (nav) => set({ pendingNavigation: nav }),@@ -97,10 +100,17 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({clearNewFramesCount: () => set({ newFramesCount: 0 }),clearSentRequestForDate: (date: Date) => {- const dateKey = `${date.getDate()}-${date.getMonth()}-${date.getFullYear()}`;+ const targetDay = date.toDateString();set((state) => {- const newSentRequests = new Set(state.sentRequests);- newSentRequests.delete(dateKey);+ const newSentRequests = new Set<string>();+ for (const key of state.sentRequests) {+ // Key format: "startISO_endISO" — check if start date matches+ const startIso = key.split('_')[0];+ try {+ if (new Date(startIso).toDateString() === targetDay) continue;+ } catch { /* keep non-matching keys */ }+ newSentRequests.add(key);+ }return { sentRequests: newSentRequests };});},@@ -134,7 +144,8 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({}},- // Clear frames when navigating to a new date to avoid confusion between old/new frames+ // Prepare for date navigation — keep old frames visible while new ones load.+ // Sets pendingDateSwap so flushFrameBuffer replaces frames atomically on first batch.clearFramesForNavigation: () => {// Clear the frame buffer tooframeBuffer = [];@@ -148,16 +159,11 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({requestTimeoutTimer = null;}requestRetryCount = 0;- // Clear frames + timestamps so:- // 1) request timeout logic correctly sees "no frames" and retries- // 2) pendingNavigation effect triggers on first batch from new date- // 3) no stale old-date frames confuse the frame selection- // The full-screen "Loading Timeline" blocker is suppressed during- // navigation by the isNavigating flag in timeline.tsx.+ // Keep frames + frameTimestamps so old content stays visible.+ // pendingDateSwap tells flushFrameBuffer to replace (not merge) on next batch.set(() => ({- frames: [],- frameTimestamps: new Set<string>(),sentRequests: new Set<string>(),+ pendingDateSwap: true,isLoading: true,loadingProgress: { loaded: 0, isStreaming: false },error: null,@@ -167,8 +173,14 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({hasDateBeenFetched: (date: Date) => {const { sentRequests } = get();- const dateKey = `${date.getDate()}-${date.getMonth()}-${date.getFullYear()}`;- return sentRequests.has(dateKey);+ const targetDay = date.toDateString();+ for (const key of sentRequests) {+ const startIso = key.split('_')[0];+ try {+ if (new Date(startIso).toDateString() === targetDay) return true;+ } catch { /* skip malformed keys */ }+ }+ return false;},// Flush accumulated frames to state - called periodically instead of on every message@@ -179,7 +191,42 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({frameBuffer = [];set((state) => {- // Filter out duplicates using O(1) Set lookup+ // If pendingDateSwap, replace frames entirely with new batch (date changed)+ if (state.pendingDateSwap) {+ // Frames received - clear the request timeout (no need to retry)+ if (requestTimeoutTimer) {+ clearTimeout(requestTimeoutTimer);+ requestTimeoutTimer = null;+ }+ requestRetryCount = 0;++ const newTimestamps = new Set<string>();+ framesToFlush.forEach((frame) => newTimestamps.add(frame.timestamp));+ const sortedFrames = [...framesToFlush].sort(+ (a, b) => b.timestamp.localeCompare(a.timestamp)+ );++ // Debounce cache save+ if (cacheSaveTimer) clearTimeout(cacheSaveTimer);+ cacheSaveTimer = setTimeout(() => {+ cacheSaveTimer = null;+ saveFramesToCache(sortedFrames, state.currentDate);+ }, CACHE_SAVE_DEBOUNCE_MS);++ return {+ frames: sortedFrames,+ frameTimestamps: newTimestamps,+ pendingDateSwap: false,+ isLoading: false,+ loadingProgress: { loaded: sortedFrames.length, isStreaming: true },+ message: null,+ error: null,+ newFramesCount: 0,+ lastFlushTimestamp: Date.now(),+ };+ }++ // Normal merge path — filter out duplicates using O(1) Set lookupconst newUniqueFrames = framesToFlush.filter((frame) => !state.frameTimestamps.has(frame.timestamp));@@ -509,7 +556,8 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({fetchTimeRange: async (startTime: Date, endTime: Date) => {const { websocket, sentRequests } = get();- const requestKey = `${startTime.getDate()}-${startTime.getMonth()}-${startTime.getFullYear()}`;+ // Use ISO range as key so narrow-window and full-day fetches get distinct keys+ const requestKey = `${startTime.toISOString()}_${endTime.toISOString()}`;if (sentRequests.has(requestKey)) {console.log("Request already sent, skipping...");@@ -536,10 +584,10 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({}requestTimeoutTimer = setTimeout(() => {requestTimeoutTimer = null;- const currentFrames = get().frames;+ const { frames: currentFrames, pendingDateSwap: stillSwapping } = get();- // If still no frames and we haven't exceeded retries, retry- if (currentFrames.length === 0 && requestRetryCount < MAX_REQUEST_RETRIES) {+ // Retry if no frames arrived (or still waiting for date swap to complete)+ if ((currentFrames.length === 0 || stillSwapping) && requestRetryCount < MAX_REQUEST_RETRIES) {requestRetryCount++;console.log(`No frames received, retrying (${requestRetryCount}/${MAX_REQUEST_RETRIES})...`);@@ -552,7 +600,7 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({// Retry the requestget().fetchTimeRange(startTime, endTime);- } else if (currentFrames.length === 0 && requestRetryCount >= MAX_REQUEST_RETRIES) {+ } else if ((currentFrames.length === 0 || stillSwapping) && requestRetryCount >= MAX_REQUEST_RETRIES) {console.log("Max retries reached, no frames available");set({isLoading: false,@@ -578,7 +626,7 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({endTime.setHours(23, 59, 59, 999);const { websocket, sentRequests } = get();- const requestKey = `${nextDay.getDate()}-${nextDay.getMonth()}-${nextDay.getFullYear()}`;+ const requestKey = `${nextDay.toISOString()}_${endTime.toISOString()}`;if (sentRequests.has(requestKey)) {console.log("Request already sent, skipping...");@@ -605,18 +653,22 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({// Always reset to today when the window is focused.// The window is hidden/shown (not destroyed), so stale dates persist.const today = new Date();+ const todayStr = today.toDateString();- // Clear sentRequests for today so we re-fetch fresh data- const todayKey = `${today.getDate()}-${today.getMonth()}-${today.getFullYear()}`;-// Also clear the old date's sentRequests in case it was differentconst { currentDate: oldDate } = get();- const oldDateKey = `${oldDate.getDate()}-${oldDate.getMonth()}-${oldDate.getFullYear()}`;+ const oldDateStr = oldDate.toDateString();set((state) => {- const newSentRequests = new Set(state.sentRequests);- newSentRequests.delete(todayKey);- newSentRequests.delete(oldDateKey);+ const newSentRequests = new Set<string>();+ for (const key of state.sentRequests) {+ const startIso = key.split('_')[0];+ try {+ const keyDateStr = new Date(startIso).toDateString();+ if (keyDateStr === todayStr || keyDateStr === oldDateStr) continue;+ } catch { /* keep non-matching keys */ }+ newSentRequests.add(key);+ }return {sentRequests: newSentRequests,currentDate: today,@@ -626,7 +678,7 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({};});- console.log("Window focused, cleared sentRequests for:", todayKey);+ console.log("Window focused, cleared sentRequests for:", todayStr);// If WebSocket is open, fetch today's dataif (websocket && websocket.readyState === WebSocket.OPEN) {diff --git a/crates/screenpipe-server/src/routes/streaming.rs b/crates/screenpipe-server/src/routes/streaming.rsindex 70e3b8e7b..90c5bfee8 100644--- a/crates/screenpipe-server/src/routes/streaming.rs+++ b/crates/screenpipe-server/src/routes/streaming.rs@@ -262,8 +262,13 @@ async fn handle_stream_frames_socket(sent_ids_clone.lock().await.clear();// Decide: is this a "today" request (use cache) or past day (use DB)?- let is_today = cache_clone.is_today(start_time).await- || cache_clone.is_today(end_time).await;+ // Only use hot_cache if end_time reaches into the present/future.+ // If the entire range is in the past (even on today's calendar day),+ // use database — hot_cache only has recent in-memory frames.+ let now = Utc::now();+ let is_today = (cache_clone.is_today(start_time).await+ || cache_clone.is_today(end_time).await)+ && end_time >= now;info!("WebSocket stream request: {} to {} (source={})",