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

feat: optimistic timeline UI - never show error/loading when user has data (#2161)

Louis Beaumont68836e3fc4d6
diff --git a/screenpipe-app-tauri/app/page.tsx b/screenpipe-app-tauri/app/page.tsx
index f21ca6a4b..7c66e3604 100644
--- a/screenpipe-app-tauri/app/page.tsx
+++ b/screenpipe-app-tauri/app/page.tsx
@@ -13,15 +13,16 @@ import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { commands } from "@/lib/utils/tauri";
import localforage from "localforage";
import { LoginDialog } from "../components/login-dialog";
-import { UpdateBanner, useUpdateListener } from "../components/update-banner";
import { ModelDownloadTracker } from "../components/model-download-tracker";
import Timeline from "@/components/rewind/timeline";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
-import { RefreshCw, AlertTriangle } from "lucide-react";
+import { RefreshCw, AlertTriangle, WifiOff } from "lucide-react";
import { PermissionButtons } from "@/components/status/permission-buttons";
import { usePlatform } from "@/lib/hooks/use-platform";
import SplashScreen from "@/components/splash-screen";
+import { useTimelineStore } from "@/lib/hooks/use-timeline-store";
+import { hasCachedData } from "@/lib/hooks/use-timeline-cache";
export default function Home() {
const { settings, updateSettings, loadUser, reloadStore, isSettingsLoaded, loadingError } = useSettings();
@@ -32,8 +33,29 @@ export default function Home() {
const [isRestarting, setIsRestarting] = useState(false);
const isProcessingRef = useRef(false);
- // Listen for update events from Rust
- useUpdateListener();
+ // Optimistic UI: track if user has any data (cached or live)
+ const { frames, isConnected, loadFromCache } = useTimelineStore();
+ const [hasAnyData, setHasAnyData] = useState(false);
+
+ // Check for cached data on mount
+ useEffect(() => {
+ const checkCache = async () => {
+ const hasCached = await hasCachedData();
+ setHasAnyData(hasCached);
+ if (hasCached) {
+ // Load cached frames immediately for instant display
+ loadFromCache();
+ }
+ };
+ checkCache();
+ }, [loadFromCache]);
+
+ // Update hasAnyData when frames change
+ useEffect(() => {
+ if (frames.length > 0) {
+ setHasAnyData(true);
+ }
+ }, [frames.length]);
// Load onboarding status on mount
useEffect(() => {
@@ -130,6 +152,13 @@ export default function Home() {
}
};
+ // Determine what to show:
+ // 1. If user has data (cached or live) -> always show timeline, even if server is down
+ // 2. If no data AND server is down -> show server error screen
+ // 3. If no data AND server is starting -> show loading
+ const showTimeline = hasAnyData || !isServerDown;
+ const showServerError = !hasAnyData && isServerDown;
+
return (
<div className="flex flex-col items-center flex-1 mx-auto relative scrollbar-hide">
{/* Transparent titlebar area - no drag region to prevent accidental window moves */}
@@ -142,12 +171,20 @@ export default function Home() {
<ChangelogDialog />
<BreakingChangesInstructionsDialog />
<LoginDialog />
- <UpdateDialog />
<ModelDownloadTracker />
- {!isServerDown ? (
+
+ {showTimeline ? (
<div className="w-full scrollbar-hide bg-background relative">
- {/* Show connecting overlay while health check is loading */}
- {isHealthLoading && (
+ {/* Subtle disconnected indicator - only show if we have data but no connection */}
+ {hasAnyData && !isConnected && isServerDown && (
+ <div className="fixed top-10 right-4 z-50 flex items-center gap-2 px-3 py-1.5 bg-muted/90 backdrop-blur-sm rounded-full text-xs text-muted-foreground border">
+ <WifiOff className="h-3 w-3" />
+ <span>reconnecting...</span>
+ </div>
+ )}
+
+ {/* Show connecting overlay only if NO data and still loading */}
+ {!hasAnyData && isHealthLoading && (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
<div className="flex flex-col items-center gap-3">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
@@ -157,7 +194,7 @@ export default function Home() {
)}
<Timeline />
</div>
- ) : (
+ ) : showServerError ? (
<div className="flex items-center justify-center h-screen p-4 bg-background w-full">
<div className="max-w-lg w-full space-y-6">
{/* Header */}
@@ -225,6 +262,14 @@ export default function Home() {
</div>
</div>
</div>
+ ) : (
+ // Fallback loading state
+ <div className="flex items-center justify-center h-screen">
+ <div className="flex flex-col items-center gap-3">
+ <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
+ <p className="text-sm text-muted-foreground">starting up...</p>
+ </div>
+ </div>
)}
</>
) : (
diff --git a/screenpipe-app-tauri/bun.lock b/screenpipe-app-tauri/bun.lock
index d42171a30..a69275e25 100644
--- a/screenpipe-app-tauri/bun.lock
+++ b/screenpipe-app-tauri/bun.lock
@@ -5,7 +5,6 @@
"": {
"name": "screenpipe-app",
"dependencies": {
- "@opencode-ai/sdk": "^1.1.48",
"@patternfly/react-core": "^6.1.0",
"@patternfly/react-log-viewer": "^6.1.0",
"@radix-ui/react-accordion": "^1.2.0",
@@ -361,8 +360,6 @@
"@nodelib/fs.walk": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, ""],
- "@opencode-ai/sdk": ["@opencode-ai/[email protected]", "", {}, "sha512-j5/79X45fUPWVD2Ffm/qvwLclDCdPeV+TYMDrm9to0p4pmzhmeKevCsyiRdLg0o0HE3AFRUnOo2rdO9NetN79A=="],
-
"@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, ""],
"@opentelemetry/api-logs": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg=="],
diff --git a/screenpipe-app-tauri/lib/hooks/use-timeline-cache.tsx b/screenpipe-app-tauri/lib/hooks/use-timeline-cache.tsx
new file mode 100644
index 000000000..d6dd950cf
--- /dev/null
+++ b/screenpipe-app-tauri/lib/hooks/use-timeline-cache.tsx
@@ -0,0 +1,98 @@
+import localforage from "localforage";
+import { StreamTimeSeriesResponse } from "@/components/rewind/timeline";
+
+// Configure localforage for timeline cache
+const timelineCache = localforage.createInstance({
+ name: "screenpipe",
+ storeName: "timeline_cache",
+});
+
+const CACHE_KEY = "cached_frames";
+const CACHE_DATE_KEY = "cached_date";
+const CACHE_TIMESTAMP_KEY = "cache_timestamp";
+const MAX_CACHED_FRAMES = 200; // Keep last 200 frames for instant load
+
+export interface TimelineCache {
+ frames: StreamTimeSeriesResponse[];
+ date: string; // ISO date string
+ timestamp: number; // When cache was saved
+}
+
+/**
+ * Save frames to cache for instant load on next app open
+ */
+export async function saveFramesToCache(
+ frames: StreamTimeSeriesResponse[],
+ date: Date
+): Promise<void> {
+ try {
+ // Only cache the most recent frames to keep storage reasonable
+ const framesToCache = frames.slice(0, MAX_CACHED_FRAMES);
+
+ await timelineCache.setItem(CACHE_KEY, framesToCache);
+ await timelineCache.setItem(CACHE_DATE_KEY, date.toISOString());
+ await timelineCache.setItem(CACHE_TIMESTAMP_KEY, Date.now());
+ } catch (error) {
+ console.warn("Failed to save frames to cache:", error);
+ }
+}
+
+/**
+ * Load cached frames for instant display
+ */
+export async function loadCachedFrames(): Promise<TimelineCache | null> {
+ try {
+ const frames = await timelineCache.getItem<StreamTimeSeriesResponse[]>(CACHE_KEY);
+ const dateStr = await timelineCache.getItem<string>(CACHE_DATE_KEY);
+ const timestamp = await timelineCache.getItem<number>(CACHE_TIMESTAMP_KEY);
+
+ if (!frames || frames.length === 0 || !dateStr) {
+ return null;
+ }
+
+ return {
+ frames,
+ date: dateStr,
+ timestamp: timestamp || Date.now(),
+ };
+ } catch (error) {
+ console.warn("Failed to load cached frames:", error);
+ return null;
+ }
+}
+
+/**
+ * Check if we have any cached data (for determining UI state)
+ */
+export async function hasCachedData(): Promise<boolean> {
+ try {
+ const frames = await timelineCache.getItem<StreamTimeSeriesResponse[]>(CACHE_KEY);
+ return frames !== null && frames.length > 0;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Clear the cache (useful for debugging or user-initiated clear)
+ */
+export async function clearTimelineCache(): Promise<void> {
+ try {
+ await timelineCache.clear();
+ } catch (error) {
+ console.warn("Failed to clear timeline cache:", error);
+ }
+}
+
+/**
+ * Get cache age in milliseconds
+ */
+export async function getCacheAge(): Promise<number | null> {
+ try {
+ const timestamp = await timelineCache.getItem<number>(CACHE_TIMESTAMP_KEY);
+ if (!timestamp) return null;
+ return Date.now() - timestamp;
+ } catch {
+ return null;
+ }
+}
diff --git a/screenpipe-app-tauri/lib/hooks/use-timeline-data.tsx b/screenpipe-app-tauri/lib/hooks/use-timeline-data.tsx
index d4c8a49b4..5a98cf13e 100644
--- a/screenpipe-app-tauri/lib/hooks/use-timeline-data.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-timeline-data.tsx
@@ -1,6 +1,6 @@
import { StreamTimeSeriesResponse } from "@/components/rewind/timeline";
import { useTimelineStore } from "./use-timeline-store";
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
export function useTimelineData(
currentDate: Date,
@@ -14,12 +14,26 @@ export function useTimelineData(
connectWebSocket,
fetchNextDayData,
websocket,
+ loadFromCache,
} = useTimelineStore();
+ const hasInitialized = useRef(false);
+
useEffect(() => {
- // Establish WebSocket connection on mount
- // The connectWebSocket function handles closing existing connections
- connectWebSocket();
+ // Only initialize once
+ if (hasInitialized.current) return;
+ hasInitialized.current = true;
+
+ const initialize = async () => {
+ // 1. First, load cached frames for instant display
+ await loadFromCache();
+
+ // 2. Then establish WebSocket connection for live updates
+ // The connectWebSocket function handles closing existing connections
+ connectWebSocket();
+ };
+
+ initialize();
}, []); // Only connect once when component mounts
// NOTE: Auto-select of first frame is handled in timeline.tsx to avoid
@@ -34,4 +48,3 @@ export function useTimelineData(
websocket, // Expose websocket so timeline.tsx can depend on it
};
}
-
diff --git a/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx b/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx
index c08ad9b8a..afc36306f 100644
--- a/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx
@@ -2,6 +2,7 @@ import { create } from "zustand";
import { StreamTimeSeriesResponse } from "@/components/rewind/timeline";
import { hasFramesForDate } from "../actions/has-frames-date";
import { subDays } from "date-fns";
+import { saveFramesToCache, loadCachedFrames } from "./use-timeline-cache";
// Frame buffer for batching updates - reduces 68 re-renders to ~3-5
let frameBuffer: StreamTimeSeriesResponse[] = [];
@@ -13,7 +14,7 @@ const PROGRESS_UPDATE_INTERVAL_MS = 500; // Only update progress indicator every
// Connection retry logic - don't show error immediately, server might be starting
let connectionAttempts = 0;
let errorGraceTimer: ReturnType<typeof setTimeout> | null = null;
-const MAX_SILENT_RETRIES = 3; // Retry 3 times before showing error
+const MAX_SILENT_RETRIES = 5; // Increased from 3 - retry more before showing error
const RETRY_DELAY_MS = 2000; // Wait 2 seconds between retries
// Request timeout logic - retry if no frames arrive
@@ -28,6 +29,10 @@ let reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
// Track the current WebSocket instance to ignore events from old connections
let currentWsId = 0;
+// Cache save debounce
+let cacheSaveTimer: ReturnType<typeof setTimeout> | null = null;
+const CACHE_SAVE_DEBOUNCE_MS = 2000; // Save cache 2s after last frame update
+
interface TimelineState {
frames: StreamTimeSeriesResponse[];
frameTimestamps: Set<string>; // For O(1) deduplication lookups
@@ -41,6 +46,9 @@ interface TimelineState {
// Track new frames for animation and position adjustment
newFramesCount: number; // How many new frames were added at the front (for animation)
lastFlushTimestamp: number; // Timestamp of last flush (to trigger effects)
+ // Optimistic UI state
+ isConnected: boolean; // WebSocket connection status
+ hasCachedData: boolean; // Whether we loaded from cache
// Actions
setFrames: (frames: StreamTimeSeriesResponse[]) => void;
@@ -57,6 +65,7 @@ interface TimelineState {
clearNewFramesCount: () => void;
clearSentRequestForDate: (date: Date) => void;
clearFramesForNavigation: () => void; // Clear frames when navigating to new date
+ loadFromCache: () => Promise<void>; // Load cached frames on startup
}
export const useTimelineStore = create<TimelineState>((set, get) => ({
@@ -71,6 +80,8 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
sentRequests: new Set<string>(),
newFramesCount: 0,
lastFlushTimestamp: 0,
+ isConnected: false,
+ hasCachedData: false,
setFrames: (frames) => set({ frames }),
setIsLoading: (isLoading) => set({ isLoading }),
@@ -88,6 +99,31 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
});
},
+ // Load cached frames for instant display
+ loadFromCache: async () => {
+ try {
+ const cached = await loadCachedFrames();
+ if (cached && cached.frames.length > 0) {
+ const cachedDate = new Date(cached.date);
+ const timestamps = new Set(cached.frames.map(f => f.timestamp));
+
+ set({
+ frames: cached.frames,
+ frameTimestamps: timestamps,
+ currentDate: cachedDate,
+ isLoading: false, // Show cached data immediately
+ hasCachedData: true,
+ message: null,
+ error: null,
+ });
+
+ console.log(`Loaded ${cached.frames.length} frames from cache`);
+ }
+ } catch (error) {
+ console.warn("Failed to load from cache:", error);
+ }
+ },
+
// Clear frames when navigating to a new date to avoid confusion between old/new frames
clearFramesForNavigation: () => {
// Clear the frame buffer too
@@ -96,14 +132,15 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
clearTimeout(flushTimer);
flushTimer = null;
}
- set({
- frames: [],
- frameTimestamps: new Set<string>(),
+ // DON'T clear frames - keep showing stale data while loading new
+ // Only clear the request tracking and show loading indicator
+ set((state) => ({
+ sentRequests: new Set<string>(),
isLoading: true,
- loadingProgress: { loaded: 0, isStreaming: false },
+ loadingProgress: { loaded: state.frames.length, isStreaming: false },
error: null,
- message: null,
- });
+ message: "loading...",
+ }));
},
hasDateBeenFetched: (date: Date) => {
@@ -173,6 +210,15 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
}
}
+ // Debounce cache save - don't save on every flush
+ if (cacheSaveTimer) {
+ clearTimeout(cacheSaveTimer);
+ }
+ cacheSaveTimer = setTimeout(() => {
+ cacheSaveTimer = null;
+ saveFramesToCache(mergedFrames, state.currentDate);
+ }, CACHE_SAVE_DEBOUNCE_MS);
+
return {
frames: mergedFrames,
frameTimestamps: updatedTimestamps,
@@ -206,16 +252,23 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
existingWs.close();
}
- // Reset state for fresh data when reconnecting
+ // OPTIMISTIC: Don't reset frames on reconnect - keep showing existing data
+ // Only reset request tracking and connection state
+ const currentFrames = get().frames;
+ const currentTimestamps = get().frameTimestamps;
+
set({
- frames: [],
- frameTimestamps: new Set<string>(),
+ // Keep existing frames visible!
+ frames: currentFrames,
+ frameTimestamps: currentTimestamps,
sentRequests: new Set<string>(),
- isLoading: true,
- loadingProgress: { loaded: 0, isStreaming: false },
+ isLoading: currentFrames.length === 0, // Only show loading if no frames
+ loadingProgress: { loaded: currentFrames.length, isStreaming: false },
error: null,
- message: null,
+ message: currentFrames.length > 0 ? null : "connecting...",
+ isConnected: false,
});
+
frameBuffer = [];
requestRetryCount = 0; // Reset retry counter on reconnection
if (progressUpdateTimer) {
@@ -240,12 +293,14 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
errorGraceTimer = null;
}
+ const currentFrames = get().frames;
set({
websocket: ws,
error: null,
message: null,
- isLoading: true,
- loadingProgress: { loaded: 0, isStreaming: true }
+ isLoading: currentFrames.length === 0,
+ loadingProgress: { loaded: currentFrames.length, isStreaming: true },
+ isConnected: true,
});
console.log("WebSocket connection established");
@@ -274,13 +329,11 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
if (data === "keep-alive-text") {
// Flush any pending frames when we get keep-alive
get().flushFrameBuffer();
+ const currentFrames = get().frames;
set((state) => ({
error: null,
isLoading: false,
- message:
- state.message === "please wait..."
- ? state.message
- : "please wait...",
+ message: currentFrames.length === 0 ? "waiting for data..." : null,
}));
return;
}
@@ -288,7 +341,11 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
// Handle error messages
if (data.error) {
get().flushFrameBuffer(); // Flush before error
- set({ error: data.error, isLoading: false });
+ // OPTIMISTIC: Don't show error if we have frames
+ const currentFrames = get().frames;
+ if (currentFrames.length === 0) {
+ set({ error: data.error, isLoading: false });
+ }
return;
}
@@ -335,10 +392,14 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
}
} catch (error) {
console.error("Failed to parse frame data:", error);
- set({
- error: "Failed to parse server response",
- isLoading: false,
- });
+ // OPTIMISTIC: Don't show error if we have frames
+ const currentFrames = get().frames;
+ if (currentFrames.length === 0) {
+ set({
+ error: "Failed to parse server response",
+ isLoading: false,
+ });
+ }
}
};
@@ -349,11 +410,17 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
console.error("WebSocket error:", error);
connectionAttempts++;
+ const currentFrames = get().frames;
+
// Silent retry if under max attempts (server might be starting)
if (connectionAttempts < MAX_SILENT_RETRIES) {
console.log(`Connection attempt ${connectionAttempts}/${MAX_SILENT_RETRIES}, retrying...`);
- // Keep showing loading state, not error
- set({ isLoading: true, message: "connecting to screenpipe..." });
+ // OPTIMISTIC: Keep showing existing frames, just update connection status
+ set({
+ isLoading: currentFrames.length === 0,
+ message: currentFrames.length === 0 ? "connecting to screenpipe..." : null,
+ isConnected: false,
+ });
// Schedule retry
if (!errorGraceTimer) {
@@ -363,8 +430,13 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
}, RETRY_DELAY_MS);
}
} else {
- // Max retries exceeded, show error
- set({ error: "Connection error occurred", isLoading: false });
+ // Max retries exceeded - but still don't block if we have frames
+ if (currentFrames.length === 0) {
+ set({ error: "Connection error occurred", isLoading: false, isConnected: false });
+ } else {
+ // Have frames - show subtle indicator, not error
+ set({ error: null, isLoading: false, isConnected: false, message: null });
+ }
}
};
@@ -390,13 +462,18 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
}
get().flushFrameBuffer();
- // Only show "Connection closed" if we had a successful connection before
- if (connectionAttempts === 0) {
+ const currentFrames = get().frames;
+
+ // OPTIMISTIC: Only show message if no frames
+ if (connectionAttempts === 0 && currentFrames.length === 0) {
set({
message: "Connection closed",
isLoading: false,
- loadingProgress: { loaded: get().frames.length, isStreaming: false }
+ loadingProgress: { loaded: 0, isStreaming: false },
+ isConnected: false,
});
+ } else {
+ set({ isConnected: false });
}
// Reset attempts and reconnect after delay (tracked to prevent cascade)
@@ -527,4 +604,3 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
}
},
}));
-