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
improve timeline
Louis Beaumontc83f18d272ad
diff --git a/screenpipe-app-tauri/app/timeline/page.tsx b/screenpipe-app-tauri/app/timeline/page.tsxindex e49beeb31..4f9c18976 100644--- a/screenpipe-app-tauri/app/timeline/page.tsx+++ b/screenpipe-app-tauri/app/timeline/page.tsx@@ -1,5 +1,5 @@"use client";-import { useEffect, useState, useRef } from "react";+import { useEffect, useState, useRef, useMemo, useCallback } from "react";import { OpenAI } from "openai";import { generateId, Message } from "ai";import { useSettings } from "@/lib/hooks/use-settings";@@ -19,6 +19,17 @@ import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";import { platform } from "@tauri-apps/plugin-os";import posthog from "posthog-js";+import { invoke } from "@tauri-apps/api/core";+import {+ TimelineDock,+ TimelineDockIcon,+ TimelineIconsSection,+} from "@/components/timeline/timeline-dock";+import { debounce, throttle } from "lodash";+import { TimelineBlocks } from "@/components/timeline/timeline-block";+import { TimeLabels } from "@/components/timeline/time-labels";+import { CurrentTimeIndicator } from "@/components/timeline/current-time-indicator";+import { ChatPanel } from "@/components/timeline/chat-panel";interface StreamTimeSeriesResponse {timestamp: string;@@ -61,6 +72,10 @@ interface Agent {dataSelector: (frames: StreamTimeSeriesResponse[]) => any;}+interface AppIconCache {+ [key: string]: string; // app_name -> base64 icon+}+const AGENTS: Agent[] = [{id: "context-master",@@ -113,6 +128,157 @@ const AGENTS: Agent[] = [},];+export interface TimeBlock {+ appName: string;+ startTime: Date;+ endTime: Date;+ color: string; // We'll generate colors based on app names+}+export interface TimelineBlock extends TimeBlock {+ left: number; // percentage position from left+ width: number; // percentage width+}++function getAppColor(appName: string): string {+ // Simple hash function to generate consistent colors for apps+ let hash = 0;+ for (let i = 0; i < appName.length; i++) {+ hash = appName.charCodeAt(i) + ((hash << 5) - hash);+ }++ // Convert to RGB - using mostly blue and green hues for a tech feel+ const hue = Math.abs(hash) % 360;+ return `hsl(${hue}, 70%, 50%)`;+}++function calculateTimeBlocks(frames: any[]): TimeBlock[] {+ if (frames.length === 0) return [];++ const timeRange = getTimelineRange(frames);+ const blocks: TimeBlock[] = [];+ let currentBlock: TimeBlock | null = null;++ // Sort frames by timestamp+ // const sortedFrames = [...frames].sort(+ // (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()+ // );++ frames.forEach((frame) => {+ const timestamp = new Date(frame.timestamp);+ const appName = frame.devices[0].metadata.app_name;++ // Skip frames outside the timeline range+ if (timestamp < timeRange.start || timestamp > timeRange.end) {+ return;+ }++ if (!currentBlock) {+ currentBlock = {+ appName,+ startTime: timestamp,+ endTime: timestamp,+ color: getAppColor(appName),+ };+ } else if (currentBlock.appName !== appName) {+ // App changed, close current block and start new one+ currentBlock.endTime = timestamp;+ blocks.push(currentBlock);+ currentBlock = {+ appName,+ startTime: timestamp,+ endTime: timestamp,+ color: getAppColor(appName),+ };+ } else {+ // Same app, update end time+ currentBlock.endTime = timestamp;+ }+ });++ // Add the last block+ if (currentBlock) {+ blocks.push(currentBlock);+ }++ return blocks;+}++function getTimelineRange(frames: StreamTimeSeriesResponse[]): {+ start: Date;+ end: Date;+} {+ // Default range: 8am to current time+ const now = new Date();+ const defaultEnd = now;+ const defaultStart = new Date(now);+ defaultStart.setHours(8, 0, 0, 0);++ if (frames.length === 0) {+ return { start: defaultStart, end: defaultEnd };+ }++ // Find actual data range+ const timestamps = frames.map((f) => new Date(f.timestamp));+ const dataStart = new Date(Math.min(...timestamps.map((t) => t.getTime())));+ const dataEnd = new Date(Math.max(...timestamps.map((t) => t.getTime())));++ // Expand range if data exists outside default range+ return {+ start:+ dataStart.getTime() < defaultStart.getTime() ? dataStart : defaultStart,+ end: dataEnd.getTime() > defaultEnd.getTime() ? dataEnd : defaultEnd,+ };+}++function getUniqueAppRanges(+ blocks: TimeBlock[],+ mergeThresholdMs: number = 300000+): TimelineBlock[] {+ if (blocks.length === 0) return [];++ const sortedBlocks = [...blocks].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime()+ );++ const mergedBlocks = sortedBlocks.reduce((acc: TimeBlock[], curr) => {+ const lastBlock = acc[acc.length - 1];++ if (!lastBlock) {+ return [curr];+ }++ if (+ lastBlock.appName === curr.appName &&+ curr.startTime.getTime() - lastBlock.endTime.getTime() <= mergeThresholdMs+ ) {+ lastBlock.endTime = new Date(+ Math.max(lastBlock.endTime.getTime(), curr.endTime.getTime())+ );+ return acc;+ }++ return [...acc, curr];+ }, []);++ // Use dynamic range instead of full day+ // @ts-ignore+ const timeRange = getTimelineRange(frames);+ const totalMs = timeRange.end.getTime() - timeRange.start.getTime();++ return mergedBlocks.map((block) => {+ const left =+ ((block.startTime.getTime() - timeRange.start.getTime()) / totalMs) * 100;+ const width =+ ((block.endTime.getTime() - block.startTime.getTime()) / totalMs) * 100;++ return {+ ...block,+ left: Math.max(0, Math.min(100, left)),+ width: Math.max(0, Math.min(100 - left, width)),+ };+ });+}+export default function Timeline() {const [currentFrame, setCurrentFrame] = useState<DeviceFrameResponse | null>(null@@ -152,6 +318,19 @@ export default function Timeline() {height: 500,});const resizerRef = useRef<HTMLDivElement | null>(null);+ const [iconCache, setIconCache] = useState<AppIconCache>({});++ // 1. Memoize time range calculation+ const timelineRange = useMemo(() => getTimelineRange(frames), [frames]);++ // 2. Memoize time blocks calculation+ const timeBlocks = useMemo(() => calculateTimeBlocks(frames), [frames]);++ // 3. Memoize app ranges calculation with merged threshold+ const appRanges = useMemo(+ () => getUniqueAppRanges(timeBlocks, 300000),+ [timeBlocks]+ );useEffect(() => {setPosition({@@ -161,6 +340,17 @@ export default function Timeline() {}, []);const setupEventSource = () => {+ // Reset states when reloading+ setFrames([]);+ setCurrentFrame(null);+ setCurrentIndex(0);+ setIsLoading(true);+ setError(null);+ setSelectionRange(null);+ setIsAiPanelExpanded(false);+ setChatMessages([]);+ setAiInput("");+if (eventSourceRef.current) {eventSourceRef.current.close();}@@ -186,17 +376,32 @@ export default function Timeline() {const data = JSON.parse(event.data);if (data === "keep-alive-text") return;+ // Add error handling for server-side errors+ if (data.error) {+ console.error("server error:", data.error);+ setError(data.error);+ setIsLoading(false);+ return;+ }+if (data.timestamp && data.devices) {+ console.log("new frame:", data.timestamp, data.devices);setFrames((prev) => {const exists = prev.some((f) => f.timestamp === data.timestamp);if (exists) return prev;- // Add new frame and sort- const newFrames = [...prev, data].sort((a, b) => {- return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();- });+ const MAX_FRAMES = 1000;++ // Add new frame and maintain limit+ // const newFrames = [...prev, data].sort(+ // (a, b) =>+ // new Date(b.timestamp).getTime() -+ // new Date(a.timestamp).getTime()+ // );+ // .slice(0, MAX_FRAMES); // TODO: likely rem- return newFrames;+ // return newFrames;+ return [...prev, data];});// Only set initial frame if we don't have one@@ -205,19 +410,21 @@ export default function Timeline() {}} catch (error) {console.error("failed to parse frame data:", error);+ setError("failed to parse server response");+ setIsLoading(false);}};eventSource.onerror = (error) => {+ setIsLoading(false);+if (eventSource.readyState === EventSource.CLOSED) {console.log("stream ended (expected behavior)", error);- setIsLoading(false);return;}console.error("eventsource error:", error);- setError("connection lost. retrying...");-+ setError("connection lost - please refresh the page");eventSource.close();};@@ -228,47 +435,6 @@ export default function Timeline() {};};- const getLoadedTimeRangeStyles = () => {- if (!loadedTimeRange || frames.length === 0)- return { left: "0%", right: "100%" };-- // Find the earliest frame timestamp- const firstFrame = [...frames].sort(- (a, b) =>- new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()- )[0];- const earliestTime = new Date(firstFrame.timestamp);-- // Create local date objects for today- const startOfDay = new Date();- startOfDay.setHours(0, 0, 0, 0);-- const endOfDay = new Date();- endOfDay.setHours(23, 59, 59, 999);-- // Convert UTC loadedTimeRange to local time- const localStart = new Date(earliestTime);- const localEnd = new Date(loadedTimeRange.end);-- const totalMs = endOfDay.getTime() - startOfDay.getTime();- const startPercent =- ((localStart.getTime() - startOfDay.getTime()) / totalMs) * 100;- const endPercent =- ((localEnd.getTime() - startOfDay.getTime()) / totalMs) * 100;-- // Temporarily return empty values to disable grey areas- return {- right: "0%",- left: "0%",- };-- // Original code commented out:- // return {- // right: `${Math.max(0, Math.min(100, startPercent))}%`, // Grey before data starts- // left: `${Math.max(0, Math.min(100, 100 - endPercent))}%`, // Grey after data ends- // };- };-useEffect(() => {setupEventSource();@@ -307,154 +473,111 @@ export default function Timeline() {return () => window.removeEventListener("keydown", handleKeyDown);}, [selectionRange, isAiPanelExpanded, aiInput]);- const handleScroll = (e: React.WheelEvent<HTMLDivElement>) => {- const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);- if (isWithinAiPanel) {- return;- }-- e.preventDefault();- e.stopPropagation();-- const scrollSensitivity = 1;- const delta = -Math.sign(e.deltaY) / scrollSensitivity;-- const newIndex = Math.min(- Math.max(- 0,- currentIndex + (delta > 0 ? Math.ceil(delta) : Math.floor(delta))- ),- frames.length - 1- );-- if (newIndex !== currentIndex) {- setCurrentIndex(newIndex);- setCurrentFrame(frames[newIndex].devices[0]);- }- };-- const getCurrentTimePercentage = () => {- if (!currentFrame) return 0;-- const frameTime = new Date(- currentFrame.metadata.timestamp || frames[currentIndex].timestamp- );- const startOfDay = new Date(frameTime);- startOfDay.setHours(0, 0, 0, 0);- const endOfDay = new Date(frameTime);- endOfDay.setHours(23, 59, 59, 999);-- const totalDayMilliseconds = endOfDay.getTime() - startOfDay.getTime();- const currentMilliseconds = frameTime.getTime() - startOfDay.getTime();-- return (currentMilliseconds / totalDayMilliseconds) * 100;- };-const handleTimelineMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {+ if (!e.currentTarget) return;const rect = e.currentTarget.getBoundingClientRect();const clickX = e.clientX - rect.left;const percentage = (clickX / rect.width) * 100;- // Clamp percentage between 0 and 100- const clampedPercentage = Math.max(0, Math.min(100, percentage));-setIsDragging(true);- setDragStart(clampedPercentage);+ setDragStart(percentage);+ setIsAiPanelExpanded(false);+ // Set initial selection rangeconst totalMinutesInDay = 24 * 60;- const minutesFromMidnight = (clampedPercentage / 100) * totalMinutesInDay;- const hours = Math.floor(minutesFromMidnight / 60);- const minutes = Math.floor(minutesFromMidnight % 60);-- const localDate = new Date();- localDate.setHours(hours, minutes, 0, 0);-- const utcDate = new Date(- Date.UTC(- localDate.getUTCFullYear(),- localDate.getUTCMonth(),- localDate.getUTCDate(),- localDate.getUTCHours(),- localDate.getUTCMinutes(),- 0,- 0- )- );+ const minutes = (percentage / 100) * totalMinutesInDay;+ const date = new Date();+ date.setHours(Math.floor(minutes / 60), Math.floor(minutes % 60), 0, 0);setSelectionRange({- start: utcDate,- end: utcDate,+ start: date,+ end: date,});};- const handleTimelineMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {- if (!isDragging || dragStart === null) return;-- // Prevent text selection during drag- e.preventDefault();-- const rect = e.currentTarget.getBoundingClientRect();- const moveX = e.clientX - rect.left;- const percentage = (moveX / rect.width) * 100;-- // Clamp percentage between 0 and 100- const clampedPercentage = Math.max(0, Math.min(100, percentage));-- const totalMinutesInDay = 24 * 60;- const startMinutes =- (Math.min(dragStart, clampedPercentage) / 100) * totalMinutesInDay;- const endMinutes =- (Math.max(dragStart, clampedPercentage) / 100) * totalMinutesInDay;-- const startLocal = new Date();- startLocal.setHours(- Math.floor(startMinutes / 60),- Math.floor(startMinutes % 60),- 0,- 0- );-- const endLocal = new Date();- endLocal.setHours(- Math.floor(endMinutes / 60),- Math.floor(endMinutes % 60),- 0,- 0- );-- const utcStartDate = new Date(- Date.UTC(- startLocal.getUTCFullYear(),- startLocal.getUTCMonth(),- startLocal.getUTCDate(),- startLocal.getUTCHours(),- startLocal.getUTCMinutes(),- 0,- 0- )- );+ const debouncedMouseMove = useMemo(+ () =>+ throttle(+ (e: React.MouseEvent<HTMLDivElement>) => {+ if (!isDragging || dragStart === null || !e.currentTarget) return;++ const rect = e.currentTarget.getBoundingClientRect();+ const moveX = e.clientX - rect.left;+ const percentage = (moveX / rect.width) * 100;++ const totalMinutesInDay = 24 * 60;+ const startMinutes =+ (Math.min(dragStart, percentage) / 100) * totalMinutesInDay;+ const endMinutes =+ (Math.max(dragStart, percentage) / 100) * totalMinutesInDay;++ const startLocal = new Date();+ startLocal.setHours(+ Math.floor(startMinutes / 60),+ Math.floor(startMinutes % 60),+ 0,+ 0+ );++ const endLocal = new Date();+ endLocal.setHours(+ Math.floor(endMinutes / 60),+ Math.floor(endMinutes % 60),+ 0,+ 0+ );++ setSelectionRange({+ start: startLocal,+ end: endLocal,+ });+ },+ 16 // ~60fps+ ),+ [isDragging, dragStart]+ );- const utcEndDate = new Date(- Date.UTC(- endLocal.getUTCFullYear(),- endLocal.getUTCMonth(),- endLocal.getUTCDate(),- endLocal.getUTCHours(),- endLocal.getUTCMinutes(),- 0,- 0- )- );+ const debouncedScroll = useMemo(+ () =>+ throttle((e: React.WheelEvent<HTMLDivElement>) => {+ const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);+ if (isWithinAiPanel) return;- setSelectionRange({- start: utcStartDate,- end: utcEndDate,- });- };+ e.preventDefault();+ e.stopPropagation();++ const scrollSensitivity = 1;+ const delta = -Math.sign(e.deltaY) / scrollSensitivity;++ const newIndex = Math.min(+ Math.max(+ 0,+ currentIndex + (delta > 0 ? Math.ceil(delta) : Math.floor(delta))+ ),+ frames.length - 1+ );++ if (newIndex !== currentIndex) {+ setCurrentIndex(newIndex);+ setCurrentFrame(frames[newIndex].devices[0]);+ }+ }, 16),+ [currentIndex, frames]+ );const handleTimelineMouseUp = () => {- setIsDragging(false);- setDragStart(null);+ if (isDragging) {+ setIsDragging(false);+ setDragStart(null);++ // Only show AI panel if we have a meaningful selection+ // if (+ // selectionRange &&+ // selectionRange.start.getTime() !== selectionRange.end.getTime()+ // ) {+ // setIsAiPanelExpanded(true);+ // }+ }};const handleAskAI = () => {@@ -602,13 +725,12 @@ export default function Timeline() {};useEffect(() => {- const preventScroll = (e: WheelEvent) => {- const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);- if (!isWithinAiPanel) {- e.preventDefault();- }+ const preventScroll = (e: Event) => {+ e.preventDefault();+ return false;};+ // Add more comprehensive scroll preventiondocument.addEventListener("wheel", preventScroll, { passive: false });return () => document.removeEventListener("wheel", preventScroll);}, []);@@ -666,11 +788,6 @@ export default function Timeline() {const handleRefresh = () => {posthog.capture("timeline_refresh");-- setFrames([]);- setCurrentFrame(null);- setCurrentIndex(0);- setIsLoading(true);setupEventSource();};@@ -704,19 +821,70 @@ export default function Timeline() {document.addEventListener("mouseup", handleMouseUp);};+ const loadAppIcon = async (appName: string, appPath?: string) => {+ if (iconCache[appName]) return;++ const icon = await invoke<{ base64: string; path: string } | null>(+ "get_app_icon",+ {+ appName,+ appPath,+ }+ );++ if (icon) {+ setIconCache((prev) => ({+ ...prev,+ [appName]: icon.base64,+ }));+ }+ };++ useEffect(() => {+ const p = platform();+ if (p !== "macos") return;+ frames.forEach((frame) => {+ frame.devices.forEach((device) => {+ loadAppIcon(device.metadata.app_name);+ });+ });+ }, [frames]);++ useEffect(() => {+ const cleanup = () => {+ if (eventSourceRef.current) {+ eventSourceRef.current.close();+ }+ if (retryTimeoutRef.current) {+ clearTimeout(retryTimeoutRef.current);+ }+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ }+ };++ window.addEventListener("beforeunload", cleanup);+ return () => {+ cleanup();+ window.removeEventListener("beforeunload", cleanup);+ };+ }, []);++ useEffect(() => {+ return () => {+ debouncedMouseMove.cancel();+ debouncedScroll.cancel();+ };+ }, [debouncedMouseMove, debouncedScroll]);+return (<divclassName="fixed inset-0 flex flex-col bg-background text-foreground overflow-hidden relative"- onWheel={(e) => {- const isWithinAiPanel = aiPanelRef.current?.contains(e.target as Node);- if (!isWithinAiPanel) {- handleScroll(e);- }- }}+ onWheel={debouncedScroll}style={{height: "100vh",overscrollBehavior: "none",- overflow: "hidden",+ overflow: "hidden",WebkitUserSelect: "none",userSelect: "none",MozUserSelect: "none",@@ -739,7 +907,7 @@ export default function Timeline() {/><div className="flex-1 relative min-h-0">- {isLoading && (+ {(isLoading || frames.length === 0) && (<div className="absolute inset-0 flex items-center justify-center"><div className="bg-background/90 p-5 border rounded-lg shadow-lg text-center"><p>loading frames...</p>@@ -747,7 +915,7 @@ export default function Timeline() {</div></div>)}- {error && (+ {error && !isLoading && (<div className="absolute inset-0 flex items-center justify-center"><div className="bg-destructive/10 p-5 border-destructive/20 border rounded-lg text-destructive"><AlertCircle className="h-4 w-4 mb-2 mx-auto" />@@ -756,47 +924,24 @@ export default function Timeline() {</div>)}{currentFrame && (- <>- <div className="w-4/5 mx-auto mt-4 mb-4 text-center select-none">- <div className="inline-block bg-card p-2 rounded-lg shadow-lg border">- <div className="flex items-center gap-4 text-sm">- <div>device: {currentFrame.device_id}</div>- <div>app: {currentFrame.metadata.app_name || "n/a"}</div>- <div>- window: {currentFrame.metadata.window_name || "n/a"}- </div>- <div className="border-l pl-4 font-mono">- {new Date(currentFrame.metadata.timestamp || frames[currentIndex].timestamp).toLocaleString()}- </div>- </div>- </div>- </div>- <img- src={`data:image/png;base64,${currentFrame.frame}`}- className="absolute inset-0 w-4/5 h-auto max-h-[75vh] object-contain mx-auto mt-12"- alt="Current frame"- />- </>+ <img+ src={`data:image/png;base64,${currentFrame.frame}`}+ className="absolute inset-0 w-full h-full object-contain mx-auto mt-6"+ alt="Current frame"+ loading="lazy"+ decoding="async"+ />)}</div><div className="w-4/5 mx-auto my-8 relative select-none"><div- className="h-[60px] bg-card border rounded-lg shadow-sm cursor-crosshair relative"+ className="h-[60px] bg-card border rounded-lg shadow-sm relative overflow-hidden"onMouseDown={handleTimelineMouseDown}- onMouseMove={handleTimelineMouseMove}+ onMouseMove={debouncedMouseMove}onMouseUp={handleTimelineMouseUp}onMouseLeave={handleTimelineMouseUp}>- <div- className="absolute inset-0 pointer-events-none"- style={{- ...getLoadedTimeRangeStyles(),- background:- "linear-gradient(to right, rgba(255,255,255,0.8), rgba(255,255,255,0.2))",- }}- />-<divclassName="absolute inset-0"style={{@@ -805,209 +950,196 @@ export default function Timeline() {backgroundSize: "10% 100%",}}/>+ <TimelineBlocks frames={frames} timeRange={timelineRange} />- <div- className="absolute top-0 h-full w-1 bg-foreground/50 shadow-sm opacity-80 z-10"- style={{- left: `${getCurrentTimePercentage()}%`,- }}+ <CurrentTimeIndicator+ currentFrame={currentFrame}+ frames={frames}+ currentIndex={currentIndex}+ timeRange={timelineRange}/>- {selectionRange && (- <div- className="absolute top-0 h-full bg-foreground/10"- style={{- left: `${- (new Date(selectionRange.start).getHours() * 3600 +- new Date(selectionRange.start).getMinutes() * 60) /- 864- }%`,- width: `${- ((selectionRange.end.getTime() -- selectionRange.start.getTime()) /- (24 * 3600 * 1000)) *- 100- }%`,- }}- />- )}+ {/* <TimelineIconsSection blocks={appRanges} /> */}++ <TimeLabels timeRange={timelineRange} /></div>+ </div>- {selectionRange && (+ <div className="h-12" />++ <div className="fixed left-12 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">+ <div className="flex flex-col items-center gap-1">+ <span>▲</span>+ <span>scroll</span>+ <span>▼</span>+ </div>+ </div>++ {selectionRange && (+ <div+ className="absolute top-0 h-full bg-foreground/10"+ style={{+ left: `${+ (new Date(selectionRange.start).getHours() * 3600 ++ new Date(selectionRange.start).getMinutes() * 60) /+ 864+ }%`,+ width: `${+ ((selectionRange.end.getTime() - selectionRange.start.getTime()) /+ (24 * 3600 * 1000)) *+ 100+ }%`,+ }}+ />+ )}++ {selectionRange && (+ <div+ ref={aiPanelRef}+ style={{+ position: "fixed",+ left: position.x,+ top: position.y,+ width: chatWindowSize.width,+ height: isAiPanelExpanded ? chatWindowSize.height : 120,+ cursor: isDraggingPanel ? "grabbing" : "default",+ }}+ className={`bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]`}+ ><div- ref={aiPanelRef}- style={{- position: "fixed",- left: position.x,- top: position.y,- width: chatWindowSize.width,- height: isAiPanelExpanded ? chatWindowSize.height : 120,- cursor: isDraggingPanel ? "grabbing" : "default",- }}- className={`bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]`}+ className="select-none cursor-grab active:cursor-grabbing"+ onMouseDown={handlePanelMouseDown}+ onMouseMove={handlePanelMouseMove}+ onMouseUp={handlePanelMouseUp}+ onMouseLeave={handlePanelMouseUp}>- <div- className="select-none cursor-grab active:cursor-grabbing"- onMouseDown={handlePanelMouseDown}- onMouseMove={handlePanelMouseMove}- onMouseUp={handlePanelMouseUp}- onMouseLeave={handlePanelMouseUp}- >- <div className="p-4 border-b border-muted-foreground flex justify-between items-center group">- <div className="flex items-center gap-2 flex-1">- <GripHorizontal className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />- <div className="text-muted-foreground text-xs">- {new Date(selectionRange.start.getTime()).toLocaleTimeString()} -{" "}- {new Date(selectionRange.end.getTime()).toLocaleTimeString()}- </div>+ <div className="p-4 border-b border-muted-foreground flex justify-between items-center group">+ <div className="flex items-center gap-2 flex-1">+ <GripHorizontal className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />+ <div className="text-muted-foreground text-xs">+ {new Date(+ selectionRange.start.getTime()+ ).toLocaleTimeString()}{" "}+ -{" "}+ {new Date(selectionRange.end.getTime()).toLocaleTimeString()}</div>- <button- onClick={() => {- setSelectionRange(null);- setIsAiPanelExpanded(false);- setChatMessages([]);- setAiInput("");- }}- className="text-muted-foreground hover:text-foreground transition-colors ml-2"- >- <X className="h-4 w-4" />- </button></div>-- {!isAiPanelExpanded && (- <div className="p-4">- <button- className="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"- onClick={(e) => {- e.stopPropagation();- setIsAiPanelExpanded(true);- setTimeout(() => {- inputRef.current?.focus();- }, 100);- }}- >- <span>ask ai</span>- <span className="text-muted-foreground text-[10px]">- {osType === "macos" ? "⌘K" : "Ctrl+K"}- </span>- </button>- </div>- )}+ <button+ onClick={() => {+ setSelectionRange(null);+ setIsAiPanelExpanded(false);+ setChatMessages([]);+ setAiInput("");+ }}+ className="text-muted-foreground hover:text-foreground transition-colors ml-2"+ >+ <X className="h-4 w-4" />+ </button></div>- {isAiPanelExpanded && (- <div className="flex flex-col h-[calc(100%-52px)]">- <div- className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0 hover:cursor-auto text-foreground font-mono text-sm leading-relaxed"- style={{- WebkitUserSelect: "text",- userSelect: "text",- MozUserSelect: "text",- msUserSelect: "text",- overscrollBehavior: "contain",+ {!isAiPanelExpanded && (+ <div className="p-4">+ <button+ className="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"+ onClick={(e) => {+ e.stopPropagation();+ setIsAiPanelExpanded(true);+ setTimeout(() => {+ inputRef.current?.focus();+ }, 100);}}>- {chatMessages.map((msg, index) => (- <ChatMessage key={index} message={msg} />- ))}- {isAiLoading && (- <div className="flex justify-center">- <Loader2 className="h-6 w-6 animate-spin text-foreground" />- </div>- )}- </div>-- <form- onSubmit={handleAiSubmit}- className="p-3 border-t border-muted-foreground"- >- <div className="flex flex-col gap-2">- <select- value={selectedAgent.id}- onChange={(e) => handleAgentChange(e.target.value)}- className="w-full bg-background border border-muted-foreground text-foreground rounded px-2 py-1 text-xs"- >- {AGENTS.map((agent) => (- <option- key={agent.id}- value={agent.id}- className="bg-background text-foreground"- >- {agent.name} - {agent.description}- </option>- ))}- </select>- <div className="flex gap-2">- <Input- ref={inputRef}- type="text"- value={aiInput}- onChange={(e) => setAiInput(e.target.value)}- placeholder="ask about this time range..."- className="flex-1 bg-background border border-muted-foreground text-foreground placeholder-muted-foreground"- disabled={isAiLoading}- />- <Button- type="submit"- variant="outline"- className="hover:bg-accent transition-colors"- disabled={isAiLoading}- >- {isStreaming ? (- <Square className="h-4 w-4" />- ) : (- <Send className="h-4 w-4" />- )}- </Button>- </div>- </div>- </form>+ <span>ask ai</span>+ <span className="text-muted-foreground text-[10px]">+ {osType === "macos" ? "⌘K" : "Ctrl+K"}+ </span>+ </button></div>)}-- <div- ref={resizerRef}- onMouseDown={handleMouseDown}- className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"- style={{- borderTopLeftRadius: "4px",- borderBottomRightRadius: "4px",- cursor: "se-resize",- }}- /></div>- )}- <div className="relative mt-1 px-2 text-[10px] text-muted-foreground select-none">- {Array(7)- .fill(0)- .map((_, i) => {- const hour = (i * 4) % 24;- const date = new Date();- date.setHours(hour, 0, 0, 0);- return (- <div- key={i}- className="absolute transform -translate-x-1/2"- style={{ left: `${(i * 100) / 6}%` }}- >- {date.toLocaleTimeString([], {- hour: "2-digit",- minute: "2-digit",- })}+ {isAiPanelExpanded && (+ <div className="flex flex-col h-[calc(100%-52px)]">+ <div+ className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0 hover:cursor-auto text-foreground font-mono text-sm leading-relaxed"+ style={{+ WebkitUserSelect: "text",+ userSelect: "text",+ MozUserSelect: "text",+ msUserSelect: "text",+ overscrollBehavior: "contain",+ }}+ >+ {chatMessages.map((msg, index) => (+ <ChatMessage key={index} message={msg} />+ ))}+ {isAiLoading && (+ <div className="flex justify-center">+ <Loader2 className="h-6 w-6 animate-spin text-foreground" />+ </div>+ )}+ </div>++ <form+ onSubmit={handleAiSubmit}+ className="p-3 border-t border-muted-foreground"+ >+ <div className="flex flex-col gap-2">+ <select+ value={selectedAgent.id}+ onChange={(e) => handleAgentChange(e.target.value)}+ className="w-full bg-background border border-muted-foreground text-foreground rounded px-2 py-1 text-xs"+ >+ {AGENTS.map((agent) => (+ <option+ key={agent.id}+ value={agent.id}+ className="bg-background text-foreground"+ >+ {agent.name} - {agent.description}+ </option>+ ))}+ </select>+ <div className="flex gap-2">+ <Input+ ref={inputRef}+ type="text"+ value={aiInput}+ onChange={(e) => setAiInput(e.target.value)}+ placeholder="ask about this time range..."+ className="flex-1 bg-background border border-muted-foreground text-foreground placeholder-muted-foreground"+ disabled={isAiLoading}+ />+ <Button+ type="submit"+ variant="outline"+ className="hover:bg-accent transition-colors"+ disabled={isAiLoading}+ >+ {isStreaming ? (+ <Square className="h-4 w-4" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ </Button>+ </div></div>- );- })}- </div>- </div>+ </form>+ </div>+ )}- <div className="fixed left-12 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">- <div className="flex flex-col items-center gap-1">- <span>▲</span>- <span>scroll</span>- <span>▼</span>+ <div+ ref={resizerRef}+ onMouseDown={handleMouseDown}+ className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"+ style={{+ borderTopLeftRadius: "4px",+ borderBottomRightRadius: "4px",+ cursor: "se-resize",+ }}+ /></div>- </div>+ )}</div>);}diff --git a/screenpipe-app-tauri/bun.lockb b/screenpipe-app-tauri/bun.lockbindex 55778a4a9..dee73ad02 100755Binary files a/screenpipe-app-tauri/bun.lockb and b/screenpipe-app-tauri/bun.lockb differdiff --git a/screenpipe-app-tauri/components/timeline/chat-panel.tsx b/screenpipe-app-tauri/components/timeline/chat-panel.tsxnew file mode 100644index 000000000..5143aab83--- /dev/null+++ b/screenpipe-app-tauri/components/timeline/chat-panel.tsx@@ -0,0 +1,329 @@+import { useRef, useState } from "react";+import { generateId, Message } from "ai";+import { OpenAI } from "openai";+import { ChatCompletionMessageParam } from "openai/resources/index.mjs";+import { Loader2, Send, Square, X, GripHorizontal } from "lucide-react";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { ChatMessage } from "@/components/chat-message-v2";+import { useToast } from "@/components/ui/use-toast";++interface Agent {+ id: string;+ name: string;+ description: string;+ dataSelector: (frames: any[]) => any;+}++interface ChatPanelProps {+ position: { x: number; y: number };+ size: { width: number; height: number };+ onPositionChange: (pos: { x: number; y: number }) => void;+ onSizeChange: (size: { width: number; height: number }) => void;+ onClose: () => void;+ isExpanded: boolean;+ onExpand: () => void;+ selectionRange: { start: Date; end: Date };+ frames: any[];+ settings: any;+ agents: Agent[];+ osType: string;+}++export function ChatPanel({+ position,+ size,+ onPositionChange,+ onSizeChange,+ onClose,+ isExpanded,+ onExpand,+ selectionRange,+ frames,+ settings,+ agents,+ osType,+}: ChatPanelProps) {+ const [messages, setMessages] = useState<Array<Message>>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [isStreaming, setIsStreaming] = useState(false);+ const [input, setInput] = useState("");+ const [selectedAgent, setSelectedAgent] = useState<Agent>(agents[0]);+ const inputRef = useRef<HTMLInputElement>(null);+ const abortControllerRef = useRef<AbortController | null>(null);+ const { toast } = useToast();++ // Dragging logic+ const [isDragging, setIsDragging] = useState(false);+ const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });++ const handlePanelMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {+ setIsDragging(true);+ setDragOffset({+ x: e.clientX - position.x,+ y: e.clientY - position.y,+ });+ };++ const handlePanelMouseMove = (e: React.MouseEvent) => {+ if (isDragging) {+ onPositionChange({+ x: e.clientX - dragOffset.x,+ y: e.clientY - dragOffset.y,+ });+ }+ };++ const handlePanelMouseUp = () => {+ setIsDragging(false);+ };++ // Resizing logic+ const handleResizeMouseDown = (e: React.MouseEvent) => {+ e.preventDefault();+ const startX = e.clientX;+ const startY = e.clientY;+ const startWidth = size.width;+ const startHeight = size.height;++ const handleMouseMove = (moveEvent: MouseEvent) => {+ const newWidth = Math.max(200, startWidth + moveEvent.clientX - startX);+ const newHeight = Math.max(200, startHeight + moveEvent.clientY - startY);+ onSizeChange({ width: newWidth, height: newHeight });+ };++ const handleMouseUp = () => {+ document.removeEventListener("mousemove", handleMouseMove);+ document.removeEventListener("mouseup", handleMouseUp);+ };++ document.addEventListener("mousemove", handleMouseMove);+ document.addEventListener("mouseup", handleMouseUp);+ };++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!input.trim()) return;++ const relevantFrames = frames.filter((frame) => {+ const frameTime = new Date(frame.timestamp);+ return (+ frameTime >= selectionRange.start && frameTime <= selectionRange.end+ );+ });++ const contextData = selectedAgent.dataSelector(relevantFrames);++ const userMessage = {+ id: crypto.randomUUID(),+ role: "user" as const,+ content: input,+ };+ setMessages((prev) => [...prev, userMessage]);+ setInput("");+ setIsLoading(true);++ try {+ const openai = new OpenAI({+ apiKey: settings.openaiApiKey,+ baseURL: settings.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ const m: Message[] = [+ {+ id: generateId(),+ role: "system" as const,+ content: `You are a helpful assistant specialized as a "${+ selectedAgent.name+ }" analyzing screen & mic recordings.+ Rules:+ - Current time (JavaScript Date.prototype.toString): ${new Date().toString()}+ - User timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}+ - User timezone offset: ${new Date().getTimezoneOffset()}+ - All timestamps in the context data are in UTC+ - Convert timestamps to local time for human-readable responses+ - Never output UTC time unless explicitly asked+ - Focus on ${selectedAgent.description}+ - Follow the user's instructions carefully & to the letter: ${+ settings.customPrompt+ }`,+ },+ ...messages,+ {+ id: generateId(),+ role: "user" as const,+ content: `Context data: ${JSON.stringify(contextData)}\n${input}`,+ },+ ];++ abortControllerRef.current = new AbortController();+ setIsStreaming(true);++ const stream = await openai.chat.completions.create(+ {+ model: settings.aiModel,+ messages: m as ChatCompletionMessageParam[],+ stream: true,+ },+ {+ signal: abortControllerRef.current.signal,+ }+ );++ let fullResponse = "";+ setMessages((prev) => [+ ...prev,+ { id: generateId(), role: "assistant", content: "" },+ ]);++ for await (const chunk of stream) {+ const content = chunk.choices[0]?.delta?.content || "";+ fullResponse += content;+ setMessages((prev) => [+ ...prev.slice(0, -1),+ { id: generateId(), role: "assistant", content: fullResponse },+ ]);+ }+ } catch (error: any) {+ console.error("error generating ai response:", error);+ toast({+ title: "error",+ description: error.message.toLowerCase().includes("maximum context")+ ? "failed to generate ai response. max context length exceeded."+ : "failed to generate ai response. please try again.",+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ setIsStreaming(false);+ }+ };++ return (+ <div+ style={{+ position: "fixed",+ left: position.x,+ top: position.y,+ width: size.width,+ height: isExpanded ? size.height : 120,+ cursor: isDragging ? "grabbing" : "default",+ }}+ className="bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"+ >+ <div+ className="select-none cursor-grab active:cursor-grabbing"+ onMouseDown={handlePanelMouseDown}+ onMouseMove={handlePanelMouseMove}+ onMouseUp={handlePanelMouseUp}+ onMouseLeave={handlePanelMouseUp}+ >+ <div className="p-4 border-b border-muted-foreground flex justify-between items-center group">+ <div className="flex items-center gap-2 flex-1">+ <GripHorizontal className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />+ <div className="text-muted-foreground text-xs">+ {selectionRange.start.toLocaleTimeString()} -{" "}+ {selectionRange.end.toLocaleTimeString()}+ </div>+ </div>+ <button+ onClick={onClose}+ className="text-muted-foreground hover:text-foreground transition-colors ml-2"+ >+ <X className="h-4 w-4" />+ </button>+ </div>++ {!isExpanded ? (+ <div className="p-4">+ <button+ className="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"+ onClick={onExpand}+ >+ <span>ask ai</span>+ <span className="text-muted-foreground text-[10px]">+ {osType === "macos" ? "⌘K" : "Ctrl+K"}+ </span>+ </button>+ </div>+ ) : (+ <div className="flex flex-col h-[calc(100%-52px)]">+ <div className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 hover:cursor-auto text-foreground font-mono text-sm leading-relaxed">+ {messages.map((msg, index) => (+ <ChatMessage key={index} message={msg} />+ ))}+ {isLoading && (+ <div className="flex justify-center">+ <Loader2 className="h-6 w-6 animate-spin text-foreground" />+ </div>+ )}+ </div>++ <div className="mt-auto border-t border-muted-foreground">+ <form onSubmit={handleSubmit} className="p-3">+ <div className="flex flex-col gap-2">+ <select+ value={selectedAgent.id}+ onChange={(e) => {+ const agent = agents.find((a) => a.id === e.target.value);+ if (agent) setSelectedAgent(agent);+ }}+ className="w-full bg-background text-foreground border border-muted-foreground rounded px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-foreground"+ >+ {agents.map((agent) => (+ <option+ key={agent.id}+ value={agent.id}+ className="bg-background text-foreground"+ style={{+ backgroundColor: "var(--background)",+ color: "var(--foreground)",+ }}+ >+ {agent.name} - {agent.description}+ </option>+ ))}+ </select>+ <div className="flex gap-2">+ <Input+ ref={inputRef}+ type="text"+ value={input}+ onChange={(e) => setInput(e.target.value)}+ placeholder="ask about this time range..."+ className="flex-1 bg-background border border-muted-foreground text-foreground placeholder-muted-foreground"+ disabled={isLoading}+ />+ <Button+ type="submit"+ variant="outline"+ className="hover:bg-accent transition-colors"+ disabled={isLoading}+ >+ {isStreaming ? (+ <Square className="h-4 w-4" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ </Button>+ </div>+ </div>+ </form>+ </div>+ </div>+ )}+ </div>++ <div+ onMouseDown={handleResizeMouseDown}+ className="absolute right-0 bottom-0 w-4 h-4 cursor-se-resize bg-transparent"+ style={{+ borderTopLeftRadius: "4px",+ borderBottomRightRadius: "4px",+ cursor: "se-resize",+ }}+ />+ </div>+ );+}diff --git a/screenpipe-app-tauri/components/timeline/current-time-indicator.tsx b/screenpipe-app-tauri/components/timeline/current-time-indicator.tsxnew file mode 100644index 000000000..c446d5679--- /dev/null+++ b/screenpipe-app-tauri/components/timeline/current-time-indicator.tsx@@ -0,0 +1,61 @@+import { cn } from "@/lib/utils";++interface CurrentTimeIndicatorProps {+ currentFrame: {+ metadata: {+ timestamp: string;+ };+ } | null;+ frames: any[]; // Replace with your StreamTimeSeriesResponse type+ currentIndex: number;+ timeRange: {+ start: Date;+ end: Date;+ };+ className?: string;+}++export function CurrentTimeIndicator({+ currentFrame,+ frames,+ currentIndex,+ timeRange,+ className,+}: CurrentTimeIndicatorProps) {+ const getCurrentTimePercentage = () => {+ if (!currentFrame) return 0;++ const frameTime = new Date(+ currentFrame.metadata.timestamp || frames[currentIndex].timestamp+ );++ const totalMs = timeRange.end.getTime() - timeRange.start.getTime();+ const currentMs = frameTime.getTime() - timeRange.start.getTime();++ return (currentMs / totalMs) * 100;+ };++ if (!currentFrame) return null;++ return (+ <div+ className={cn(+ "absolute top-0 bottom-0 flex flex-col items-center pointer-events-none z-10",+ className+ )}+ style={{+ left: `${Math.max(0, Math.min(100, getCurrentTimePercentage()))}%`,+ }}+ >+ <div className="w-0.5 h-full bg-foreground/50" />+ <div className="absolute bottom-[-20px] text-xs text-foreground bg-background px-1 rounded-sm border whitespace-nowrap">+ {new Date(+ currentFrame.metadata.timestamp || frames[currentIndex].timestamp+ ).toLocaleTimeString([], {+ hour: '2-digit',+ minute: '2-digit'+ })}+ </div>+ </div>+ );+}diff --git a/screenpipe-app-tauri/components/timeline/time-labels.tsx b/screenpipe-app-tauri/components/timeline/time-labels.tsxnew file mode 100644index 000000000..f2c12bcc1--- /dev/null+++ b/screenpipe-app-tauri/components/timeline/time-labels.tsx@@ -0,0 +1,48 @@+import { cn } from "@/lib/utils";++interface TimeLabelsProps {+ timeRange: {+ start: Date;+ end: Date;+ };+ className?: string;+}++export function TimeLabels({ timeRange, className }: TimeLabelsProps) {+ const totalHours =+ (timeRange.end.getTime() - timeRange.start.getTime()) / (1000 * 60 * 60);+ const labelCount = Math.min(14, Math.ceil(totalHours / 1)); // One label every ~2 hours, max 7 labels++ return (+ <div+ className={cn(+ "flex items-center justify-start px-6 text-[10px] text-muted-foreground absolute bottom-2 w-full",+ className+ )}+ >+ {Array(labelCount)+ .fill(0)+ .map((_, i) => {+ const msPerLabel =+ (timeRange.end.getTime() - timeRange.start.getTime()) /+ (labelCount - 1);+ const timestamp = new Date(+ timeRange.start.getTime() + i * msPerLabel+ );++ return (+ <div+ key={i}+ className="absolute transform -translate-x-1/2"+ style={{ left: `${(i * 100) / (labelCount - 1)}%` }}+ >+ {timestamp.toLocaleTimeString([], {+ hour: "2-digit",+ minute: "2-digit",+ })}+ </div>+ );+ })}+ </div>+ );+}diff --git a/screenpipe-app-tauri/components/timeline/timeline-block.tsx b/screenpipe-app-tauri/components/timeline/timeline-block.tsxnew file mode 100644index 000000000..8516030ad--- /dev/null+++ b/screenpipe-app-tauri/components/timeline/timeline-block.tsx@@ -0,0 +1,103 @@+import { useMemo } from "react";++interface TimeBlock {+ appName: string;+ startTime: Date;+ endTime: Date;+ color: string;+}++interface TimelineBlocksProps {+ frames: any[]; // Replace with your StreamTimeSeriesResponse type+ timeRange: { start: Date; end: Date };+}++export function TimelineBlocks({ frames, timeRange }: TimelineBlocksProps) {+ // Move helper functions inside component+ const getAppColor = (appName: string): string => {+ let hash = 0;+ for (let i = 0; i < appName.length; i++) {+ hash = appName.charCodeAt(i) + ((hash << 5) - hash);+ }+ const hue = Math.abs(hash) % 360;+ return `hsl(${hue}, 70%, 50%)`;+ };++ // Memoize the heavy calculation+ const blocks = useMemo(() => {+ if (frames.length === 0) return [];++ const blocks: TimeBlock[] = [];+ let currentBlock: TimeBlock | null = null;++ const sortedFrames = [...frames].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()+ );++ sortedFrames.forEach((frame) => {+ const timestamp = new Date(frame.timestamp);+ const appName = frame.devices[0].metadata.app_name;++ if (timestamp < timeRange.start || timestamp > timeRange.end) {+ return;+ }++ if (!currentBlock) {+ currentBlock = {+ appName,+ startTime: timestamp,+ endTime: timestamp,+ color: getAppColor(appName),+ };+ } else if (currentBlock.appName !== appName) {+ currentBlock.endTime = timestamp;+ blocks.push(currentBlock);+ currentBlock = {+ appName,+ startTime: timestamp,+ endTime: timestamp,+ color: getAppColor(appName),+ };+ } else {+ currentBlock.endTime = timestamp;+ }+ });++ if (currentBlock) {+ blocks.push(currentBlock);+ }++ return blocks;+ }, [frames, timeRange]);++ return (+ <>+ {blocks.map((block, index) => {+ const totalMs = timeRange.end.getTime() - timeRange.start.getTime();+ const blockStart =+ ((block.startTime.getTime() - timeRange.start.getTime()) / totalMs) *+ 100;+ const blockWidth =+ ((block.endTime.getTime() - block.startTime.getTime()) / totalMs) *+ 100;++ return (+ <div+ key={index}+ className="absolute top-0 h-full"+ style={{+ left: `${Math.max(0, Math.min(100, blockStart))}%`,+ width: `${Math.max(0, Math.min(100 - blockStart, blockWidth))}%`,+ backgroundColor: block.color,+ transition: "all 0.1s ease-in-out",+ }}+ title={`${+ block.appName+ }\n${block.startTime.toLocaleTimeString()} - ${block.endTime.toLocaleTimeString()}`}+ />+ );+ })}+ </>+ );+}diff --git a/screenpipe-app-tauri/components/timeline/timeline-dock.tsx b/screenpipe-app-tauri/components/timeline/timeline-dock.tsxnew file mode 100644index 000000000..489705a4e--- /dev/null+++ b/screenpipe-app-tauri/components/timeline/timeline-dock.tsx@@ -0,0 +1,233 @@+import React, { useEffect, useState, useCallback, useMemo } from "react";+import { motion, AnimatePresence } from "framer-motion";+import { cn } from "@/lib/utils";+import { platform } from "@tauri-apps/plugin-os";+import { invoke } from "@tauri-apps/api/core";+import { TimeBlock, TimelineBlock } from "@/app/timeline/page";+import { debounce } from "lodash";++interface TimelineDockProps {+ children: React.ReactNode;+ magnification?: number;+ distance?: number;+ className?: string;+}++interface TimelineDockIconProps {+ children: React.ReactNode;+ className?: string;+ timestamp?: Date;+ appName?: string;+ mouseX?: number | null;+ index?: number;+ magnification?: number;+ distance?: number;+ style?: React.CSSProperties;+}++export function TimelineDock({+ children,+ magnification = 2,+ distance = 100,+ className,+}: TimelineDockProps) {+ const [mouseX, setMouseX] = React.useState<null | number>(null);++ // Debounce mouse move handler+ const handleMouseMove = useMemo(+ () =>+ debounce((e: React.MouseEvent) => {+ const bounds = e.currentTarget.getBoundingClientRect();+ setMouseX(e.clientX - bounds.left);+ }, 16), // ~60fps+ []+ );++ return (+ <motion.div+ onMouseMove={handleMouseMove}+ onMouseLeave={() => setMouseX(null)}+ className={cn(+ "flex items-center justify-start h-8 relative px-2 w-full",+ className+ )}+ >+ {useMemo(() =>+ React.Children.map(children, (child, index) => {+ if (!React.isValidElement(child)) return null;+ return React.cloneElement(+ child as React.ReactElement<TimelineDockIconProps>,+ {+ mouseX,+ index,+ magnification,+ distance,+ }+ );+ }),+ [children, mouseX, magnification, distance]+ )}+ </motion.div>+ );+}++// Memoize the TimelineDockIcon component+export const TimelineDockIcon = React.memo(function TimelineDockIcon({+ children,+ className,+ timestamp,+ appName,+ mouseX,+ index,+ magnification = 2,+ distance = 50,+ style,+}: TimelineDockIconProps) {+ const ref = React.useRef<HTMLDivElement>(null);++ // Calculate scale based on percentage position rather than pixel position+ let scale = 1;+ let isClosest = false;+ let spacing = 0;++ if (mouseX != null && style?.left) {+ // Convert left percentage to actual position+ const iconPosition = parseFloat(style.left as string);+ const mousePosition =+ (mouseX / (ref.current?.parentElement?.offsetWidth || 1)) * 100;++ // Calculate distance as percentage difference+ const distanceFromMouse = Math.abs(mousePosition - iconPosition);++ if (distanceFromMouse < 5) {+ // Reduced distance threshold to 5%+ scale = Math.max(+ 1,+ magnification - (distanceFromMouse / 5) * magnification+ );++ spacing = scale > 1 ? 2 * (1 - distanceFromMouse / 5) : 0;+ isClosest = distanceFromMouse < 2; // Show tooltip when within 2%+ }+ }++ const yOffset = scale > 1 ? (scale - 1) * 16 : 0;+ const xOffset = mouseX != null ? spacing : 0;++ return (+ <motion.div+ ref={ref}+ style={{+ scale,+ y: -yOffset,+ x: xOffset,+ zIndex: scale > 1 ? 1 : 0,+ position: "absolute",+ transform: `translate(-50%, -50%)`,+ ...style,+ }}+ transition={{+ type: "spring",+ stiffness: 400,+ damping: 25,+ }}+ className={cn(+ "flex items-center justify-center w-4 h-4 origin-center",+ className+ )}+ >+ <div className="relative flex items-center justify-center">+ {children}+ <AnimatePresence>+ {isClosest && (+ <motion.div+ initial={{ opacity: 0, y: -10 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -10 }}+ className="absolute top-full mt-2 left-1/2 -translate-x-1/2 flex flex-col items-center bg-background/80 backdrop-blur-sm px-2 py-1 rounded-md border shadow-sm text-xs whitespace-nowrap"+ >+ <span>{appName}</span>+ <span>{timestamp?.toLocaleTimeString()}</span>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ </motion.div>+ );+});++// Optimize TimelineIconsSection+export function TimelineIconsSection({ blocks }: { blocks: TimelineBlock[] }) {+ const [iconCache, setIconCache] = useState<{ [key: string]: string }>({});++ // Memoize significant blocks calculation+ const significantBlocks = useMemo(() =>+ blocks.filter((block) => {+ const minutesInDay = 24 * 60;+ const blockMinutes = (block.width / 100) * minutesInDay;+ return blockMinutes > 10;+ }),+ [blocks]+ );++ // Memoize unique apps calculation+ const uniqueApps = useMemo(() =>+ [...new Set(significantBlocks.map((block) => block.appName))],+ [significantBlocks]+ );++ const loadAppIcon = useCallback(async (appName: string, appPath?: string) => {+ if (iconCache[appName]) return;++ const icon = await invoke<{ base64: string; path: string } | null>(+ "get_app_icon",+ { appName, appPath }+ );++ if (icon) {+ setIconCache(prev => ({+ ...prev,+ [appName]: icon.base64,+ }));+ }+ }, [iconCache]);++ useEffect(() => {+ const loadIcons = async () => {+ const p = platform();+ if (p !== "macos") return;++ // Load icons for unique app names only+ uniqueApps.forEach((appName) => {+ loadAppIcon(appName);+ });+ };++ loadIcons();+ }, [uniqueApps, loadAppIcon]);++ return (+ <div className="absolute -bottom-20 inset-x-0 pointer-events-none">+ {significantBlocks.map((block, i) => (+ <div+ key={`${block.appName}-${i}`}+ className="absolute top-0 h-full"+ style={{+ left: `${block.left}%`,+ width: `${block.width}%`,+ }}+ >+ {iconCache[block.appName] && (+ <img+ src={`data:image/png;base64,${iconCache[block.appName]}`}+ className="w-6 h-6 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 opacity-50"+ alt={block.appName}+ loading="lazy"+ decoding="async"+ />+ )}+ </div>+ ))}+ </div>+ );+}diff --git a/screenpipe-app-tauri/components/ui/dock.tsx b/screenpipe-app-tauri/components/ui/dock.tsxnew file mode 100644index 000000000..2655d9979--- /dev/null+++ b/screenpipe-app-tauri/components/ui/dock.tsx@@ -0,0 +1,128 @@+"use client";++import React, { PropsWithChildren, useRef } from "react";+import { cva, type VariantProps } from "class-variance-authority";+import { motion, useMotionValue, useSpring, useTransform } from "framer-motion";++import { cn } from "@/lib/utils";++export interface DockProps extends VariantProps<typeof dockVariants> {+ className?: string;+ magnification?: number;+ distance?: number;+ direction?: "top" | "middle" | "bottom";+ children: React.ReactNode;+}++const DEFAULT_MAGNIFICATION = 60;+const DEFAULT_DISTANCE = 140;++const dockVariants = cva(+ "supports-backdrop-blur:bg-white/10 supports-backdrop-blur:dark:bg-black/10 mx-auto mt-8 flex h-[58px] w-max gap-2 rounded-2xl border p-2 backdrop-blur-md",+);++const Dock = React.forwardRef<HTMLDivElement, DockProps>(+ (+ {+ className,+ children,+ magnification = DEFAULT_MAGNIFICATION,+ distance = DEFAULT_DISTANCE,+ direction = "bottom",+ ...props+ },+ ref,+ ) => {+ const mouseX = useMotionValue(Infinity);++ const renderChildren = () => {+ return React.Children.map(children, (child) => {+ if (React.isValidElement(child) && child.type === DockIcon) {+ return React.cloneElement(child, {+ ...child.props,+ mouseX: mouseX,+ magnification: magnification,+ distance: distance,+ });+ }+ return child;+ });+ };++ return (+ <motion.div+ ref={ref}+ onMouseMove={(e) => mouseX.set(e.pageX)}+ onMouseLeave={() => mouseX.set(Infinity)}+ {...props}+ className={cn(dockVariants({ className }), {+ "items-start": direction === "top",+ "items-center": direction === "middle",+ "items-end": direction === "bottom",+ })}+ >+ {renderChildren()}+ </motion.div>+ );+ },+);++Dock.displayName = "Dock";++export interface DockIconProps {+ size?: number;+ magnification?: number;+ distance?: number;+ mouseX?: any;+ className?: string;+ children?: React.ReactNode;+ props?: PropsWithChildren;+}++const DockIcon = ({+ size,+ magnification = DEFAULT_MAGNIFICATION,+ distance = DEFAULT_DISTANCE,+ mouseX,+ className,+ children,+ ...props+}: DockIconProps) => {+ const ref = useRef<HTMLDivElement>(null);++ const distanceCalc = useTransform(mouseX, (val: number) => {+ const bounds = ref.current?.getBoundingClientRect() ?? { x: 0, width: 0 };++ return val - bounds.x - bounds.width / 2;+ });++ let widthSync = useTransform(+ distanceCalc,+ [-distance, 0, distance],+ [40, magnification, 40],+ );++ let width = useSpring(widthSync, {+ mass: 0.1,+ stiffness: 150,+ damping: 12,+ });++ return (+ <motion.div+ ref={ref}+ style={{ width }}+ className={cn(+ "flex aspect-square cursor-pointer items-center justify-center rounded-full",+ className,+ )}+ {...props}+ >+ {children}+ </motion.div>+ );+};++DockIcon.displayName = "DockIcon";++export { Dock, DockIcon, dockVariants };diff --git a/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsx b/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsxindex c9c401577..5672f94df 100644--- a/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsx@@ -1,12 +1,14 @@-import { useEffect, useState } from 'react';-import localforage from 'localforage';-import { Conversation } from '../types/history';+import { useEffect, useState } from "react";+import localforage from "localforage";+import { SearchHistory } from "../types/history";-const HISTORY_KEY = 'screenpipe-conversation-history';+const HISTORY_KEY = "screenpipe-conversation-history";export function useConversationHistory() {- const [conversations, setConversations] = useState<Conversation[]>([]);- const [currentConversationId, setCurrentConversationId] = useState<string | null>(null);+ const [conversations, setConversations] = useState<SearchHistory[]>([]);+ const [currentConversationId, setCurrentConversationId] = useState<+ string | null+ >(null);const [isLoading, setIsLoading] = useState(true);useEffect(() => {@@ -15,26 +17,26 @@ export function useConversationHistory() {const loadConversations = async () => {try {- const stored = await localforage.getItem<Conversation[]>(HISTORY_KEY);+ const stored = await localforage.getItem<SearchHistory[]>(HISTORY_KEY);setConversations(stored || []);} catch (error) {- console.error('failed to load conversations:', error);+ console.error("failed to load conversations:", error);}setIsLoading(false);};- const saveConversations = async (updated: Conversation[]) => {+ const saveConversations = async (updated: SearchHistory[]) => {try {await localforage.setItem(HISTORY_KEY, updated);setConversations(updated);} catch (error) {- console.error('failed to save conversations:', error);+ console.error("failed to save conversations:", error);}};const addMessage = async (conversationId: string | null,- type: 'search' | 'ai',+ type: "search" | "ai",content: string,searchQuery?: any) => {@@ -43,20 +45,24 @@ export function useConversationHistory() {if (!conversationId) {// create new conversation- const newConversation: Conversation = {+ const newConversation: SearchHistory = {id: crypto.randomUUID(),- title: content.slice(0, 30) + (content.length > 30 ? '...' : ''),- createdAt: timestamp,- lastUpdatedAt: timestamp,- messages: [{- id: messageId,- type,- content,- timestamp,- searchQuery- }]+ query: content.slice(0, 30) + (content.length > 30 ? "..." : ""),+ timestamp,+ searchParams: {+ ...searchQuery,+ },+ results: [],+ messages: [+ {+ id: messageId,+ type,+ content,+ timestamp,+ },+ ],};-+const updated = [newConversation, ...conversations];await saveConversations(updated);setCurrentConversationId(newConversation.id);@@ -64,18 +70,21 @@ export function useConversationHistory() {}// add to existing conversation- const updated = conversations.map(conv => {+ const updated = conversations.map((conv) => {if (conv.id === conversationId) {return {...conv,lastUpdatedAt: timestamp,- messages: [...conv.messages, {- id: messageId,- type,- content,- timestamp,- searchQuery- }]+ messages: [+ ...conv.messages,+ {+ id: messageId,+ type,+ content,+ timestamp,+ searchQuery,+ },+ ],};}return conv;@@ -86,7 +95,7 @@ export function useConversationHistory() {};const deleteConversation = async (id: string) => {- const updated = conversations.filter(c => c.id !== id);+ const updated = conversations.filter((c) => c.id !== id);await saveConversations(updated);if (currentConversationId === id) {setCurrentConversationId(null);@@ -99,6 +108,6 @@ export function useConversationHistory() {setCurrentConversationId,addMessage,deleteConversation,- isLoading+ isLoading,};-}\ No newline at end of file+}diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 238f85aba..c7a5f7de7 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -86,6 +86,11 @@ tauri-plugin-global-shortcut = "2"tauri-plugin-single-instance = "2.0.0"tauri-plugin-updater = "2.0.0"+[target."cfg(target_os = \"macos\")".dependencies]+cocoa = "0.26.0"+objc = "0.2.7"+base64 = "0.22.1"+[features]cudart = []metal = []diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rsindex 414e61efa..0f277cafd 100644--- a/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -1,7 +1,4 @@-// #[tauri::command]-// pub fn has_screen_capture_access() -> bool {-// scap::has_permission()-// }+use serde_json::Value;use tauri::Manager;@@ -26,30 +23,6 @@ pub fn open_mic_preferences() {.expect("failed to open system preferences");}-#[allow(dead_code)]-#[tauri::command]-pub fn reset_screen_permissions() {- #[cfg(target_os = "macos")]- std::process::Command::new("tccutil")- .arg("reset")- .arg("ScreenCapture")- .arg("so.cap.desktop")- .spawn()- .expect("failed to reset screen permissions");-}--#[allow(dead_code)]-#[tauri::command]-pub fn reset_microphone_permissions() {- #[cfg(target_os = "macos")]- std::process::Command::new("tccutil")- .arg("reset")- .arg("Microphone")- .arg("so.cap.desktop")- .spawn()- .expect("failed to reset microphone permissions");-}-#[tauri::command]pub async fn load_pipe_config(pipe_name: String) -> Result<Value, String> {info!("Loading pipe config for {}", pipe_name);diff --git a/screenpipe-app-tauri/src-tauri/src/icons.rs b/screenpipe-app-tauri/src-tauri/src/icons.rsnew file mode 100644index 000000000..edbe0be4d--- /dev/null+++ b/screenpipe-app-tauri/src-tauri/src/icons.rs@@ -0,0 +1,85 @@+use base64::{engine::general_purpose::STANDARD, Engine};+use cocoa::base::id;+use cocoa::foundation::{NSData, NSString};+use objc::{class, msg_send, sel, sel_impl};+use serde::{Deserialize, Serialize};++#[derive(Debug, Serialize, Deserialize)]+pub struct AppIcon {+ pub base64: String,+ pub path: Option<String>,+}++#[tauri::command]+#[cfg(target_os = "macos")]+pub async fn get_app_icon(+ app_name: &str,+ app_path: Option<String>,+) -> Result<Option<AppIcon>, String> {+ // info!("getting icon for {}", app_name);++ unsafe {+ let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];++ let path = if let Some(path) = app_path {+ path+ } else {+ let ns_app_name = NSString::alloc(cocoa::base::nil).init_str(app_name);+ let path: id = msg_send![workspace, fullPathForApplication: ns_app_name];+ if path == cocoa::base::nil {+ return Ok(None);+ }+ let path: id = msg_send![path, UTF8String];+ std::ffi::CStr::from_ptr(path as *const _)+ .to_string_lossy()+ .into_owned()+ };++ let icon: id =+ msg_send![workspace, iconForFile:NSString::alloc(cocoa::base::nil).init_str(&path)];+ if icon == cocoa::base::nil {+ return Ok(None);+ }++ // Convert to PNG data+ let tiff_data: id = msg_send![icon, TIFFRepresentation];+ let image_rep: id = msg_send![class!(NSBitmapImageRep), imageRepWithData: tiff_data];+ let png_data: id =+ msg_send![image_rep, representationUsingType:4 properties:cocoa::base::nil];++ let length = NSData::length(png_data);+ let bytes = NSData::bytes(png_data);+ let data = std::slice::from_raw_parts(bytes as *const u8, length as usize);++ let base64 = STANDARD.encode(data);++ Ok(Some(AppIcon {+ base64,+ path: Some(path),+ }))+ }+}++#[tauri::command]+#[cfg(target_os = "windows")]+pub async fn get_app_icon(+ app_name: &str,+ app_path: Option<String>,+) -> Result<Option<AppIcon>, String> {+ // Windows: Extract icon from exe using Shell32+ // Convert to base64+ // Return AppIcon struct+ Ok(None)+}++#[tauri::command]+#[cfg(target_os = "linux")]+pub async fn get_app_icon(+ app_name: &str,+ app_path: Option<String>,+) -> Result<Option<AppIcon>, String> {+ // Linux: Check XDG icon themes+ // Convert to base64+ // Return AppIcon struct+ Ok(None)+}diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex 3ec95ff3f..79721f431 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -33,6 +33,7 @@ use tracing_subscriber::EnvFilter;use updates::start_update_check;use uuid::Uuid;mod analytics;+mod icons;use crate::analytics::start_analytics;use crate::llm_sidecar::LLMSidecar;@@ -44,7 +45,6 @@ mod sidecar;mod updates;pub use commands::open_screen_capture_preferences;pub use commands::reset_all_pipes;-pub use commands::reset_screen_permissions;pub use server::spawn_server;pub use sidecar::kill_all_sreenpipes;pub use sidecar::spawn_screenpipe;@@ -107,7 +107,6 @@ async fn main() {.invoke_handler(tauri::generate_handler![spawn_screenpipe,kill_all_sreenpipes,- reset_screen_permissions,open_screen_capture_preferences,load_pipe_config,save_pipe_config,@@ -116,6 +115,7 @@ async fn main() {llm_sidecar::stop_ollama_sidecar,commands::update_show_screenpipe_shortcut,commands::show_timeline,+ icons::get_app_icon]).setup(|app| {// Logging setupdiff --git a/screenpipe-app-tauri/src-tauri/src/updates.rs b/screenpipe-app-tauri/src-tauri/src/updates.rsindex a27c0c339..d091af183 100644--- a/screenpipe-app-tauri/src-tauri/src/updates.rs+++ b/screenpipe-app-tauri/src-tauri/src/updates.rs@@ -12,7 +12,6 @@ use tauri_plugin_updater::UpdaterExt;use tokio::sync::oneshot;use tokio::sync::Mutex;use tokio::time::interval;-use crate::llm_sidecar::stop_ollama_sidecar;pub struct UpdatesManager {interval: Duration,@@ -42,12 +41,14 @@ impl UpdatesManager {if let Some(update) = self.app.updater()?.check().await? {*self.update_available.lock().await = true;- #[cfg(target_os = "windows")] {+ #[cfg(target_os = "windows")]+ {self.update_menu_item.set_enabled(true)?;self.update_menu_item.set_text("update now")?;}- #[cfg(not(target_os = "windows"))] {+ #[cfg(not(target_os = "windows"))]+ {self.update_menu_item.set_enabled(false)?;self.update_menu_item.set_text("downloading latest version of screenpipe")?;@@ -65,7 +66,8 @@ impl UpdatesManager {}}- #[cfg(not(target_os = "windows"))] {+ #[cfg(not(target_os = "windows"))]+ {update.download_and_install(|_, _| {}, || {}).await?;*self.update_installed.lock().await = true;self.update_menu_item.set_enabled(true)?;@@ -90,14 +92,18 @@ impl UpdatesManager {});if rx.await? {+ #[cfg(target_os = "windows")]+ {+ use crate::llm_sidecar::stop_ollama_sidecar;- #[cfg(target_os = "windows")] {self.update_menu_item.set_enabled(false)?;self.update_menu_item.set_text("downloading latest version of screenpipe")?;if let Err(err) =- kill_all_sreenpipes(self.app.state::<SidecarState>(), self.app.clone()).await {+ kill_all_sreenpipes(self.app.state::<SidecarState>(), self.app.clone())+ .await+ {error!("Failed to kill sidecar: {}", err);}// llm sidecar only need to kill in windows@@ -116,9 +122,12 @@ impl UpdatesManager {// i think it shouldn't kill if we're in dev mode (on macos, windows need to kill)// bad UX: i use CLI and it kills my CLI because i updated app- #[cfg(not(target_os = "windows"))] {- if let Err(err) =- kill_all_sreenpipes(self.app.state::<SidecarState>(), self.app.clone()).await {+ #[cfg(not(target_os = "windows"))]+ {+ if let Err(err) =+ kill_all_sreenpipes(self.app.state::<SidecarState>(), self.app.clone())+ .await+ {error!("Failed to kill sidecar: {}", err);}}@@ -180,4 +189,4 @@ pub fn start_update_check(});Ok(updates_manager)-}\ No newline at end of file+}diff --git a/screenpipe-app-tauri/tsconfig.json b/screenpipe-app-tauri/tsconfig.jsonindex 9b8664c2a..7ee536cf7 100644--- a/screenpipe-app-tauri/tsconfig.json+++ b/screenpipe-app-tauri/tsconfig.json@@ -1,5 +1,6 @@{"compilerOptions": {+ "target": "ES2020","lib": ["dom","dom.iterable",diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 430fcb509..9e1706b7e 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1284,42 +1284,70 @@ async fn stream_frames_handler();let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel(100);- let cache = state.frame_cache.as_ref().unwrap().clone();- // Calculate duration in minutes between start and end time- let duration_minutes = (request.end_time - request.start_time).num_minutes().max(1) as i64;-- // Calculate center timestamp- let center_timestamp = request.start_time + (request.end_time - request.start_time) / 2;-- // Use a cancellation token to handle client disconnection- let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();-- // Spawn frame extraction task using get_frames- tokio::spawn({- let frame_tx = frame_tx.clone();- async move {- tokio::select! {- result = cache.get_frames(center_timestamp, duration_minutes, frame_tx, true) => {- if let Err(e) = result {- error!("frame extraction failed: {}", e);+ // Create a stream that will be used for both success and error cases+ let stream = async_stream::stream! {+ // Early validation of frame cache+ let cache = match state.frame_cache.as_ref() {+ Some(cache) => cache.clone(),+ None => {+ error!("frame cache not initialized");+ yield Ok(Event::default().data("{\"error\": \"frame cache not initialized\"}"));+ return;+ }+ };++ // Calculate duration in minutes between start and end time+ let duration_minutes = (request.end_time - request.start_time).num_minutes().max(1) as i64;++ // Calculate center timestamp+ let center_timestamp = request.start_time + (request.end_time - request.start_time) / 2;++ // Use a cancellation token to handle client disconnection+ let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();++ // Spawn frame extraction task using get_frames+ tokio::spawn({+ let frame_tx = frame_tx.clone();+ async move {+ tokio::select! {+ result = cache.get_frames(center_timestamp, duration_minutes, frame_tx.clone(), true) => {+ if let Err(e) = result {+ error!("frame extraction failed: {}", e);+ // Send error to client+ let _ = frame_tx.send(TimeSeriesFrame {+ timestamp: Utc::now(),+ frame_data: vec![],+ error: Some(format!("frame extraction failed: {}", e)),+ }).await;+ }+ }+ _ = cancel_rx => {+ debug!("client disconnected, stopping frame stream");}- }- _ = cancel_rx => {- debug!("client disconnected, stopping frame stream");}}- }- });+ });- let stream = async_stream::stream! {let _cancel_guard = scopeguard::guard(cancel_tx, |tx| {let _ = tx.send(()); // Signal cancellation when stream is dropped});while let Some(timeseries_frame) = frame_rx.recv().await {- if let Ok(json) = serde_json::to_string(&StreamTimeSeriesResponse::from(timeseries_frame)) {- yield Ok(Event::default().data(json));+ // Handle potential error in the frame+ if let Some(error) = timeseries_frame.error {+ yield Ok(Event::default().data(format!("{{\"error\": \"{}\"}}", error)));+ break; // Stop streaming on error+ }++ // Convert frame to response and send+ match serde_json::to_string(&StreamTimeSeriesResponse::from(timeseries_frame)) {+ Ok(json) => yield Ok(Event::default().data(json)),+ Err(e) => {+ error!("failed to serialize frame: {}", e);+ yield Ok(Event::default().data(format!("{{\"error\": \"failed to serialize frame: {}\"}}", e)));+ break;+ }}}};diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex b7aecfd33..96574f34e 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -24,6 +24,7 @@ type FrameChannel = mpsc::Sender<TimeSeriesFrame>;pub struct TimeSeriesFrame {pub timestamp: DateTime<Utc>,pub frame_data: Vec<DeviceFrame>,+ pub error: Option<String>,}#[derive(Debug, Clone)]@@ -425,6 +426,7 @@ impl FrameCache {let mut timeseries_frame = TimeSeriesFrame {timestamp: chunk.timestamp,frame_data: Vec::new(),+ error: None,};for device_data in &chunk.ocr_entries {@@ -602,9 +604,11 @@ async fn extract_frame(// Calculate frame interval based on target FPSlet frame_interval = (source_fps / 0.1).round() as i64; // Using 0.1 as target FPS-- debug!("extracting frames with interval {} (source: {}fps, target: {}fps)",- frame_interval, source_fps, 0.1);++ debug!(+ "extracting frames with interval {} (source: {}fps, target: {}fps)",+ frame_interval, source_fps, 0.1+ );// Calculate which frames to extractlet frame_positions: Vec<String> = tasks@@ -612,26 +616,29 @@ async fn extract_frame(.filter_map(|(frame, _)| {// Only select frames that align with our target FPSif frame.offset_index as i64 % frame_interval == 0 {- Some(format!("select=eq(n\\,{})", frame.offset_index))+ Some(frame.offset_index.to_string())} else {None}}).collect();-+if frame_positions.is_empty() {debug!("no frames to extract after applying fps filter");return Ok(0);}- let select_filter = frame_positions.join("+");+ // Join frame numbers with commas and wrap in select filter+ let select_filter = format!("select='eq(n,{})'", frame_positions.join(")+eq(n,"));let mut cmd = Command::new(&ffmpeg);cmd.args(["-i",&video_file_path,"-vf",- &select_filter,+ &format!("{},format=yuv420p,scale=iw:ih", select_filter),+ "-strict",+ "unofficial","-c:v","mjpeg","-q:v",@@ -698,6 +705,7 @@ async fn extract_frame(// Then send the frameframe_tx.send(TimeSeriesFrame {+ error: None,timestamp: chunk.timestamp,frame_data: vec![DeviceFrame {device_id: device_data.device_name.clone(),@@ -794,18 +802,18 @@ fn parse_timestamp(timestamp_str: &str) -> Result<DateTime<Utc>> {struct OrderedFrameStreamer {buffer: BTreeMap<DateTime<Utc>, Vec<TimeSeriesFrame>>,- window_size: Duration,- last_sent: Option<DateTime<Utc>>,+ bucket_size: Duration,+ current_bucket: Option<DateTime<Utc>>,tx: mpsc::Sender<TimeSeriesFrame>,descending: bool,}impl OrderedFrameStreamer {- fn new(tx: mpsc::Sender<TimeSeriesFrame>, window_size: Duration, descending: bool) -> Self {+ fn new(tx: mpsc::Sender<TimeSeriesFrame>, bucket_size: Duration, descending: bool) -> Self {Self {buffer: BTreeMap::new(),- window_size,- last_sent: None,+ bucket_size,+ current_bucket: None,tx,descending,}@@ -813,9 +821,16 @@ impl OrderedFrameStreamer {async fn push(&mut self, frame: TimeSeriesFrame) -> Result<()> {let ts = frame.timestamp;++ // Initialize current_bucket if not set+ if self.current_bucket.is_none() {+ self.current_bucket = Some(ts);+ debug!("initialized first bucket at: {}", ts);+ }+self.buffer.entry(ts).or_default().push(frame);- // Sort frames within each timestamp by device_id for consistency+ // Sort frames within timestamp for consistencyif let Some(frames) = self.buffer.get_mut(&ts) {frames.sort_by(|a, b| {a.frame_data@@ -825,93 +840,87 @@ impl OrderedFrameStreamer {});}- self.flush_window().await+ // Flush completed buckets+ self.flush_completed_buckets().await}- async fn flush_window(&mut self) -> Result<()> {- if self.last_sent.is_none() && !self.buffer.is_empty() {- self.last_sent = if self.descending {- self.buffer.keys().next_back().copied()- } else {- self.buffer.keys().next().copied()- };- }-- let Some(last_sent) = self.last_sent else {+ async fn flush_completed_buckets(&mut self) -> Result<()> {+ let Some(current_bucket) = self.current_bucket else {return Ok(());};- // Determine the window range based on direction- let window_range = if self.descending {- (last_sent - self.window_size)..=last_sent+ // Determine bucket range+ let bucket_range = if self.descending {+ (current_bucket - self.bucket_size)..=current_bucket} else {- last_sent..=(last_sent + self.window_size)+ current_bucket..=(current_bucket + self.bucket_size)};- // Collect frames that are ready to be sent- let mut ready_frames = Vec::new();- for (_, frames) in self.buffer.range(window_range) {- ready_frames.extend(frames.iter().cloned());- }+ // Find frames ready to be sent (outside current bucket)+ let mut ready_timestamps: Vec<DateTime<Utc>> = self.buffer+ .keys()+ .filter(|ts| !bucket_range.contains(ts))+ .copied()+ .collect();- // Sort all collected frames- ready_frames.sort_by_key(|frame| {+ if !ready_timestamps.is_empty() {+ // Sort timestamps based on directionif self.descending {- std::cmp::Reverse(frame.timestamp)+ ready_timestamps.sort_by(|a, b| b.cmp(a));} else {- std::cmp::Reverse(std::cmp::Reverse(frame.timestamp)).0+ ready_timestamps.sort();}- });- // Send frames and update buffer- for frame in ready_frames {- let ts = frame.timestamp;- self.tx.send(frame).await?;- self.buffer.remove(&ts);- self.last_sent = Some(ts);+ // Send frames and update buffer+ for ts in ready_timestamps {+ if let Some(frames) = self.buffer.remove(&ts) {+ for frame in frames {+ self.tx.send(frame).await?;+ }+ }+ }++ // Update current bucket+ self.current_bucket = self.buffer.keys().next().copied();+ debug!("flushed bucket, new current bucket: {:?}", self.current_bucket);}Ok(())}async fn finish(self) -> Result<()> {- let mut all_frames = Vec::new();-- // Collect all remaining frames- for frames in self.buffer.values() {- all_frames.extend(frames.iter().cloned());+ // Flush any remaining frames in buffer+ let mut remaining: Vec<TimeSeriesFrame> = self.buffer+ .into_values()+ .flatten()+ .collect();++ // Sort remaining frames+ if self.descending {+ remaining.sort_by_key(|frame| std::cmp::Reverse(frame.timestamp));+ } else {+ remaining.sort_by_key(|frame| frame.timestamp);}- // Sort them according to the desired order- all_frames.sort_by_key(|frame| {- if self.descending {- std::cmp::Reverse(frame.timestamp)- } else {- std::cmp::Reverse(std::cmp::Reverse(frame.timestamp)).0- }- });-- // Send all remaining frames- for frame in all_frames {+ // Send remaining frames+ for frame in remaining {self.tx.send(frame).await?;}+ debug!("streamer finished, sent all remaining frames");Ok(())}}async fn get_video_fps(ffmpeg_path: &PathBuf, video_path: &str) -> Result<f64> {let output = Command::new(ffmpeg_path)- .args([- "-i",- video_path,- ])+ .args(["-i", video_path]).output().await?;// ffmpeg outputs metadata to stderr by designlet metadata = String::from_utf8_lossy(&output.stderr);-+// Look for fps info in patterns like: "23.98 fps" or "30 fps" or "29.97 fps"let fps = metadata.lines()