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(timeline): measure visible first frame latency (#6652)
Ezra Ellettee094b5057032
diff --git a/apps/screenpipe-app-tauri/components/rewind/__tests__/timeline-empty-state.test.tsx b/apps/screenpipe-app-tauri/components/rewind/__tests__/timeline-empty-state.test.tsxindex d629bcd39..e174047e3 100644--- a/apps/screenpipe-app-tauri/components/rewind/__tests__/timeline-empty-state.test.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/__tests__/timeline-empty-state.test.tsx@@ -19,7 +19,7 @@*/import React from "react";-import { render, screen, cleanup } from "@testing-library/react";+import { act, render, screen, cleanup, fireEvent, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const DISCORD_URL = "discord.com/channels/1120795297094832337";@@ -60,10 +60,13 @@ const store = vi.hoisted(() => ({error: null as unknown,message: null as string | null,frameStatus: "disabled",+ hasCachedData: false,}));// Hoisted alongside the mocks — vi.mock factories run before module scope.const noop = vi.hoisted(() => () => {});+const posthogCapture = vi.hoisted(() => vi.fn());+const tauriEventListeners = vi.hoisted(() => new Map<string, Array<(event: { payload: unknown }) => void>>());vi.mock("@/lib/hooks/use-timeline-store", () => ({useTimelineStore: Object.assign(@@ -80,6 +83,7 @@ vi.mock("@/lib/hooks/use-timeline-store", () => ({clearFramesForNavigation: noop,pendingNavigation: null,setPendingNavigation: noop,+ hasCachedData: store.hasCachedData,}),{getState: () => ({ currentDate: new Date("2026-08-05T12:00:00+05:30") }),@@ -208,7 +212,16 @@ vi.mock("@/components/rewind/hooks/use-timeline-keyboard", () => ({// Child components are not under test — render nothing so the assertions can// only be satisfied by Timeline's own markup.vi.mock("@/components/rewind/current-frame-timeline", () => ({- CurrentFrameTimeline: () => <div data-testid="frame-canvas" />,+ CurrentFrameTimeline: ({ onFrameLoadSuccess }: { onFrameLoadSuccess?: (details: { frameId: string; mode: "snapshot_direct" }) => void }) => (+ <div data-testid="frame-canvas">+ <button+ type="button"+ onClick={() => onFrameLoadSuccess?.({ frameId: "567", mode: "snapshot_direct" })}+ >+ finish frame load+ </button>+ </div>+ ),}));vi.mock("@/components/rewind/timeline/timeline", () => ({ TimelineSlider: () => null }));vi.mock("@/components/rewind/timeline/timeline-controls", () => ({@@ -224,9 +237,21 @@ vi.mock("@/components/rewind/search-result-strip", () => ({}));vi.mock("@tauri-apps/api/event", () => ({- listen: async () => () => {},+ listen: async (eventName: string, callback: (event: { payload: unknown }) => void) => {+ const listeners = tauriEventListeners.get(eventName) ?? [];+ listeners.push(callback);+ tauriEventListeners.set(eventName, listeners);+ return () => {+ tauriEventListeners.set(eventName, listeners.filter((listener) => listener !== callback));+ };+ },emit: async () => {},}));+vi.mock("@tauri-apps/api/window", () => ({+ getCurrentWindow: () => ({ isFocused: async () => false }),+ currentMonitor: async () => null,+ cursorPosition: async () => ({ x: 0, y: 0 }),+}));vi.mock("@/lib/utils/tauri", () => ({ commands: { showWindow: vi.fn() } }));vi.mock("@/lib/api", () => ({ localFetch: async () => ({ ok: true, json: async () => ({}) }) }));vi.mock("@/lib/actions/get-start-date", () => ({@@ -240,7 +265,7 @@ vi.mock("@/lib/chat-utils", () => ({formatShortcutDisplay: (s: string) => s,}));vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));-vi.mock("posthog-js", () => ({ default: { capture: vi.fn() } }));+vi.mock("posthog-js", () => ({ default: { capture: posthogCapture } }));import Timeline from "@/components/rewind/timeline";@@ -270,12 +295,73 @@ beforeEach(() => {error: null,message: null,frameStatus: "disabled",+ hasCachedData: false,});+ posthogCapture.mockClear();+ tauriEventListeners.clear();});afterEach(cleanup);describe("Timeline empty state (mounted)", () => {+ it("measures a real displayed frame and uses the cache source instead of frame count", () => {+ let now = 1_000;+ const nowSpy = vi.spyOn(performance, "now").mockImplementation(() => now);+ setStore({ frames: [aug5Frame()], hasCachedData: true });++ render(<Timeline embedded />);+ expect(+ posthogCapture.mock.calls.some(([event]) => event === "timeline_time_to_first_frame"),+ ).toBe(false);++ now = 1_125;+ fireEvent.click(screen.getByRole("button", { name: "finish frame load" }));++ expect(posthogCapture).toHaveBeenCalledWith("timeline_time_to_first_frame", {+ measurement_version: 2,+ duration_ms: 125,+ had_cache: true,+ frames_count: 1,+ frame_id: "567",+ load_mode: "snapshot_direct",+ surface: "home",+ });+ nowSpy.mockRestore();+ });++ it("excludes time while the overlay window is hidden", async () => {+ let now = 10_000;+ const nowSpy = vi.spyOn(performance, "now").mockImplementation(() => now);+ setStore({ frames: [aug5Frame()], hasCachedData: false });++ render(<Timeline />);+ now = 610_000;+ fireEvent.click(screen.getByRole("button", { name: "finish frame load" }));+ expect(+ posthogCapture.mock.calls.some(([event]) => event === "timeline_time_to_first_frame"),+ ).toBe(false);++ await waitFor(() => {+ expect(tauriEventListeners.get("window-focused")?.length).toBeGreaterThan(0);+ });+ act(() => {+ for (const listener of tauriEventListeners.get("window-focused") ?? []) {+ listener({ payload: true });+ }+ });++ expect(posthogCapture).toHaveBeenCalledWith("timeline_time_to_first_frame", {+ measurement_version: 2,+ duration_ms: 0,+ had_cache: false,+ frames_count: 1,+ frame_id: "567",+ load_mode: "snapshot_direct",+ surface: "overlay",+ });+ nowSpy.mockRestore();+ });+/*** The reported journey. Visit 2 is the one that used to paint a blank* canvas: the component remounts while the store still holds Aug 5, sodiff --git a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsxindex d83ae5b3b..e95c85bf3 100644--- a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx@@ -18,7 +18,10 @@ import { useSettings } from "@/lib/hooks/use-settings";import { ImageOff, ChevronLeft, ChevronRight, Copy, ImageIcon, Link2, MessageCircle, Type } from "lucide-react";import { usePipes } from "@/lib/hooks/use-pipes";import { toast } from "@/components/ui/use-toast";-import { useFrameLoading } from "@/components/rewind/hooks/use-frame-loading";+import {+ type FrameLoadSuccessDetails,+ useFrameLoading,+} from "@/components/rewind/hooks/use-frame-loading";import { useLiveText } from "@/components/rewind/hooks/use-live-text";import { useFrameActions } from "@/components/rewind/hooks/use-frame-actions";import { commands } from "@/lib/utils/tauri";@@ -85,6 +88,7 @@ interface CurrentFrameTimelineProps {canNavigateNext?: boolean;onFrameUnavailable?: () => void;onFrameLoadError?: () => void;+ onFrameLoadSuccess?: (details: FrameLoadSuccessDetails) => void;onUrlsDetected?: (urls: DetectedUrl[]) => void;/** all unique device_ids seen in this session (e.g. ["monitor_1", "monitor_4"]) */allDeviceIds?: string[];@@ -136,6 +140,7 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({canNavigateNext = true,onFrameUnavailable,onFrameLoadError,+ onFrameLoadSuccess,onUrlsDetected,allDeviceIds,searchNavFrame,@@ -239,6 +244,7 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({onSearchNavComplete,onFrameUnavailable,onFrameLoadError,+ onFrameLoadSuccess,videoRef,isPlaying,playbackSpeed,diff --git a/apps/screenpipe-app-tauri/components/rewind/hooks/use-frame-loading.ts b/apps/screenpipe-app-tauri/components/rewind/hooks/use-frame-loading.tsindex b6e63409c..0f74dd697 100644--- a/apps/screenpipe-app-tauri/components/rewind/hooks/use-frame-loading.ts+++ b/apps/screenpipe-app-tauri/components/rewind/hooks/use-frame-loading.ts@@ -42,6 +42,11 @@ function markChunkFailed(path: string): void {// Cache calibrated fps per video file path so we only compute onceconst calibratedFpsCache = new Map<string, number>();+export interface FrameLoadSuccessDetails {+ frameId: string;+ mode: "video_seek" | "snapshot_direct" | "search_nav_fallback" | "ffmpeg_fallback";+}+export function useFrameLoading(opts: {currentFrame: StreamTimeSeriesResponse;adjacentFrames?: StreamTimeSeriesResponse[];@@ -50,6 +55,7 @@ export function useFrameLoading(opts: {onSearchNavComplete?: () => void;onFrameUnavailable?: () => void;onFrameLoadError?: () => void;+ onFrameLoadSuccess?: (details: FrameLoadSuccessDetails) => void;videoRef: React.RefObject<HTMLVideoElement | null>;/** Timeline is playing — lets HD chunks play natively instead of seek-stepping */isPlaying?: boolean;@@ -64,6 +70,7 @@ export function useFrameLoading(opts: {onSearchNavComplete,onFrameUnavailable,onFrameLoadError,+ onFrameLoadSuccess,videoRef,isPlaying,playbackSpeed,@@ -302,6 +309,7 @@ export function useFrameLoading(opts: {setIsLoading(false);setHasError(false);setNaturalDimensions({ width: video.videoWidth, height: video.videoHeight });+ onFrameLoadSuccess?.({ frameId: fid, mode: "video_seek" });return;}@@ -332,6 +340,7 @@ export function useFrameLoading(opts: {width: video.videoWidth,height: video.videoHeight,});+ onFrameLoadSuccess?.({ frameId: fid, mode: "video_seek" });// Analyticsif (frameLoadStartTimeRef.current !== null) {@@ -360,7 +369,7 @@ export function useFrameLoading(opts: {loadedChunkRef.current = null;setUseVideoMode(false);});- }, [debouncedFrame, useVideoMode, getVideoUrl, resolveEffectiveFps, isSnapshotFrame, searchNavFrame, isPlaying, playbackSpeed]);+ }, [debouncedFrame, useVideoMode, getVideoUrl, resolveEffectiveFps, isSnapshotFrame, searchNavFrame, isPlaying, playbackSpeed, onFrameLoadSuccess]);// Safety net: the <video> must only ever be *playing* during HD native// playback. Pause it in every other state (paused, scrubbing, normal@@ -396,6 +405,10 @@ export function useFrameLoading(opts: {setIsLoading(false);setHasError(false);setNaturalDimensions({ width: img.naturalWidth, height: img.naturalHeight });+ onFrameLoadSuccess?.({+ frameId: debouncedFrame.frameId,+ mode: "snapshot_direct",+ });if (frameLoadStartTimeRef.current !== null) {const loadTime = performance.now() - frameLoadStartTimeRef.current;posthog.capture("timeline_frame_load_time", {@@ -417,7 +430,7 @@ export function useFrameLoading(opts: {});return () => { cancelled = true; };- }, [isSnapshotFrame, snapshotFailed, debouncedFrame?.filePath, debouncedFrame?.frameId, getVideoUrl]);+ }, [isSnapshotFrame, snapshotFailed, debouncedFrame?.filePath, debouncedFrame?.frameId, getVideoUrl, onFrameLoadSuccess]);// Fallback: ffmpeg <img> mode (same as old behavior)// Skipped for snapshot frames that loaded successfully via asset protocol@@ -448,6 +461,12 @@ export function useFrameLoading(opts: {setIsLoading(false);setHasError(false);setNaturalDimensions({ width: img.naturalWidth, height: img.naturalHeight });+ if (debouncedFrame?.frameId) {+ onFrameLoadSuccess?.({+ frameId: debouncedFrame.frameId,+ mode: searchNavFrame ? "search_nav_fallback" : "ffmpeg_fallback",+ });+ }if (frameLoadStartTimeRef.current !== null) {const loadTime = performance.now() - frameLoadStartTimeRef.current;posthog.capture("timeline_frame_load_time", {diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline.tsxindex 2e7071e66..e2c5d4218 100644--- a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx@@ -36,6 +36,7 @@ import { useAudioPlayback } from "@/lib/hooks/use-audio-playback";import { useHealthCheck } from "@/lib/hooks/use-health-check";import { useSettings } from "@/lib/hooks/use-settings";import { usePipes, type TemplatePipe } from "@/lib/hooks/use-pipes";+import type { FrameLoadSuccessDetails } from "@/components/rewind/hooks/use-frame-loading";import posthog from "posthog-js";import { toast } from "@/components/ui/use-toast";@@ -136,7 +137,11 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {// Performance tracking refsconst timelineOpenedAtRef = useRef<number>(performance.now());- const firstFrameDisplayedRef = useRef<boolean>(false);+ const firstFrameMeasurementStartedAtRef = useRef<number | null>(null);+ const firstFrameReadyRef = useRef<FrameLoadSuccessDetails | null>(null);+ const firstFrameMeasuredRef = useRef(false);+ const firstFrameHadCacheRef = useRef(false);+ const firstFrameCountRef = useRef(0);const totalLoadingTimeRef = useRef<number>(0);const loadingStartTimeRef = useRef<number | null>(null);const framesViewedRef = useRef<number>(0);@@ -196,7 +201,7 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {// Note: audio transcript is now on-demand (opened via subtitle bar click)- const { currentDate, setCurrentDate, fetchTimeRange, hasDateBeenFetched, onWindowFocus, clearNewFramesCount, clearSentRequestForDate, clearFramesForNavigation, pendingNavigation, setPendingNavigation } =+ const { currentDate, setCurrentDate, fetchTimeRange, hasDateBeenFetched, onWindowFocus, clearNewFramesCount, clearSentRequestForDate, clearFramesForNavigation, pendingNavigation, setPendingNavigation, hasCachedData } =useTimelineStore();const { frames, isLoading, error, message, fetchNextDayData, websocket } =@@ -692,6 +697,69 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {// blocker — the inline spinner on the date control is enough feedback.const hasInitialFrames = frames.length > 0;const showBlockingLoader = isLoading && !hasInitialFrames && !isNavigating;+ firstFrameHadCacheRef.current = hasCachedData;+ firstFrameCountRef.current = frames.length;++ const captureFirstDisplayedFrame = useCallback(() => {+ const startedAt = firstFrameMeasurementStartedAtRef.current;+ const readyFrame = firstFrameReadyRef.current;+ if (startedAt === null || !readyFrame || firstFrameMeasuredRef.current) return;++ firstFrameMeasuredRef.current = true;+ posthog.capture("timeline_time_to_first_frame", {+ measurement_version: 2,+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),+ had_cache: firstFrameHadCacheRef.current,+ frames_count: firstFrameCountRef.current,+ frame_id: readyFrame.frameId,+ load_mode: readyFrame.mode,+ surface: embedded ? "home" : "overlay",+ });+ }, [embedded]);++ const beginFirstFrameMeasurement = useCallback(() => {+ if (firstFrameMeasuredRef.current) return;+ firstFrameMeasurementStartedAtRef.current = performance.now();+ captureFirstDisplayedFrame();+ }, [captureFirstDisplayedFrame]);++ const handleFirstFrameLoaded = useCallback((details: FrameLoadSuccessDetails) => {+ firstFrameReadyRef.current = details;+ captureFirstDisplayedFrame();+ }, [captureFirstDisplayedFrame]);++ // The embedded Timeline mounts only when its section is opened. The overlay+ // webview, however, can stay mounted for minutes while its window is hidden,+ // so only count focused/visible time there. A frame decoded in the background+ // is immediately ready on focus instead of inheriting the hidden interval.+ useEffect(() => {+ if (embedded) {+ beginFirstFrameMeasurement();+ return;+ }++ let disposed = false;+ const unlisten = listen<boolean>("window-focused", (event) => {+ if (event.payload) {+ beginFirstFrameMeasurement();+ } else if (!firstFrameMeasuredRef.current) {+ firstFrameMeasurementStartedAtRef.current = null;+ }+ });++ void import("@tauri-apps/api/window").then(({ getCurrentWindow }) =>+ getCurrentWindow().isFocused(),+ ).then((focused) => {+ if (!disposed && focused) beginFirstFrameMeasurement();+ }).catch(() => {+ // The focus event remains authoritative if the initial query is unavailable.+ });++ return () => {+ disposed = true;+ unlisten.then((fn) => fn());+ };+ }, [beginFirstFrameMeasurement, embedded]);// Auto-select first frame when frames arrive and no frame is selected@@ -714,7 +782,6 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {// Track timeline opened and setup session trackinguseEffect(() => {timelineOpenedAtRef.current = performance.now();- firstFrameDisplayedRef.current = false;totalLoadingTimeRef.current = 0;framesViewedRef.current = 0;framesFailedRef.current = 0;@@ -758,24 +825,13 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {}}, [isLoading, showBlockingLoader]);- // Track time to first frame+ // Track frames viewed. First-frame latency is recorded by the successful+ // media-load callback above, not by selecting frame metadata.useEffect(() => {- if (currentFrame && !firstFrameDisplayedRef.current) {- firstFrameDisplayedRef.current = true;- const timeToFirstFrame = performance.now() - timelineOpenedAtRef.current;-- posthog.capture("timeline_time_to_first_frame", {- duration_ms: Math.round(timeToFirstFrame),- had_cache: frames.length > 1, // If we have multiple frames, likely from cache- frames_count: frames.length,- });- }-- // Track frames viewedif (currentFrame) {framesViewedRef.current += 1;}- }, [currentFrame, frames.length]);+ }, [currentFrame]);// Send timeline selection context to chat (optionally with a specific pipe)const sendSelectionToChat = useCallback(async (pipe?: TemplatePipe) => {@@ -1174,6 +1230,7 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {onFrameLoadError={() => {framesFailedRef.current += 1;}}+ onFrameLoadSuccess={handleFirstFrameLoaded}onFrameUnavailable={async () => {// Get the current frame's frame_idconst failedFrameId = frames[currentIndex]?.devices?.[0]?.frame_id;